How can I send a return back to my react native ex...
# ask-ai
f
How can I send a return back to my react native expo livekit sdk from the function tools because I want to show a modal popup for user pin
t
Thanks for reaching out, Rasheed. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to send a return back to your React Native Expo LiveKit SDK and show a modal popup for the user’s PIN, you can use Remote Procedure Call (RPC) to help your agent and frontend chat smoothly. Here’s a quick rundown: Agent Side: • Create a function tool that uses
room.local_participant.perform_rpc()
to send nicely structured data to the frontend. For example, you might send a payload with the modal title, message, and input type. React Native Side: • Grab the
useRoom
hook to get access to the room and set up an RPC method (like
show_pin_modal
) to handle incoming requests. • Use
useState
to manage whether the modal is visible, and show it with the
Modal
component. • If you want, you can also send the PIN the user enters back to the agent with another RPC call. If you’d like me to share some detailed code examples or help you out further, just give me a shout! Sources: complex-agents/shopify-voice-shopper/shopify.py | example/src/RoomControls.tsx | Tool definition and use | LiveKit Docs
f
Yes would really appreciate a python code example for backend and React native expo example for ui
t
Here are some detailed examples for both the backend (Python) and the React Native Expo UI to help you out: Backend (Python):
Copy code
from livekit.agents import function_tool, RunContext
import json

@function_tool
async def request_user_pin(ctx: RunContext) -> str:
    """Request user PIN input via modal popup"""
    try:
        room = ctx.userdata.room  # Access room from context
        if room:
            # Send to all participants
            remote_participants = list(room.remote_participants.values())
            for participant in remote_participants:
                await room.local_participant.perform_rpc(
                    destination_identity=participant.identity,
                    method="show_pin_modal",
                    payload=json.dumps({
                        "title": "Enter PIN",
                        "message": "Please enter your 4-digit PIN",
                        "input_type": "numeric"
                    })
                )
    except Exception as e:
        print(f"Failed to send pin modal RPC: {e}")
        return "Error requesting PIN input"

    return "PIN input requested from user"
React Native Expo (UI):
Copy code
import React, { useState, useEffect } from 'react';
import { Modal, View, Text, TextInput, Pressable, StyleSheet } from 'react-native';
import { useRoom } from '@livekit/components-react';

export const PinModal = () => {
  const [pinModalVisible, setPinModalVisible] = useState(false);
  const [pinValue, setPinValue] = useState('');
  const [modalData, setModalData] = useState(null);
  const room = useRoom();

  useEffect(() => {
    if (!room) return;

    // Register RPC handler for pin modal
    const handlePinModal = async (data) => {
      const payload = JSON.parse(data.payload);
      setModalData(payload);
      setPinModalVisible(true);
    };

    // Register the RPC method handler
    room.localParticipant.registerRpcMethod('show_pin_modal', handlePinModal);

    return () => {
      // Cleanup RPC handler
      room.localParticipant.unregisterRpcMethod('show_pin_modal');
    };
  }, [room]);

  const handleSubmitPin = () => {
    console.log('PIN entered:', pinValue);
    setPinModalVisible(false);
    setPinValue('');

    // Optionally send PIN back to agent via RPC
    if (room && pinValue) {
      room.localParticipant.performRpc({
        destinationIdentity: 'agent-identity', // Replace with actual agent identity
        method: 'receive_pin',
        payload: JSON.stringify({ pin: pinValue })
      });
    }
  };

  const handleCancel = () => {
    setPinModalVisible(false);
    setPinValue('');
  };

  return (
    
  );
};

const styles = StyleSheet.create({
  centeredView: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalView: {
    margin: 20,
    backgroundColor: 'white',
    borderRadius: 20,
    padding: 35,
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  modalMessage: {
    fontSize: 14,
    marginBottom: 20,
    textAlign: 'center',
  },
  pinInput: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    padding: 10,
    fontSize: 18,
    textAlign: 'center',
    marginBottom: 20,
    width: 100,
  },
  buttonContainer: {
    flexDirection: 'row',
    gap: 10,
  },
  cancelButton: {
    backgroundColor: '#ccc',
    padding: 10,
    borderRadius: 5,
  },
  submitButton: {
    backgroundColor: '#007AFF',
    padding: 10,
    borderRadius: 5,
  },
  buttonText: {
    color: 'white',
    fontWeight: 'bold',
  },
});
If you have any questions or want me to walk you through any part of this, just let me know — I’m happy to help!