-
Notifications
You must be signed in to change notification settings - Fork 55
Vercel Voice Agents PR #324
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
CoderOMaster
wants to merge
5
commits into
main
Choose a base branch
from
vercel-ai
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
73
examples/cookbook/vercel-voice-agent/app/api/token/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; }); | ||
|
|
||
| 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) { | ||
|
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] }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| ); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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; });