Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions examples/mastra-chat/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
43 changes: 43 additions & 0 deletions examples/mastra-chat/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# mastra-chat

An [OpenUI](https://openui.com) example showing how to wire a [Mastra](https://mastra.ai) agent backend to OpenUI's generative UI frontend.

## What this demonstrates

- Using `mastraAdapter` as the `streamProtocol` on OpenUI's `ChatProvider`
- Using `mastraMessageFormat` to keep the chat history compatible with Mastra's expected message shape
- A real Mastra `Agent` with `createTool` tools (weather and stock price) running in a Next.js API route

## Getting started

1. Copy the example environment file and add your OpenAI key:

```bash
cp .env.example .env.local
# then edit .env.local and set OPENAI_API_KEY=sk-...
```

2. Install dependencies from the monorepo root:

```bash
pnpm install
```

3. Run the dev server from this directory:

```bash
pnpm dev
```

Open [http://localhost:3000](http://localhost:3000) to see the chat interface.

## How it works

The frontend (`src/app/page.tsx`) passes `streamProtocol={mastraAdapter()}` and `mastraMessageFormat` to `<FullScreen />`. Mastra handles the agentic loop (including multi-step tool calls) on the server, and the adapter converts the AI SDK SSE stream into OpenUI's internal event format.

To add more tools, define them with `createTool` in `src/app/api/chat/route.ts` and pass them to the `Agent`.

## Learn more

- [OpenUI documentation](https://openui.com/docs)
- [Mastra documentation](https://mastra.ai/docs)
18 changes: 18 additions & 0 deletions examples/mastra-chat/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
import { defineConfig, globalIgnores } from "eslint/config";

const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);

export default eslintConfig;
8 changes: 8 additions & 0 deletions examples/mastra-chat/next.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
turbopack: {},
transpilePackages: ["@openuidev/react-ui", "@openuidev/react-headless", "@openuidev/react-lang"],
};

export default nextConfig;
35 changes: 35 additions & 0 deletions examples/mastra-chat/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "mastra-chat",
"version": "0.1.0",
"private": true,
"scripts": {
"generate:prompt": "pnpm --filter @openuidev/cli build && node ../../packages/openui-cli/dist/index.js generate src/library.ts --out src/generated/system-prompt.txt",
"dev": "pnpm generate:prompt && next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@ag-ui/mastra": "^1.0.1",
"@mastra/core": "1.15.0",
"@openuidev/react-headless": "workspace:*",
"@openuidev/react-lang": "workspace:*",
"@openuidev/react-ui": "workspace:*",
"lucide-react": "^0.575.0",
"next": "16.1.6",
"react": "19.2.3",
"react-dom": "19.2.3",
"zod": "^3.23.0"
},
"devDependencies": {
"@openuidev/cli": "workspace:*",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.1.6",
"tailwindcss": "^4",
"typescript": "^5"
}
}
7 changes: 7 additions & 0 deletions examples/mastra-chat/postcss.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};

export default config;
216 changes: 216 additions & 0 deletions examples/mastra-chat/src/app/api/chat/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
import { MastraAgent } from "@ag-ui/mastra";
import { Agent } from "@mastra/core/agent";
import { createTool } from "@mastra/core/tools";
import { EventType, type Message, type TextInputContent } from "@openuidev/react-headless";
import { readFileSync } from "fs";
import { NextRequest } from "next/server";
import { join } from "path";
import { z } from "zod";

const systemPromptFile = readFileSync(
join(process.cwd(), "src/generated/system-prompt.txt"),
"utf-8",
);

const getWeather = createTool({
id: "get_weather",
description: "Get current weather for a city.",
inputSchema: z.object({ location: z.string().describe("City name") }),
execute: async ({ location }) => {
const knownTemps: Record<string, number> = {
tokyo: 22,
"san francisco": 18,
london: 14,
"new york": 25,
paris: 19,
sydney: 27,
mumbai: 33,
berlin: 16,
};
const temp = knownTemps[location.toLowerCase()] ?? Math.floor(Math.random() * 30 + 5);
return { location, temperature_celsius: temp, condition: "Clear" };
},
});

