앱 통화는 웹 통화처럼 동작합니다. 에이전트가 발신자의 말을 듣고, 카드를 보여 주거나 앱 자체의 함수를 호출할 수 있으며, 통화는 다른 통화처럼 나열, 분석, 과금됩니다. API 키는 서버가 보관하고, 로그인한 사용자를 위한 일회용 주소나 토큰을 앱에 줍니다.
| 앱 | 연결 방식 |
|---|---|
| iOS | WebSocket 오디오, iOS 에코 제거 사용 |
| Android | WebSocket 오디오, Android 에코 제거 사용 |
| React Native | 웹 통화 토큰과 Pipecat의 React Native 클라이언트 |
iOS와 Android에서는 서버가 통화를 시작하고 그 websocket_url을 앱에 돌려줍니다. 이 주소는 15분 안에 한 번 열 수 있습니다.
curl https://evasay.com/api/v1/voice/calls/websocket \
-X POST \
-H "Authorization: Bearer sk-your-key" \
-H "Content-Type: application/json" \
-d '{ "agent_id": "AGENT_ID", "encoding": "pcm_s16le", "sample_rate": 16000, "user_id": "u_42", "page_tools": ["open_order"] }'
React Native에서는 POST /api/v1/voice/web-calls로 웹 통화 토큰을 만들고 token과 web_call_url을 앱에 돌려줍니다.
websocket_url을 URLSessionWebSocketTask로 엽니다. 음성 처리를 켠 AVAudioEngine으로 녹음하고(그러면 에이전트가 스피커로 나오는 자기 목소리를 듣지 않습니다), 마이크를 통화 샘플 레이트의 16비트 PCM으로 변환해 20 ms 바이너리 프레임으로 보냅니다. EvaSay에서 오는 바이너리 프레임은 같은 형식의 에이전트 목소리이므로 AVAudioPlayerNode로 재생합니다.
let session = AVAudioSession.sharedInstance()
try session.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker])
try engine.inputNode.setVoiceProcessingEnabled(true)
let socket = URLSession.shared.webSocketTask(with: websocketURL)
socket.resume()
// microphone tap → 16 kHz Int16 mono → socket.send(.data(frame))
// socket.receive: .data → player.scheduleBuffer, .string → the call's events
텍스트 프레임은 JSON 형식의 통화 이벤트입니다. clear(발신자가 끼어듦)에서는 플레이어를 멈추고 대기열을 비우고, ended에서는 소켓을 닫습니다. 앱의 Info.plist에 NSMicrophoneUsageDescription을 추가하세요.
websocket_url을 OkHttp로 엽니다. 휴대폰의 에코 제거를 켜는 VOICE_COMMUNICATION에서 AudioRecord로 녹음하고, USAGE_VOICE_COMMUNICATION용 AudioTrack으로 재생합니다. 둘 다 통화 샘플 레이트의 16비트 모노입니다.
val record = AudioRecord(
MediaRecorder.AudioSource.VOICE_COMMUNICATION, 16000,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferBytes)
val socket = OkHttpClient().newWebSocket(Request.Builder().url(websocketUrl).build(), listener)
// a thread reads 640 bytes (20 ms) at a time → socket.send(frame.toByteString())
// listener.onMessage(bytes) → track.write(...); onMessage(text) → the call's events
clear에서는 AudioTrack을 일시 정지하고 비우며, ended에서는 소켓을 닫습니다. 앱에는 RECORD_AUDIO와 INTERNET 권한이 필요합니다.
{ "token": "…", "pageTools": ["open_order"] }를 https://evasay.com + web_call_url로 POST합니다. 응답의 data가 통화 연결 정보입니다. 그 transport가 cf이면 통화는 cfUrl의 Cloudflare Realtime을 거칩니다. Pipecat의 React Native SmallWebRTC 트랜스포트(@pipecat-ai/react-native-small-webrtc-transport, @pipecat-ai/client-js와 함께)로 연결하되, 연결 설정은 아래 EvaSay 시그널링을 따릅니다. 응답에 offerUrl이 있으면 수정하지 않은 트랜스포트로 그곳에 연결합니다.
// Offer to cfUrl, then answer each offer Cloudflare makes at /api/cf/answer
// until the reply names the two data channels.
await pc.setLocalDescription(await pc.createOffer());
let reply = await post(cfUrl, { sdp: pc.localDescription.sdp, type: 'offer', requestData });
const pcId = reply.pc_id;
for (;;) {
if (reply.answer) await pc.setRemoteDescription({ type: 'answer', sdp: reply.answer });
if (reply.offer) {
await pc.setRemoteDescription({ type: 'offer', sdp: reply.offer });
await pc.setLocalDescription(await pc.createAnswer());
reply = await post(answerUrl, { pc_id: pcId, sdp: pc.localDescription.sdp });
} else if (reply.next) reply = await post(answerUrl, { pc_id: pcId });
else break;
}
// "to-agent" is the channel RTVI messages are sent on, "to-caller" the agent's.
dc = pc.createDataChannel('to-agent', { negotiated: true, id: reply.channels.toAgent });
pc.createDataChannel('to-caller', { negotiated: true, id: reply.channels.toCaller });
오퍼 전에 마이크가 연결된 오디오 트랜시버(sendonly)를 하나 추가하세요. 에이전트 트랙은 Cloudflare의 오퍼로 들어옵니다. Cloudflare는 앱의 ICE 후보가 필요 없으며, 연결이 끊기면 통화가 끝납니다.
카드, 페이지 함수, 알림은 RTVI server-message(evasay.cards, evasay.tool, evasay.notice)로 도착합니다. 입력한 글은 send-text로 보내고, 페이지 상황과 함수 응답은 client-message의 evasay.context와 evasay.tool_result({ id, result } 또는 { id, error })로 보냅니다.
에이전트에 내 웹페이지에서 실행 유형("kind": "page")의 함수를 추가하고 앱에서 응답하세요. WebSocket에서는 통화가 {"type":"tool","id","name","arguments"}를 보내고 앱이 {"type":"tool_result","id","result"}로 답합니다. 에이전트는 앱이 지정한 함수(page_tools 또는 pageTools)만 호출할 수 있습니다. 함수는 그 사용자로 로그인한 상태로 실행되므로, 돈이 들거나 되돌릴 수 없는 일 전에는 앱에서 확인을 받으세요.