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
35 changes: 35 additions & 0 deletions examples/google-adk/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

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

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

# vercel
.vercel

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

An [OpenUI](https://openui.com) example showing how to wire a
[Google Agent Development Kit (ADK)](https://github.com/google/adk-js) agent
(TypeScript) to OpenUI's generative UI frontend.

## What this demonstrates

- A Google ADK `Agent` with a `FunctionTool` (weather) running inside a Next.js
API route via an `InMemorySessionService` + `Runner`
- Bridging ADK's `runAsync` event stream into OpenAI-style chat-completion SSE
chunks so OpenUI's `openAIAdapter()` can parse them
- Rendering the streamed OpenUI Lang with OpenUI's `<AgentInterface />` and the
built-in `openuiChatLibrary`

The ADK agent is prompted with OpenUI's generated system prompt
(`src/generated/system-prompt.txt`), so its replies are OpenUI Lang that the
frontend renders as live generative UI (cards, tables, forms, charts…).

## Getting started

1. Create a `.env.local` file with your Gemini key
(get a free one at https://aistudio.google.com/apikey):

```bash
echo "GEMINI_API_KEY=your-key-here" > .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) and try a starter such as
"What's the weather like in Tokyo right now?".

## How it works

- `src/agent.ts` defines the `get_weather` tool and a `createAgent()` builder
that appends OpenUI's generated system prompt to the agent's instruction.
- `src/app/api/chat/route.ts` runs the agent with a `Runner`, keys ADK sessions
by chat `threadId` (so multi-turn history is preserved), and streams the
assistant text as OpenAI chat-completion SSE chunks.
- `src/app/page.tsx` renders `<AgentInterface />`, sending `{ messages, threadId }`
to `/api/chat` and parsing the stream with `openAIAdapter()`.

The `dev` script regenerates `src/generated/system-prompt.txt` from
`src/library.ts` before starting Next.js (`pnpm generate:prompt`). Re-run it
after changing the component library.

To add more tools, define them with `FunctionTool` in `src/agent.ts` and pass
them to the `Agent`.

## Learn more

- [OpenUI documentation](https://openui.com/docs)
- [Google ADK for TypeScript](https://github.com/google/adk-js)
20 changes: 20 additions & 0 deletions examples/google-adk/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
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",
// Generated prompt file.
"src/generated/**",
]),
]);

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

const nextConfig: NextConfig = {
turbopack: {},
// @google/adk is a Node.js library; keep it out of the client/server bundle
// so it loads from node_modules at runtime in the Node.js API route.
serverExternalPackages: ["@google/adk"],
};

export default nextConfig;
34 changes: 34 additions & 0 deletions examples/google-adk/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "google-adk-chat",
"version": "0.1.0",
"private": true,
"description": "OpenUI generative-UI chat backed by a Google ADK (TypeScript) agent.",
"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": {
"@google/adk": "^1.3.0",
"@openuidev/react-headless": "workspace:*",
"@openuidev/react-lang": "workspace:*",
"@openuidev/react-ui": "workspace:*",
"next": "16.2.6",
"react": "19.2.3",
"react-dom": "19.2.3",
"zod": "^4.0.0"
},
"devDependencies": {
"@openuidev/cli": "workspace:*",
"@tailwindcss/postcss": "^4",
"@types/node": "catalog:",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.2.6",
"tailwindcss": "^4",
"typescript": "^5"
}
}
7 changes: 7 additions & 0 deletions examples/google-adk/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;
50 changes: 50 additions & 0 deletions examples/google-adk/src/agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Agent, FunctionTool } from "@google/adk";
import { z } from "zod";

/**
* A tiny custom tool. The LLM decides when to call it based on the
* `description` and `parameters` schema below.
*/
export const getWeather = new FunctionTool({
name: "get_weather",
description: "Get the current weather for a given city.",
parameters: z.object({
city: z.string().describe('The city to get the weather for, e.g. "Tokyo".'),
}),
execute: ({ city }) => {
// Hard-coded so the demo runs without any external weather API.
const table: Record<string, { condition: string; temperature_celsius: number }> = {
tokyo: { condition: "Sunny", temperature_celsius: 24 },
london: { condition: "Rainy", temperature_celsius: 14 },
"san francisco": { condition: "Foggy", temperature_celsius: 17 },
"new york": { condition: "Cloudy", temperature_celsius: 21 },
paris: { condition: "Clear", temperature_celsius: 19 },
sydney: { condition: "Sunny", temperature_celsius: 27 },
};
const key = city.toLowerCase();
const data = table[key];
if (!data) {
return { city, error: "No weather data for this city." };
}
return { city, ...data };
},
});

/**
* Builds the weather assistant. The generated OpenUI system prompt is appended
* to the base instruction so the model replies with OpenUI Lang that the
* frontend renders as generative UI.
*/
export function createAgent(genUISystemPrompt: string) {
return new Agent({
name: "weather_assistant",
model: process.env.GEMINI_MODEL || "gemini-flash-latest",
description: "A helpful assistant that can report the weather.",
instruction:
"You are a friendly assistant. When the user asks about the weather, " +
"use the get_weather tool before answering. Help the user with any other " +
"requests too.\n\n" +
genUISystemPrompt,
tools: [getWeather],
});
}
153 changes: 153 additions & 0 deletions examples/google-adk/src/app/api/chat/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { InMemorySessionService, Runner, StreamingMode } from "@google/adk";
import { readFileSync } from "fs";
import { NextRequest } from "next/server";
import { join } from "path";
import { createAgent } from "@/agent";

// @google/adk relies on Node APIs, so pin this route to the Node.js runtime.
export const runtime = "nodejs";

const APP_NAME = "openui-adk-chat";
const USER_ID = "demo-user";

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

// A single Runner + in-memory session store, shared across requests. Sessions
// are keyed by the chat threadId so multi-turn history is preserved for the
// lifetime of the server process.
const sessionService = new InMemorySessionService();
const runner = new Runner({
appName: APP_NAME,
agent: createAgent(systemPrompt),
sessionService,
});
const sessions = new Map<string, string>();

// ----- AG-UI message helpers -----
interface AGUIMessage {
role: string;
content?: string | Array<{ type?: string; text?: string }>;
}

function messageText(message: AGUIMessage | undefined): string {
if (!message?.content) return "";
if (typeof message.content === "string") return message.content;
return message.content
.map((part) => (typeof part.text === "string" ? part.text : ""))
.join("");
}

async function ensureSession(threadId: string): Promise<string> {
const existing = sessions.get(threadId);
if (existing) return existing;
const session = await sessionService.createSession({ appName: APP_NAME, userId: USER_ID });
sessions.set(threadId, session.id);
return session.id;
}

// ----- OpenAI chat-completion SSE chunk helpers (parsed by openAIAdapter) -----
function contentChunk(id: string, content: string): string {
const payload = {
id,
object: "chat.completion.chunk",
choices: [{ index: 0, delta: { content }, finish_reason: null }],
};
return `data: ${JSON.stringify(payload)}\n\n`;
}

function stopChunk(id: string): string {
const payload = {
id,
object: "chat.completion.chunk",
choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
};
return `data: ${JSON.stringify(payload)}\n\n`;
}

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

const lastUser = [...(messages ?? [])].reverse().find((m) => m.role === "user");
const prompt = messageText(lastUser);
if (!prompt) {
return new Response(JSON.stringify({ error: "No user message provided" }), {
status: 400,
headers: { "Content-Type": "application/json" },
});
}

const sessionId = await ensureSession(threadId || "default");
const encoder = new TextEncoder();
const responseId = `adk-${sessionId}`;

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

try {
// Track whether we've streamed partial deltas. When ADK is in SSE
// mode it emits incremental partial events followed by a final,
// aggregated (non-partial) event carrying the full text. Streaming
// both would duplicate the message, so we skip the final aggregate
// whenever partials were already sent.
let sawPartial = false;

for await (const event of runner.runAsync({
userId: USER_ID,
sessionId,
newMessage: { parts: [{ text: prompt }] },
runConfig: { streamingMode: StreamingMode.SSE },
abortSignal: req.signal,
})) {
const parts = event.content?.parts ?? [];
const text = parts
.map((part) => (typeof part.text === "string" ? part.text : ""))
.join("");

if (!text) continue;

if (event.partial) {
sawPartial = true;
controller.enqueue(encoder.encode(contentChunk(responseId, text)));
} else if (!sawPartial) {
controller.enqueue(encoder.encode(contentChunk(responseId, text)));
}
}
} catch (error) {
if (!req.signal.aborted) {
console.error("ADK stream error:", error);
}
} finally {
close();
}
},
});

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" },
});
}
}
2 changes: 2 additions & 0 deletions examples/google-adk/src/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@import "tailwindcss";
@import "@openuidev/react-ui/styles/index.css";
Loading
Loading