import React, { useRef, useState, useEffect } from 'react';
import {
ConversationAgent,
BrowserAudioInterface,
InteractionType,
AgentState,
Role,
} from 'sarvam-conv-ai-sdk/browser';
interface Message {
role: 'user' | 'bot';
content: string;
}
function VoiceChat() {
const [state, setState] = useState<AgentState>(AgentState.IDLE);
const [messages, setMessages] = useState<Message[]>([]);
const [isMuted, setIsMuted] = useState(false);
const agentRef = useRef<ConversationAgent | null>(null);
useEffect(() => {
return () => {
agentRef.current?.stop().catch(console.error);
};
}, []);
const startConversation = async () => {
const audioInterface = new BrowserAudioInterface(16000, {
outputLevelCallback: (level) => {
// Update volume visualization
},
});
const agent = new ConversationAgent({
apiKey: 'your_api_key',
config: {
org_id: 'your_org_id',
workspace_id: 'your_workspace_id',
app_id: 'your_app_id',
user_identifier: 'user123',
user_identifier_type: 'custom',
interaction_type: InteractionType.CALL,
input_sample_rate: 16000,
output_sample_rate: 16000,
},
audioInterface,
stateCallback: (newState) => setState(newState),
transcriptCallback: async (msg) => {
setMessages((prev) => [
...prev,
{ role: msg.role === Role.USER ? 'user' : 'bot', content: msg.content },
]);
},
endCallback: async () => {
agentRef.current = null;
setState(AgentState.IDLE);
},
});
agentRef.current = agent;
await agent.start();
};
const toggleMute = () => {
if (!agentRef.current) return;
if (agentRef.current.isMuted()) {
agentRef.current.unmute();
setIsMuted(false);
} else {
agentRef.current.mute();
setIsMuted(true);
}
};
return (
<div>
<p>State: {state}</p>
<button onClick={startConversation} disabled={state !== AgentState.IDLE}>
Start
</button>
<button onClick={() => agentRef.current?.stop()} disabled={state === AgentState.IDLE}>
Stop
</button>
<button onClick={toggleMute} disabled={state === AgentState.IDLE}>
{isMuted ? 'Unmute' : 'Mute'}
</button>
<div>
{messages.map((msg, i) => (
<p key={i}>
<strong>{msg.role === 'user' ? 'You' : 'Agent'}:</strong> {msg.content}
</p>
))}
</div>
</div>
);
}
export default VoiceChat;