Hi, I have a method in my voice_assistant.py @func...
# ask-ai
b
Hi, I have a method in my voice_assistant.py @function_tool( description="Handle a user selection from the last shown options and advance the flow" ) async def choose_option(self, value: str): """ Persist the user's selection based on the current step and advance to the next step. Works for both skincare and gifting flows. """ step = self.conversation_state.get("step") user_choice = self.conversation_state.get("user_choice") if not step or not user_choice: return START_FRESH_MESSAGE # Skincare flow if user_choice == RecommendationType.SKINCARE.value: if step == ConversationStep.SKIN_TYPE.value: self.conversation_state["skin_type"] = value return await fetch_available_options( self, OptionType.CONCERN.value, self.is_chat_mode ) if step == ConversationStep.CONCERN.value: skin_type = self.conversation_state.get("skin_type") or "" return await get_product_recommendations( self, skin_type, value, RecommendationType.SKINCARE.value, self.is_chat_mode, ) # Gifting flow if user_choice == RecommendationType.GIFTING.value: if step == ConversationStep.PRICE_RANGE.value: self.conversation_state["price"] = value return await fetch_available_options( self, OptionType.PRODUCT_TYPE.value, self.is_chat_mode, price=self.conversation_state.get("price"), ) if step == ConversationStep.PRODUCT_TYPE.value: self.conversation_state["product_type"] = value product_type = self.conversation_state.get("product_type") or "" return await get_gift_recommendations( self, product_type, value, self.is_chat_mode, ) return "Thanks! What would you like to do next?" and my app.py looks like async def entrypoint(ctx: JobContext) -> None: logger = logging.getLogger("support-assistant") logger.info("Initializing support assistant...") await ctx.connect() tts_instance = create_tts() session = AgentSession( llm=openai.LLM(model=LLM_MODEL_NAME), stt=openai.STT(language=VoiceConfig.language, model=STT_MODEL_NAME), tts=tts_instance, vad=ctx.proc.userdata["vad"], preemptive_generation=True, user_away_timeout=5, ) @session.on("user_state_changed") def _on_user_state_changed(ev: UserStateChangedEvent): global disconnect_task if ev.new_state == "away": logger.info("User inactive 30s → asking if they are still there...") session.generate_reply(instructions="ask user if they are still there") # Start a background disconnect timer async def delayed_disconnect(): await asyncio.sleep(15) # wait another 15s # Check if still away if session.user_state == "away": logger.info("No response after warning → disconnecting") try: await ctx.delete_room() except Exception as e: logger.warning( f"Room deletion raised (likely already closed): {e}" ) disconnect_task = asyncio.create_task(delayed_disconnect()) elif ev.new_state == "active": logger.info("User became active again, cancelling pending disconnect") if disconnect_task and not disconnect_task.done(): disconnect_task.cancel() disconnect_task = None @session.on("agent_false_interruption") def _on_false_interrupt(ev: AgentFalseInterruptionEvent): logger.info("False positive interruption detected, resuming...") session.generate_reply(instructions=ev.extra_instructions or "") usage_collector = metrics.UsageCollector() @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): metrics.log_metrics(ev.metrics) usage_collector.collect(ev.metrics) async def log_usage(): summary = usage_collector.get_summary() logger.info(f"Usage summary: {summary}") ctx.add_shutdown_callback(log_usage) await session.start( agent=Assistant(), room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), ), ) try: await session.say( "Hi there! I'm Maya, your voice assistant specialized in personalized skincare consultations. " "Are you looking for skincare products, or a gift for someone?", allow_interruptions=False, ) logger.info("Initial greeting delivered to user") except Exception as e: logger.error(f"Failed to deliver greeting: {e}") if name == "__main__": setup_logging() worker_opts = WorkerOptions( entrypoint_fnc=entrypoint, load_threshold=LoadBalancingConfig.load_threshold, num_idle_processes=LoadBalancingConfig.num_idle_processes, max_retry=LoadBalancingConfig.max_retry, shutdown_process_timeout=LoadBalancingConfig.shutdown_timeout, initialize_process_timeout=LoadBalancingConfig.initialize_timeout, prewarm_fnc=prewarm, ) cli.run_app(worker_opts) I want that when product is recommeded then i should able to send the response fetched to my frontend so that my frontend can use the recommended products data and use it in anywhere in frontend
t
Thanks for reaching out, Mayank. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! To send the recommended product data from your backend to the frontend, a great way is to use LiveKit's Remote Procedure Calls (RPC). It’s a neat way to keep communication between your backend and frontend smooth and structured. Backend Implementation:
Copy code
await ctx.room.local_participant.perform_rpc(
    destination_identity=client_participant.identity,
    method="receive_recommendations",
    payload=json.dumps({"recommendations": recommended_products})
)
Frontend Implementation:
Copy code
localParticipant.registerRpcMethod(
  'receive_recommendations',
  async (data) => {
    const payload = JSON.parse(data.payload);
    console.log('Received recommendations:', payload.recommendations);
    // Use the data in your frontend as needed
  }
);
This way, your recommended products get sent in real-time and your frontend can use them right away. If you have any questions or want to chat more about it, just let me know—I’m here to help! Sources: complex-agents/nova-sonic/form_agent.py | Tool definition and use | LiveKit Docs | Function calling with Voice Agents | LiveKit Docs | agent-console/app/api/room/send-data/route.ts | Data packets | LiveKit Docs
b
can i use publish_data(from Backend) and DataRecieved from frontend, in place of rpc? or what is the difference between rpc and publish_data
t
Hey there! Yes, you can definitely use
publish_data
from the backend and
DataReceived
on the frontend as an alternative to RPC. Just a heads-up, there are some important differences between these two: RPC (Remote Procedure Call): • This lets you call a specific method on another participant and get a response back. • Great for structured, request-response interactions—like triggering actions or fetching specific data. • It’s actually built on top of the
publish_data
system but offers a more polished way to handle complex interactions. publish_data: • This is a more basic API for sending data packets to one or more participants in a room. • It doesn’t expect a response—it’s more like broadcasting a message. • You can choose reliable (in-order delivery) or lossy (faster but no delivery guarantee) transmission. • Plus, you can send data to specific participants or the whole room using the
destination_identities
parameter. So, in a nutshell: go with
publish_data
if you just need simple, one-way data sending. If you want a neat request-response setup, RPC is your friend. If you want, I’m here to help you get started with either one! Sources: packages/livekit-rtc/README.md | Data packets | LiveKit Docs | livekit/src/room/participant/local_participant.rs