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
12 changes: 12 additions & 0 deletions examples/cookbook/vercel-voice-agent/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
MOSS_PROJECT_ID=your-project-id
MOSS_PROJECT_KEY=your-project-key
MOSS_INDEX_NAME=your-index-name

# Vercel AI Gateway — generates WebSocket tokens + routes to gpt-realtime-2
# Get key: https://vercel.com/dashboard/ai-gateway
AI_GATEWAY_API_KEY=your-vercel-ai-gateway-key

# Demo auth — set both to the same value; omit to disable the check locally
DEMO_SECRET=change-me
NEXT_PUBLIC_DEMO_SECRET=change-me
ALLOW_UNAUTHENTICATED_DEMO=true
49 changes: 49 additions & 0 deletions examples/cookbook/vercel-voice-agent/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# MOSS Voice Agent — Vercel AI Gateway

Realtime voice agent using [Vercel AI Gateway](https://vercel.com/blog/realtime-voice-agents-on-ai-gateway) with MOSS as the knowledge base. Speak a question — the agent searches your MOSS index and answers out loud.

## Architecture

```text
Browser (useRealtime) ──WebSocket── Vercel AI Gateway ── gpt-realtime-2
│ │
│ tool call: search_knowledge_base │
└─── POST /api/token ───────────────►│
MOSS index (local)
```

- `POST /api/token` (empty body) — mints a short-lived WebSocket token via the gateway
- `POST /api/token` (`{ query }`) — executes MOSS search; uses local in-memory index loaded at startup

> **Security note:** `/api/token` is unauthenticated for demo purposes. Before deploying publicly, add a session/cookie check so arbitrary callers cannot mint Gateway tokens or query your index.

## Setup

### 1. Install dependencies

Requires **Node.js ≥ 22** (`ai@7` and `@ai-sdk/gateway@4` require it).

```bash
npm install
```

### 2. Add credentials

```bash
cp .env.example .env
```

| Variable | Where to get it |
| --- | --- |
| `MOSS_PROJECT_ID` | [moss.dev](https://moss.dev) dashboard |
| `MOSS_PROJECT_KEY` | [moss.dev](https://moss.dev) dashboard |
| `MOSS_INDEX_NAME` | Name of the index to search |
| `AI_GATEWAY_API_KEY` | [Vercel AI Gateway](https://vercel.com/dashboard/ai-gateway) → API Keys |

### 3. Run

```bash
npm run dev
```

Open [http://localhost:3000](http://localhost:3000) and tap the orb to start talking.
73 changes: 73 additions & 0 deletions examples/cookbook/vercel-voice-agent/app/api/token/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { createGateway } from '@ai-sdk/gateway';
import { MossClient } from '@moss-dev/moss';
import { mossSearchTool } from '@moss-tools/vercel-sdk';

export const runtime = 'nodejs';

const gateway = createGateway({ apiKey: process.env.AI_GATEWAY_API_KEY });

const client = new MossClient(
process.env.MOSS_PROJECT_ID!,
process.env.MOSS_PROJECT_KEY!,
);

const searchTool = mossSearchTool({
client,
indexName: process.env.MOSS_INDEX_NAME!,
});

// Load the index into local memory at startup.
// Cloud query returns 503 — local queries work fine after loadIndex.
// Storing the promise means search requests block until ready, or fail fast if it rejects.
const indexReady = client.loadIndex(process.env.MOSS_INDEX_NAME!)
.then(() => console.log('[MOSS] index loaded locally'))
.catch((err: unknown) => { console.error('[MOSS] loadIndex failed:', err); throw err; });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BLOCKING ```ts
.catch((err: unknown) => { console.error('[MOSS] loadIndex failed:', err); throw err; });

`indexReady` is created at module load, so if `loadIndex()` rejects before any search request awaits it, this rethrow leaves the stored promise rejected without a handler and can terminate the Node/Next process instead of returning the intended 503. Keep the startup promise fulfilled with status, then branch in the handler:
```ts
const indexReady = client.loadIndex(indexName)
  .then(() => true)
  .catch((err) => { console.error('[MOSS] loadIndex failed:', err); return false; });

if (!(await indexReady)) return new Response('Search index unavailable', { status: 503 });


const MOSS_TOOL = {
type: 'function' as const,
name: 'search_knowledge_base',
description: searchTool.description,
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: 'Concise search query' },
topK: { type: 'integer', minimum: 1, maximum: 100, description: 'Number of results to return (1–100, default 5)' },
},
required: ['query'],
},
};

// POST (empty body) → mint a short-lived WebSocket token via Vercel AI Gateway
// POST ({ query }) → execute MOSS search on behalf of the realtime model's tool call
//
// Auth: fails closed (401) unless ALLOW_UNAUTHENTICATED_DEMO=true is explicitly set.
// For production, replace this check with a real session/token verification.
export async function POST(req: Request) {
Comment thread
CoderOMaster marked this conversation as resolved.
if (process.env.ALLOW_UNAUTHENTICATED_DEMO !== 'true') {
return new Response('Unauthorized', { status: 401 });
}

const body = await req.json().catch(() => ({})) as Record<string, unknown>;

if (typeof body.query === 'string') {
try {
await indexReady;
} catch {
return new Response('Search index unavailable', { status: 503 });
}
const topK = Number.isInteger(body.topK) ? Math.min(100, Math.max(1, body.topK as number)) : 5;
const result = await searchTool.execute!(
{ query: body.query, topK },
{ toolCallId: 'realtime', messages: [], abortSignal: req.signal },
);
const docs = (result as { docs: Array<{ text: string }> }).docs ?? [];
return new Response(docs.map((d) => d.text).join('\n\n---\n\n'), {
headers: { 'Content-Type': 'text/plain' },
});
}

const { token, url } = await gateway.experimental_realtime.getToken({
model: 'openai/gpt-realtime-2',
});
return Response.json({ token, url, tools: [MOSS_TOOL] });
}
28 changes: 28 additions & 0 deletions examples/cookbook/vercel-voice-agent/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { Metadata } from 'next';

export const metadata: Metadata = {
title: 'MOSS Voice Agent',
description: 'Realtime voice agent powered by Vercel AI Gateway and MOSS semantic search',
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
rel="stylesheet"
/>
</head>
<body style={{
margin: 0,
background: '#0a0a0a',
color: '#f0f0ee',
fontFamily: '"Inter", ui-sans-serif, system-ui, -apple-system, sans-serif',
WebkitFontSmoothing: 'antialiased',
}}>
{children}
</body>
</html>
);
}
Loading
Loading