|
1 | 1 | 'use client'; |
2 | 2 |
|
3 | | -import { useRef, useState } from 'react'; |
4 | | - |
5 | | -type Status = 'idle' | 'recording' | 'processing' | 'speaking'; |
| 3 | +import { experimental_useRealtime as useRealtime } from '@ai-sdk/react'; |
| 4 | +import { gateway } from '@ai-sdk/gateway'; |
| 5 | +import { useMemo, useState } from 'react'; |
6 | 6 |
|
7 | 7 | export default function Page() { |
8 | | - const [status, setStatus] = useState<Status>('idle'); |
9 | | - const [transcript, setTranscript] = useState(''); |
10 | | - const [reply, setReply] = useState(''); |
| 8 | + const [log, setLog] = useState<string[]>([]); |
11 | 9 | const [error, setError] = useState<string | null>(null); |
12 | 10 |
|
13 | | - const recorderRef = useRef<MediaRecorder | null>(null); |
14 | | - const chunksRef = useRef<Blob[]>([]); |
15 | | - |
16 | | - const startRecording = async () => { |
17 | | - if (status !== 'idle') return; |
18 | | - setError(null); |
| 11 | + const model = useMemo( |
| 12 | + () => gateway.experimental_realtime('openai/gpt-realtime-2'), |
| 13 | + [], |
| 14 | + ); |
19 | 15 |
|
20 | | - const stream = await navigator.mediaDevices.getUserMedia({ |
21 | | - audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }, |
| 16 | + const { status, connect, disconnect, startAudioCapture, stopAudioCapture, isCapturing } = |
| 17 | + useRealtime({ |
| 18 | + model, |
| 19 | + api: { token: '/api/token' }, |
| 20 | + sessionConfig: { |
| 21 | + voice: 'alloy', |
| 22 | + turnDetection: { type: 'server-vad' }, |
| 23 | + instructions: |
| 24 | + 'You are a helpful voice assistant with access to a knowledge base. ' + |
| 25 | + 'Always call search_knowledge_base before answering factual questions. ' + |
| 26 | + 'Keep answers brief — two or three sentences.', |
| 27 | + }, |
| 28 | + onError: (err) => { |
| 29 | + console.error('[realtime error]', err); |
| 30 | + setError(err instanceof Error ? err.message : String(err)); |
| 31 | + }, |
| 32 | + onToolCall: async ({ toolCall }) => { |
| 33 | + if (toolCall.toolName !== 'search_knowledge_base') return; |
| 34 | + const { query, topK } = toolCall.args as { query: string; topK?: number }; |
| 35 | + setLog((l) => [`🔍 "${query}"`, ...l.slice(0, 9)]); |
| 36 | + |
| 37 | + const res = await fetch('/api/token', { |
| 38 | + method: 'POST', |
| 39 | + headers: { 'Content-Type': 'application/json' }, |
| 40 | + body: JSON.stringify({ query, topK: topK ?? 5 }), |
| 41 | + }); |
| 42 | + const text = await res.json() as string; |
| 43 | + setLog((l) => [`✓ returned context`, ...l.slice(0, 9)]); |
| 44 | + return text; |
| 45 | + }, |
22 | 46 | }); |
23 | 47 |
|
24 | | - const recorder = new MediaRecorder(stream, { mimeType: 'audio/webm' }); |
25 | | - chunksRef.current = []; |
26 | | - |
27 | | - recorder.ondataavailable = (e) => { if (e.data.size > 0) chunksRef.current.push(e.data); }; |
28 | | - recorder.onstop = () => { |
29 | | - stream.getTracks().forEach((t) => t.stop()); |
30 | | - runPipeline(new Blob(chunksRef.current, { type: 'audio/webm' })); |
31 | | - }; |
32 | | - |
33 | | - recorder.start(); |
34 | | - recorderRef.current = recorder; |
35 | | - setStatus('recording'); |
36 | | - }; |
37 | | - |
38 | | - const stopRecording = () => { |
39 | | - if (recorderRef.current?.state === 'recording') { |
40 | | - recorderRef.current.stop(); |
41 | | - recorderRef.current = null; |
42 | | - setStatus('processing'); |
43 | | - } |
44 | | - }; |
45 | | - |
46 | | - const runPipeline = async (blob: Blob) => { |
47 | | - try { |
48 | | - const res = await fetch('/api/pipeline', { |
49 | | - method: 'POST', |
50 | | - headers: { 'Content-Type': 'audio/webm' }, |
51 | | - body: blob, |
52 | | - }); |
53 | | - |
54 | | - if (res.status === 204) { |
55 | | - setError('No speech detected'); |
56 | | - setStatus('idle'); |
57 | | - return; |
| 48 | + const handleButton = async () => { |
| 49 | + setError(null); |
| 50 | + if (status === 'connected') { |
| 51 | + stopAudioCapture(); |
| 52 | + disconnect(); |
| 53 | + } else { |
| 54 | + try { |
| 55 | + const stream = await navigator.mediaDevices.getUserMedia({ |
| 56 | + audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }, |
| 57 | + }); |
| 58 | + await connect(); |
| 59 | + startAudioCapture(stream); |
| 60 | + } catch (err) { |
| 61 | + setError(err instanceof Error ? err.message : String(err)); |
58 | 62 | } |
59 | | - if (!res.ok) throw new Error(`Pipeline failed: ${res.status}`); |
60 | | - |
61 | | - const raw = res.headers.get('X-Transcript'); |
62 | | - if (raw) setTranscript(decodeURIComponent(raw)); |
63 | | - |
64 | | - const rawReply = res.headers.get('X-Reply'); |
65 | | - if (rawReply) setReply(decodeURIComponent(rawReply)); |
66 | | - |
67 | | - const audioBlob = await res.blob(); |
68 | | - const url = URL.createObjectURL(audioBlob); |
69 | | - const audio = new Audio(url); |
70 | | - setStatus('speaking'); |
71 | | - audio.onended = () => { URL.revokeObjectURL(url); setStatus('idle'); }; |
72 | | - audio.onerror = () => { URL.revokeObjectURL(url); setStatus('idle'); }; |
73 | | - audio.play(); |
74 | | - } catch (err) { |
75 | | - setError(err instanceof Error ? err.message : String(err)); |
76 | | - setStatus('idle'); |
77 | 63 | } |
78 | 64 | }; |
79 | 65 |
|
80 | | - const busy = status !== 'idle'; |
81 | | - |
82 | 66 | return ( |
83 | | - <main style={{ maxWidth: 520, margin: '4rem auto', fontFamily: 'sans-serif', padding: '0 1rem' }}> |
84 | | - <h1 style={{ fontSize: '1.6rem', marginBottom: '0.25rem' }}>MOSS Voice Agent</h1> |
| 67 | + <main style={{ maxWidth: 480, margin: '4rem auto', fontFamily: 'sans-serif', padding: '0 1rem' }}> |
| 68 | + <h1 style={{ fontSize: '1.5rem', marginBottom: '0.25rem' }}>MOSS Voice Agent</h1> |
85 | 69 | <p style={{ color: '#6b7280', fontSize: '0.85rem', marginBottom: '2rem' }}> |
86 | | - Deepgram STT · GPT-4.1 Mini · Deepgram TTS · MOSS retrieval |
| 70 | + Vercel AI Gateway · gpt-realtime-2 · MOSS retrieval |
87 | 71 | </p> |
88 | 72 |
|
89 | 73 | <button |
90 | | - onMouseDown={startRecording} |
91 | | - onMouseUp={stopRecording} |
92 | | - onTouchStart={(e) => { e.preventDefault(); startRecording(); }} |
93 | | - onTouchEnd={(e) => { e.preventDefault(); stopRecording(); }} |
94 | | - disabled={status === 'processing' || status === 'speaking'} |
| 74 | + onClick={handleButton} |
| 75 | + disabled={status === 'connecting'} |
95 | 76 | style={{ |
96 | | - padding: '1rem 2.5rem', |
| 77 | + padding: '0.75rem 1.75rem', |
97 | 78 | fontSize: '1rem', |
98 | 79 | fontWeight: 600, |
99 | | - borderRadius: 12, |
| 80 | + borderRadius: 10, |
100 | 81 | border: 'none', |
101 | | - cursor: busy && status !== 'recording' ? 'not-allowed' : 'pointer', |
102 | | - background: |
103 | | - status === 'recording' ? '#dc2626' : |
104 | | - status === 'processing' ? '#6b7280' : |
105 | | - status === 'speaking' ? '#059669' : '#2563eb', |
| 82 | + cursor: status === 'connecting' ? 'not-allowed' : 'pointer', |
| 83 | + background: status === 'connected' ? '#dc2626' : '#2563eb', |
106 | 84 | color: '#fff', |
107 | | - userSelect: 'none', |
108 | | - WebkitUserSelect: 'none', |
109 | 85 | transition: 'background 0.15s', |
110 | 86 | }} |
111 | 87 | > |
112 | | - {status === 'recording' ? '🎙 Release to send' |
113 | | - : status === 'processing' ? 'Transcribing…' |
114 | | - : status === 'speaking' ? '🔊 Speaking…' |
115 | | - : '● Hold to speak'} |
| 88 | + {status === 'connecting' ? 'Connecting…' |
| 89 | + : status === 'connected' ? 'Stop' |
| 90 | + : 'Start talking'} |
116 | 91 | </button> |
117 | 92 |
|
118 | | - <p style={{ marginTop: '0.75rem', fontSize: '0.8rem', color: '#9ca3af' }}> |
119 | | - {status === 'idle' ? 'Press and hold, speak, then release.' : `Status: ${status}`} |
| 93 | + <p style={{ marginTop: '0.6rem', fontSize: '0.8rem', color: '#9ca3af' }}> |
| 94 | + Status: <strong>{status}</strong> |
| 95 | + {isCapturing && <span style={{ color: '#059669' }}> · mic active</span>} |
120 | 96 | </p> |
121 | 97 |
|
122 | 98 | {error && ( |
123 | | - <p style={{ marginTop: '0.75rem', color: '#dc2626', fontSize: '0.82rem' }}>⚠ {error}</p> |
124 | | - )} |
125 | | - |
126 | | - {transcript && ( |
127 | | - <div style={{ marginTop: '1.5rem', padding: '0.75rem 1rem', background: '#f3f4f6', borderRadius: 8 }}> |
128 | | - <p style={{ fontSize: '0.72rem', color: '#9ca3af', margin: '0 0 0.25rem' }}>YOU</p> |
129 | | - <p style={{ margin: 0, fontSize: '0.9rem' }}>{transcript}</p> |
130 | | - </div> |
| 99 | + <p style={{ marginTop: '0.5rem', color: '#dc2626', fontSize: '0.8rem' }}>⚠ {error}</p> |
131 | 100 | )} |
132 | 101 |
|
133 | | - {reply && ( |
134 | | - <div style={{ marginTop: '0.75rem', padding: '0.75rem 1rem', background: '#eff6ff', borderRadius: 8 }}> |
135 | | - <p style={{ fontSize: '0.72rem', color: '#93c5fd', margin: '0 0 0.25rem' }}>AGENT</p> |
136 | | - <p style={{ margin: 0, fontSize: '0.9rem' }}>{reply}</p> |
137 | | - </div> |
| 102 | + {log.length > 0 && ( |
| 103 | + <ul style={{ marginTop: '1.5rem', fontSize: '0.8rem', color: '#374151', paddingLeft: '1.2rem' }}> |
| 104 | + {log.map((entry, i) => <li key={i}>{entry}</li>)} |
| 105 | + </ul> |
138 | 106 | )} |
139 | 107 | </main> |
140 | 108 | ); |
|
0 commit comments