const getStockPrice = createTool({
id: "get_stock_price",
description: "Get current stock price for a ticker symbol.",
inputSchema: z.object({ symbol: z.string().describe("Ticker symbol, e.g. AAPL") }),
execute: async ({ symbol }) => {
const prices: Record<string, number> = {
AAPL: 189.84,
GOOGL: 141.8,
TSLA: 248.42,
MSFT: 378.91,
NVDA: 875.28,
};
const s = symbol.toUpperCase();
const price = prices[s] ?? Math.floor(Math.random() * 500 + 50);
return { symbol: s, price };
},
});

type AgentRunInput = Parameters<MastraAgent["run"]>[0];
type AgentMessage = AgentRunInput["messages"][number];

const agentTools: AgentRunInput["tools"] = [
{
name: getWeather.id,
description: getWeather.description,
parameters: getWeather.inputSchema,
},
{
name: getStockPrice.id,
description: getStockPrice.description,
parameters: getStockPrice.inputSchema,
},
];

function getAgent() {
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
throw new Error(
"OPENAI_API_KEY is not set. Please provide it in your environment variables to run this example.",
);
}

const baseAgent = new Agent({
id: "openui-agent",
name: "OpenUI Agent",
instructions: `You are a helpful assistant. Use tools when relevant and help the user with their requests. Always format your responses cleanly.\n\n${systemPromptFile}`,
model: {
id: (process.env.OPENAI_MODEL as `${string}/${string}`) || "openai/gpt-4o",
apiKey: apiKey,
url: process.env.OPENAI_BASE_URL || "https://api.openai.com/v1",
},
tools: { getWeather, getStockPrice },
});

return new MastraAgent({
agent: baseAgent,
resourceId: "chat-user",
});
}

function toAgentMessage(message: Message): AgentMessage | null {
switch (message.role) {
case "developer":
case "system":
return {
id: message.id,
role: message.role,
content: message.content,
};
case "user":
return {
id: message.id,
role: "user",
content:
typeof message.content === "string"
? message.content
: message.content.find(
(content): content is TextInputContent => content.type === "text",
)?.text || "",
};
case "assistant":
return {
id: message.id,
role: "assistant",
content: message.content,
toolCalls: message.toolCalls,
};
case "tool":
return {
id: message.id,
role: "tool",
content: message.content,
toolCallId: message.toolCallId,
error: message.error,
};
default:
return null;
}
}

export async function POST(req: NextRequest) {
try {
const { messages, threadId }: { messages: Message[]; threadId: string } = await req.json();

const convertedMessages = messages
.map(toAgentMessage)
.filter((message): message is AgentMessage => message !== null);

const agent = getAgent();
const encoder = new TextEncoder();

const readable = new ReadableStream({
start(controller) {
const subscription = agent
.run({
messages: convertedMessages,
threadId,
runId: crypto.randomUUID(),
tools: agentTools,
context: [],
})
.subscribe({
next: (event) => {
if (
(event.type === EventType.TEXT_MESSAGE_CHUNK ||
event.type === EventType.TEXT_MESSAGE_CONTENT) &&
event.delta
) {
const translatedEvent = {
type: EventType.TEXT_MESSAGE_CONTENT,
messageId: event.messageId || "current-message",
delta: event.delta,
};
controller.enqueue(encoder.encode(`data: ${JSON.stringify(translatedEvent)}\n\n`));
} else if (event.type === EventType.RUN_ERROR) {
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({
type: EventType.RUN_ERROR,
message: event.message || "An error occurred during the agent run",
})}\n\n`,
),
);
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
}
},
complete: () => {
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
controller.close();
},
error: (error: unknown) => {
const message =
error instanceof Error ? error.message : "Unknown Mastra stream error";
console.error("Mastra stream error:", error);
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ error: message })}\n\n`));
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
controller.close();
},
});

req.signal.addEventListener("abort", () => {
subscription.unsubscribe();
});
},
});

return new Response(readable, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
},
});
} catch (error: unknown) {
const message = error instanceof Error ? error.message : "Unknown route error";
console.error("Route error:", error);
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
}
1 change: 1 addition & 0 deletions examples/mastra-chat/src/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@import "tailwindcss";
22 changes: 22 additions & 0 deletions examples/mastra-chat/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ThemeProvider } from "@/hooks/use-system-theme";
import type { Metadata } from "next";
import "./globals.css";

export const metadata: Metadata = {
title: "OpenUI Chat",
description: "Generative UI Chat with OpenAI SDK",
};

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body>
<ThemeProvider>{children}</ThemeProvider>
</body>
</html>
);
}
Loading