Skip to content
Merged
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
45 changes: 45 additions & 0 deletions examples/mastra-chat/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# 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 using the [AG-UI protocol](https://docs.ag-ui.com).

## What this demonstrates

- Using `agUIAdapter()` as the `streamProtocol` on OpenUI's `<FullScreen />` component
- A Mastra `Agent` with `createTool` tools (weather and stock price) running in a Next.js API route
- Streaming AG-UI protocol events from the server to the client via SSE

## Getting started

1. Create a `.env.local` file with your OpenAI key:

```bash
echo "OPENAI_API_KEY=sk-..." > .env.local
```

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 server (`src/app/api/chat/route.ts`) wraps a Mastra `Agent` with `@ag-ui/mastra`'s `MastraAgent`, which emits AG-UI protocol events. These events are serialized as SSE and streamed to the client.

The frontend (`src/app/page.tsx`) uses `agUIAdapter()` from `@openuidev/react-headless` as the `streamProtocol` for the `<FullScreen />` component. The adapter parses the SSE stream into internal chat events that drive the UI.

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)
- [AG-UI protocol](https://docs.ag-ui.com)
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;
36 changes: 36 additions & 0 deletions examples/mastra-chat/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"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/core": "^0.0.45",
"@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;
127 changes: 127 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,127 @@
import { MastraAgent } from "@ag-ui/mastra";
import { Agent } from "@mastra/core/agent";
import { createTool } from "@mastra/core/tools";
import type { Message } from "@ag-ui/core";
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",
);

// ========== Mock tools ==========
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 };
},
});
// ================================

const agent = new MastraAgent({
agent: 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: process.env.OPENAI_API_KEY,
url: process.env.OPENAI_BASE_URL || "https://api.openai.com/v1",
},
tools: { getWeather, getStockPrice },
}),
resourceId: "chat-user",
});

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

const readable = new ReadableStream({
start(controller) {
let closed = false;
const close = () => {
if (closed) return;
closed = true;
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
controller.close();
};

const subscription = agent
.run({
messages,
threadId,
runId: crypto.randomUUID(),
tools: [],
context: [],
})
.subscribe({
next: (event) => {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
},
complete: close,
error: (error: Error) => {
const msg = error.message;
console.error("Mastra stream error:", error);
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ error: msg })}\n\n`));
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>
);
}
49 changes: 49 additions & 0 deletions examples/mastra-chat/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"use client";
import "@openuidev/react-ui/components.css";

import { useTheme } from "@/hooks/use-system-theme";
import { agUIAdapter } from "@openuidev/react-headless";
import { FullScreen } from "@openuidev/react-ui";
import { openuiChatLibrary } from "@openuidev/react-ui/genui-lib";

export default function Page() {
const mode = useTheme();

return (
<div className="h-screen w-screen overflow-hidden relative">
<FullScreen
processMessage={async ({ messages, threadId, abortController }) => {
return fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages, threadId }),
signal: abortController.signal,
});
}}
streamProtocol={agUIAdapter()}
componentLibrary={openuiChatLibrary}
agentName="OpenUI + Mastra Chat"
theme={{ mode }}
conversationStarters={{
variant: "short",
options: [
{
displayText: "Weather in Tokyo",
prompt: "What's the weather like in Tokyo right now?",
},
{ displayText: "AAPL stock price", prompt: "What's the current Apple stock price?" },
{
displayText: "Contact form",
prompt: "Build me a contact form with name, email, topic, and message fields.",
},
{
displayText: "Data table",
prompt:
"Show me a table of the top 5 programming languages by popularity with year created.",
},
],
}}
/>
</div>
);
}
Loading
Loading