रीयलटाइम वॉयस एजेंट
रीयलटाइम एजेंट द्विदिश ऑडियो स्ट्रीमिंग का उपयोग करके एआई सहायकों के साथ आवाज-आधारित इंटरैक्शन को सक्षम करते हैं। adk-realtime क्रेट आवाज-सक्षम एजेंट बनाने के लिए एक एकीकृत इंटरफ़ेस प्रदान करता है जो OpenAI के Realtime API और Google के Gemini Live API के साथ काम करते हैं।
अवलोकन
रीयलटाइम एजेंट टेक्स्ट-आधारित LlmAgents से कई प्रमुख तरीकों से भिन्न होते हैं:
| विशेषता | LlmAgent | RealtimeAgent |
|---|---|---|
| इनपुट | टेक्स्ट | ऑडियो/टेक्स्ट |
| आउटपुट | टेक्स्ट | ऑडियो/टेक्स्ट |
| कनेक्शन | HTTP अनुरोध | WebSocket |
| विलंबता | अनुरोध/प्रतिक्रिया | वास्तविक समय स्ट्रीमिंग |
| VAD | N/A | सर्वर-साइड वॉयस डिटेक्शन |
आर्किटेक्चर
┌─────────────────────────────────────────┐
│ Agent Trait │
│ (name, description, run, sub_agents) │
└────────────────┬────────────────────────┘
│
┌───────────────────────┼───────────────────────┐
│ │ │
┌──────▼──────┐ ┌─────────▼─────────┐ ┌─────────▼─────────┐
│ LlmAgent │ │ RealtimeAgent │ │ SequentialAgent │
│ (text-based)│ │ (voice-based) │ │ (workflow) │
└─────────────┘ └───────────────────┘ └───────────────────┘
RealtimeAgent वही Agent ट्रेट लागू करता है जो LlmAgent, साझा करते हुए:
- निर्देश (स्थिर और गतिशील)
- टूल पंजीकरण और निष्पादन
- कॉलबैक (before_agent, after_agent, before_tool, after_tool)
- उप-एजेंट हैंडऑफ़
त्वरित शुरुआत
स्थापना
अपने Cargo.toml में जोड़ें:
[dependencies]
adk-realtime = { version = "2.0.0", features = ["openai"] }
# For Vertex AI Live (Google Cloud with ADC auth)
# adk-realtime = { version = "2.0.0", features = ["vertex-live"] }
# For LiveKit WebRTC bridge
# adk-realtime = { version = "2.0.0", features = ["livekit"] }
# For all transports (except WebRTC which needs cmake)
# adk-realtime = { version = "2.0.0", features = ["full"] }
बुनियादी उपयोग
use adk_realtime::{
RealtimeAgent, RealtimeModel, RealtimeConfig, ServerEvent,
openai::OpenAIRealtimeModel,
};
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let api_key = std::env::var("OPENAI_API_KEY")?;
// Create the realtime model
let model: Arc<dyn RealtimeModel> = Arc::new(
OpenAIRealtimeModel::new(&api_key, "gpt-realtime")
);
// Build the realtime agent
let agent = RealtimeAgent::builder("voice_assistant")
.model(model.clone())
.instruction("You are a helpful voice assistant. Be concise.")
.voice("alloy")
.server_vad() // Enable voice activity detection
.build()?;
// Or use the low-level session API directly
let config = RealtimeConfig::default()
.with_instruction("You are a helpful assistant.")
.with_voice("alloy")
.with_modalities(vec!["text".to_string(), "audio".to_string()]);
let session = model.connect(config).await?;
// Send text and get response
session.send_text("Hello!").await?;
session.create_response().await?;
// Process events
while let Some(event) = session.next_event().await {
match event? {
ServerEvent::TextDelta { delta, .. } => print!("{}", delta),
ServerEvent::AudioDelta { delta, .. } => {
// Play audio (delta is base64-encoded PCM)
}
ServerEvent::ResponseDone { .. } => break,
_ => {}
}
}
Ok(())
}
समर्थित प्रदाता
| प्रदाता | मॉडल | ट्रांसपोर्ट | फ़ीचर फ़्लैग | ऑडियो फ़ॉर्मेट |
|---|---|---|---|---|
| OpenAI | gpt-realtime | WebSocket | openai | PCM16 24kHz |
| OpenAI | gpt-realtime | WebRTC | openai-webrtc | Opus |
| गूगल | gemini-live-2.5-flash-native-audio | WebSocket | gemini | PCM16 16kHz/24kHz |
| Gemini Vertex AI के माध्यम से | WebSocket + OAuth2 | vertex-live | PCM16 16kHz/24kHz | |
| LiveKit | कोई भी (Gemini/OpenAI से ब्रिज) | WebRTC | livekit | PCM16 |
ध्यान दें:
gpt-realtime, बेहतर भाषण गुणवत्ता, भावना और फ़ंक्शन कॉलिंग क्षमताओं वाला OpenAI का नवीनतम रीयलटाइम मॉडल है।
परिवहन विकल्प
ADK-Realtime कई परिवहन परतों का समर्थन करता है:
- WebSocket (डिफ़ॉल्ट): OpenAI या Gemini से सीधा कनेक्शन। सरल, कम-विलंबता वाला, हर जगह काम करता है।
- Vertex AI Live: OAuth2 प्रमाणीकरण (Application Default Credentials) के साथ Google Cloud के माध्यम से Gemini से कनेक्ट होता है। इसका उपयोग तब करें जब आपको एंटरप्राइज़ प्रमाणीकरण और GCP एकीकरण की आवश्यकता हो।
- LiveKit WebRTC: प्रोडक्शन-ग्रेड WebRTC ब्रिज। स्केलेबल, बहु-प्रतिभागी परिदृश्यों के लिए LiveKit सर्वर के माध्यम से ऑडियो रूट करता है।
- OpenAI WebRTC: Opus कोडेक और डेटा चैनलों के साथ OpenAI से सीधा WebRTC कनेक्शन। Opus C लाइब्रेरी बनाने के लिए cmake की आवश्यकता होती है।
RealtimeAgent बिल्डर
RealtimeAgentBuilder एजेंट्स को कॉन्फ़िगर करने के लिए एक धाराप्रवाह API प्रदान करता है:
let agent = RealtimeAgent::builder("assistant")
// Required
.model(model)
// Instructions (same as LlmAgent)
.instruction("You are helpful.")
.instruction_provider(|ctx| format!("User: {}", ctx.user_name()))
// Voice settings
.voice("alloy") // Options: alloy, coral, sage, shimmer, etc.
// Voice Activity Detection
.server_vad() // Use defaults
.vad(VadConfig {
mode: VadMode::ServerVad,
threshold: Some(0.5),
prefix_padding_ms: Some(300),
silence_duration_ms: Some(500),
interrupt_response: Some(true),
eagerness: None,
})
// Tools (same as LlmAgent)
.tool(Arc::new(weather_tool))
.tool(Arc::new(search_tool))
// Sub-agents for handoffs
.sub_agent(booking_agent)
.sub_agent(support_agent)
// Callbacks (same as LlmAgent)
.before_agent_callback(|ctx| async { Ok(()) })
.after_agent_callback(|ctx, event| async { Ok(()) })
.before_tool_callback(|ctx, tool, args| async { Ok(None) })
.after_tool_callback(|ctx, tool, result| async { Ok(result) })
// Realtime-specific callbacks
.on_audio(|audio_chunk| { /* play audio */ })
.on_transcript(|text| { /* show transcript */ })
.build()?;
वॉइस एक्टिविटी डिटेक्शन (VAD)
VAD यह पता लगाकर प्राकृतिक बातचीत के प्रवाह को सक्षम बनाता है कि उपयोगकर्ता कब बोलना शुरू करता है और कब बंद करता है।
सर्वर VAD (अनुशंसित)
let agent = RealtimeAgent::builder("assistant")
.model(model)
.server_vad() // Uses sensible defaults
.build()?;
कस्टम VAD कॉन्फ़िगरेशन
use adk_realtime::{VadConfig, VadMode};
let vad = VadConfig {
mode: VadMode::ServerVad,
threshold: Some(0.5), // Speech detection sensitivity (0.0-1.0)
prefix_padding_ms: Some(300), // Audio to include before speech
silence_duration_ms: Some(500), // Silence before ending turn
interrupt_response: Some(true), // Allow interrupting assistant
eagerness: None, // For SemanticVad mode
};
let agent = RealtimeAgent::builder("assistant")
.model(model)
.vad(vad)
.build()?;
सिमेंटिक VAD (Gemini)
Gemini मॉडलों के लिए, आप सिमेंटिक VAD का उपयोग कर सकते हैं जो अर्थ पर विचार करता है:
let vad = VadConfig {
mode: VadMode::SemanticVad,
eagerness: Some("high".to_string()), // low, medium, high
..Default::default()
};
टूल कॉलिंग
रीयलटाइम एजेंट्स वॉइस वार्तालापों के दौरान टूल कॉलिंग का समर्थन करते हैं:
use adk_realtime::{config::ToolDefinition, ToolResponse};
use serde_json::json;
// Define tools
let tools = vec![
ToolDefinition {
name: "get_weather".to_string(),
description: Some("Get weather for a location".to_string()),
parameters: Some(json!({
"type": "object",
"properties": {
"location": { "type": "string" }
},
"required": ["location"]
})),
},
];
let config = RealtimeConfig::default()
.with_tools(tools)
.with_instruction("Use tools to help the user.");
let session = model.connect(config).await?;
// Handle tool calls in the event loop
while let Some(event) = session.next_event().await {
match event? {
ServerEvent::FunctionCallDone { call_id, name, arguments, .. } => {
// Execute the tool
let result = execute_tool(&name, &arguments);
// Send the response
let response = ToolResponse::new(&call_id, result);
session.send_tool_response(response).await?;
}
_ => {}
}
}
मल्टी-एजेंट हैंडऑफ़
विशेषज्ञ एजेंट्स के बीच वार्तालापों को स्थानांतरित करें:
// Create sub-agents
let booking_agent = Arc::new(RealtimeAgent::builder("booking_agent")
.model(model.clone())
.instruction("Help with reservations.")
.build()?);
let support_agent = Arc::new(RealtimeAgent::builder("support_agent")
.model(model.clone())
.instruction("Help with technical issues.")
.build()?);
// Create main agent with sub-agents
let receptionist = RealtimeAgent::builder("receptionist")
.model(model)
.instruction(
"Route customers: bookings → booking_agent, issues → support_agent. \
Use transfer_to_agent tool to hand off."
)
.sub_agent(booking_agent)
.sub_agent(support_agent)
.build()?;
जब मॉडल transfer_to_agent को कॉल करता है, तो RealtimeRunner हैंडऑफ़ को स्वचालित रूप से संभालता है।
ऑडियो फ़ॉर्मेट
| प्रारूप | नमूना दर | बिट्स | चैनल | उपयोग का मामला |
|---|---|---|---|---|
| PCM16 | 24000 Hz | 16 | Mono | OpenAI (डिफ़ॉल्ट) |
| PCM16 | 16000 Hz | 16 | Mono | Gemini इनपुट |
| G711 u-law | 8000 Hz | 8 | Mono | Telephony |
| G711 A-law | 8000 Hz | 8 | Mono | Telephony |
use adk_realtime::{AudioFormat, AudioChunk};
// Create audio format
let format = AudioFormat::pcm16_24khz();
// Work with audio chunks
let chunk = AudioChunk::new(audio_bytes, format);
let base64 = chunk.to_base64();
let decoded = AudioChunk::from_base64(&base64, format)?;
इवेंट के प्रकार
सर्वर इवेंट
| घटना | विवरण |
|---|---|
SessionCreated | कनेक्शन स्थापित |
AudioDelta | ऑडियो चंक (base64 PCM) |
TextDelta | पाठ प्रतिक्रिया खंड |
TranscriptDelta | इनपुट ऑडियो प्रतिलेख |
FunctionCallDone | Tool कॉल अनुरोध |
ResponseDone | प्रतिक्रिया पूरी हुई |
SpeechStarted | VAD ने भाषण की शुरुआत का पता लगाया |
SpeechStopped | VAD द्वारा वाणी की समाप्ति का पता चला |
Error | त्रुटि हुई |
क्लाइंट इवेंट्स
| घटना | विवरण |
|---|---|
AudioInput | ऑडियो चंक भेजें |
AudioCommit | ऑडियो बफर कमिट करें |
ItemCreate | टेक्स्ट या टूल प्रतिक्रिया भेजें |
CreateResponse | प्रतिक्रिया का अनुरोध करें |
CancelResponse | वर्तमान प्रतिक्रिया रद्द करें |
SessionUpdate | कॉन्फ़िगरेशन अपडेट करें |
Vertex AI Live (Google Cloud)
Gemini Live से Vertex AI के माध्यम से एंटरप्राइज़ प्रमाणीकरण (ADC, service accounts, WIF) के साथ कनेक्ट करें:
use adk_realtime::gemini::{GeminiLiveBackend, GeminiRealtimeModel};
use adk_realtime::{RealtimeConfig, RealtimeModel};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let project_id = std::env::var("GOOGLE_CLOUD_PROJECT")?;
let region = std::env::var("GOOGLE_CLOUD_REGION")
.unwrap_or_else(|_| "us-central1".to_string());
// Use Application Default Credentials
let credentials = google_cloud_auth::credentials::Builder::default()
.build()
.await?;
let backend = GeminiLiveBackend::Vertex { credentials, region, project_id };
let model = GeminiRealtimeModel::new(backend, "models/gemini-live-2.5-flash-native-audio");
let config = RealtimeConfig::default()
.with_instruction("You are a helpful voice assistant.");
let session = model.connect(config).await?;
session.send_text("Hello from Vertex AI!").await?;
session.create_response().await?;
// Process events...
Ok(())
}
ADC के लिए एक सुविधा कंस्ट्रक्टर भी है:
let model = GeminiRealtimeModel::vertex_adc(
"us-central1",
"my-project-id",
"models/gemini-live-2.5-flash-native-audio",
).await?;
Vertex AI Live with Tool Calling
vertex_live_tools उदाहरण Vertex AI Live session पर function calling को प्रदर्शित करता है:
use adk_realtime::config::ToolDefinition;
use adk_realtime::events::ToolResponse;
use serde_json::json;
// Declare tools
let tools = vec![
ToolDefinition {
name: "get_weather".to_string(),
description: Some("Get current weather for a city".to_string()),
parameters: Some(json!({
"type": "object",
"properties": {
"city": { "type": "string" }
},
"required": ["city"]
})),
},
];
let config = RealtimeConfig::default()
.with_tools(tools)
.with_instruction("Use tools to answer questions about weather.");
let session = model.connect(config).await?;
// Handle FunctionCallDone events and send ToolResponse back
while let Some(event) = session.next_event().await {
match event? {
ServerEvent::FunctionCallDone { call_id, name, arguments, .. } => {
let result = match name.as_str() {
"get_weather" => json!({"temperature": "22°C", "condition": "sunny"}),
_ => json!({"error": "unknown tool"}),
};
session.send_tool_response(ToolResponse::new(&call_id, result)).await?;
}
ServerEvent::TextDelta { delta, .. } => print!("{delta}"),
ServerEvent::ResponseDone { .. } => break,
_ => {}
}
}
फ़ीचर फ़्लैग्स
| सुविधा | निर्भरताएँ | उपयोग का मामला |
|---|---|---|
vertex-live | gemini + google-cloud-auth | Vertex AI Live के साथ ADC/service account auth |
livekit | livekit + livekit-api | LiveKit WebRTC पुल |
openai-webrtc | openai + str0m + audiopus | OpenAI WebRTC Opus के साथ (cmake आवश्यक है) |
full | openai + gemini + vertex-live + livekit | सभी transports को छोड़कर WebRTC |
full-webrtc | full + openai-webrtc | सब कुछ (आवश्यकता है cmake) |
LiveKit WebRTC ब्रिज
उत्पादन वॉयस अनुप्रयोगों के लिए, LiveKit ब्रिज स्केलेबल, बहु-प्रतिभागी परिदृश्यों के लिए एक LiveKit सर्वर के माध्यम से ऑडियो को रूट करता है।
LiveKitConfig
सुरक्षित रूप से LiveKit क्रेडेंशियल कॉन्फ़िगर करें। API कुंजियाँ और रहस्य secrecy::SecretString का उपयोग करके संग्रहीत किए जाते हैं और डीबग आउटपुट में संपादित किए जाते हैं:
use adk_realtime::livekit::{LiveKitConfig, LiveKitRoomBuilder};
let config = LiveKitConfig::new(
"wss://your-server.livekit.cloud",
std::env::var("LIVEKIT_API_KEY")?,
std::env::var("LIVEKIT_API_SECRET")?,
)?;
LiveKitConfig::new() URL प्रारूप को मान्य करता है और निर्माण के समय खाली क्रेडेंशियल को अस्वीकार करता है।
LiveKitRoomBuilder
LiveKit कमरों से जुड़ने के लिए एक टाइपस्टेट बिल्डर। identity फ़ील्ड संकलन समय पर आवश्यक है — connect() केवल सेट होने के बाद ही उपलब्ध होता है:
let bundle = LiveKitRoomBuilder::new(config)
.identity("my-agent") // required — enables connect()
.name("Voice Agent") // optional display name
.room_name("session-room-123") // optional — auto-generated if omitted
.auto_subscribe(true) // subscribe to remote tracks
.with_audio(24_000, 1) // publish a local audio track (sample rate, channels)
.connect()
.await?;
// The bundle contains everything you need
let room = bundle.room;
let mut events = bundle.events;
let audio_source = bundle.audio_source; // for publishing audio
let audio_track = bundle.audio_track;
ऑडियो को ब्रिज करना
LiveKit ऑडियो को एक RealtimeRunner से जोड़ने के लिए ब्रिज यूटिलिटीज का उपयोग करें:
use adk_realtime::livekit::{LiveKitEventHandler, bridge_input};
// Wrap your event handler to publish model audio to LiveKit
let lk_handler = LiveKitEventHandler::new(inner_handler, audio_source, 24000, 1);
// Bridge participant audio from LiveKit into the RealtimeRunner
tokio::spawn(bridge_input(remote_track, runner));
उदाहरण
शामिल उदाहरणों को चलाएँ:
# OpenAI Realtime (WebSocket)
cargo run -p adk-realtime --example openai_session_update --features openai
# Vertex AI Live (requires gcloud auth application-default login)
cargo run -p adk-realtime --example vertex_live_voice --features vertex-live
cargo run -p adk-realtime --example vertex_live_tools --features vertex-live
# LiveKit Bridge (requires LiveKit server)
cargo run -p adk-realtime --example livekit_bridge --features livekit,openai
cargo run -p adk-realtime --example livekit_gemini_bridge --features livekit,gemini
# Debug utilities
cargo run -p adk-realtime --example debug_gemini --features gemini
cargo run -p adk-realtime --example debug_livekit_auth --features livekit
# OpenAI WebRTC (requires cmake)
cargo run -p adk-realtime --example openai_webrtc --features openai-webrtc
सर्वोत्तम अभ्यास
- सर्वर VAD का उपयोग करें: कम विलंबता के लिए सर्वर को स्पीच डिटेक्शन संभालने दें
- बाधाओं को संभालें: प्राकृतिक बातचीत के लिए
interrupt_responseसक्षम करें - निर्देशों को संक्षिप्त रखें: ध्वनि प्रतिक्रियाएँ संक्षिप्त होनी चाहिए
- पहले टेक्स्ट के साथ परीक्षण करें: ऑडियो जोड़ने से पहले टेक्स्ट के साथ अपने एजेंट लॉजिक को डीबग करें
- त्रुटियों को शालीनता से संभालें: WebSocket कनेक्शनों के साथ नेटवर्क समस्याएँ आम हैं
OpenAI Agents SDK के साथ तुलना
ADK-Rust का रीयलटाइम कार्यान्वयन OpenAI Agents SDK पैटर्न का पालन करता है:
| विशेषता | OpenAI SDK | ADK-Rust |
|---|---|---|
| एजेंट बेस क्लास | Agent | Agent trait |
| रीयलटाइम एजेंट | RealtimeAgent | RealtimeAgent |
| उपकरण | फ़ंक्शन परिभाषाएँ | Tool trait + ToolDefinition |
| हस्तांतरण | transfer_to_agent | sub_agents + स्वचालित रूप से उत्पन्न tool |
| कॉलबैक | हुक | before_* / after_* कॉलबैक |
पिछला: ← Graph Agents | अगला: मॉडल प्रदाता →