A2UI Launched: Full CopilotKit support at launch!

A2UI Launched: CopilotKit has partnered with Google to deliver full support in both CopilotKit and AG-UI!

Check it out
LogoLogo
  • Overview
  • Integrations
  • API Reference
  • Copilot Cloud
Slanted end borderSlanted end border
Slanted start borderSlanted start border
Select integration...

Please select an integration to view the sidebar content.

IntegrationsMastraGenerative ui

Agent State

Render the state of your agent with custom UI components.

What is this?

All Mastra Agents are stateful through working memory. This means that as your agent progresses, working memory is preserved across the session. CopilotKit allows you to render this state in your application with custom UI components, which we call Agentic Generative UI.

When should I use this?

Rendering the state of your agent in the UI is useful when you want to provide the user with feedback about the overall state of a session. A great example of this is a situation where a user and an agent are working together to solve a problem. The agent can store a draft in its working memory which is then rendered in the UI.

Implementation

Run and connect your agent

You'll need to run your agent and connect it to CopilotKit before proceeding.

If you don't already have CopilotKit and your agent connected, choose one of the following options:

Set up your agent with working memory

Create your Mastra agent with working memory. Here's a complete example that tracks searches:

src/mastra/agents/index.ts
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { LibSQLStore } from "@mastra/libsql";
import { z } from "zod";
import { Memory } from "@mastra/memory";
import { createTool } from "@mastra/core/tools";

// Define the agent state schema
const AgentStateSchema = z.object({
  searches: z.array(
    z.object({
      query: z.string(),
      done: z.boolean(),
    })
  ).default([]),
});

export type AgentState = z.infer<typeof AgentStateSchema>;

// Create tools that update working memory
const addSearch = createTool({
  id: "addSearch",
  inputSchema: z.object({
    query: z.string(),
  }),
  description: "Add a search to the agent's list of searches",
  execute: async ({ context: { query } }) => {
    // Tool implementation - working memory is automatically updated
    return { success: true, query };
  },
});

export const searchAgent = new Agent({
  name: "Search Agent",
  model: openai("gpt-4o"),
  instructions: `
    You are a helpful assistant for storing searches.

    IMPORTANT:
    - Use the addSearch tool to add a search to the agent's state
    - ONLY USE THE addSearch TOOL ONCE FOR A GIVEN QUERY
  `,
  tools: {
    addSearch,
  },
  memory: new Memory({
    storage: new LibSQLStore({ url: "file::memory:" }),
    options: {
      workingMemory: {
        enabled: true,
        schema: AgentStateSchema,
      },
    },
  }),
});

Render state of the agent in the chat

Now we can utilize useCoAgentStateRender to render the state of our agent in the chat.

app/page.tsx
// ...
import { useCoAgentStateRender } from "@copilotkit/react-core";
// ...

// Define the state of the agent, should match the working memory of your Mastra Agent.
type AgentState = {
  searches: {
    query: string;
    done: boolean;
  }[];
};

function YourMainContent() {
  // ...

  // styles omitted for brevity
  useCoAgentStateRender<AgentState>({
    name: "searchAgent", // MUST match the agent name in your Mastra instance
    render: ({ state }) => (
      <div>
        {state.searches?.map((search, index) => (
          <div key={index}>
            {search.done ? "✅" : "❌"} {search.query}{search.done ? "" : "..."}
          </div>
        ))}
      </div>
    ),
  });

  // ...

  return <div>...</div>;
}

Important

The name parameter must exactly match the agent name you defined in your Mastra instance (e.g., searchAgent from above).

Render state outside of the chat

You can also render the state of your agent outside of the chat. This is useful when you want to render the state of your agent anywhere other than the chat.

app/page.tsx
import { useCoAgent } from "@copilotkit/react-core"; 
// ...

// Define the state of the agent, should match the working memory of your Mastra Agent.
type AgentState = {
  searches: {
    query: string;
    done: boolean;
  }[];
};

function YourMainContent() {
  // ...

  const { state } = useCoAgent<AgentState>({
    name: "searchAgent", // MUST match the agent name in your Mastra instance
  })

  // ...

  return (
    <div>
      {/* ... */}
      <div className="flex flex-col gap-2 mt-4">
        {state.searches?.map((search, index) => (
          <div key={index} className="flex flex-row">
            {search.done ? "✅" : "❌"} {search.query}
          </div>
        ))}
      </div>
    </div>
  )
}

Important

The name parameter must exactly match the agent name you defined in your Mastra instance (e.g., searchAgent from above).

Give it a try!

You've now created a component that will render the agent's working memory in the chat.

PREV
Mastra
Slanted end borderSlanted end border
Slanted start borderSlanted start border
NEXT
Prebuilt Copilot UI

On this page

What is this?
When should I use this?
Implementation
Run and connect your agent
Set up your agent with working memory
Render state of the agent in the chat
Render state outside of the chat
Give it a try!