We're planning to use a LiveKit agent in Unity on ...
# ask-ai
b
We're planning to use a LiveKit agent in Unity on Android devices. The agent will be Python, maybe on a LiveKit server, but we'd like tool calls to be handled in C# on the Android device. How do we make the Python code call into our Unity app and get a result back?
t
Thanks for reaching out, Mat. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how a Python LiveKit agent can invoke tool calls that run in your Unity (C#) Android app and return results. Use LiveKit RPC over the WebRTC data channel: have the agent forward the tool call to the Android participant, Unity handle it, and return the result. Key steps (concise): 1. In the Python agent, define the tool to forward via RPC: • Use your tool function to call
room.local_participant.perform_rpc(...)
targeting the Android participant's identity, send a JSON payload, and set an appropriate
response_timeout
. 1. In Unity (C#), register an RPC handler on the local participant: • Use
LocalParticipant.RegisterRpcMethod("methodName", handler)
when connected. • In
handler
, parse
data.Payload
, run the native Unity/Android logic (GPS, camera, sensors, etc.), serialize the result to JSON, and return it. • On failure throw/return an RPC error so the agent can handle it. 1. Match participant identity: • Ensure the Python agent selects the correct remote participant identity so the RPC reaches the intended Android device. 1. Payload and limits: • Use JSON strings, keep payloads under ~15 KiB, and keep responses small. Use IDs or references for large data (e.g., upload image to storage and return URL) rather than sending large binary blobs. 1. Error handling and timeouts: • Unity should return errors via RPC exceptions; the Python tool should catch timeouts or RPC errors and raise a ToolError or handle retries. • Set
response_timeout
long enough for device operations (e.g., GPS or camera). 1. Security and reliability: • Validate payloads in Unity, reject unexpected method names, and handle disconnects gracefully. • Consider fallback behavior if the device is offline (agent can run alternate logic or notify the user). If you want, I can: • Provide a compact Python example that forwards a tool call (with
perform_rpc
) tailored to your agent framework. • Produce a C# Unity RPC handler snippet that calls Android location or camera APIs and returns JSON. Which snippet would you like first? Sources: Tool definition and use | LiveKit docs | Remote method calls | LiveKit docs
b
The Python one.
t
Below is a concise Python example showing a LiveKit agent tool that forwards a tool call to a Unity Android participant via RPC, waits for the JSON response, and returns it. Adjust method name, payload fields, timeout, and participant selection to fit your app.
Copy code
import json
from livekit.agents import function_tool, get_job_context, RunContext, ToolError

@function_tool()
async def get_user_location(context: RunContext, high_accuracy: bool = False) -> dict:
    """
    Forward a location request to the Unity Android app via RPC and return the result.
    Unity should register an RPC method named "getUserLocation" that accepts:
      { "highAccuracy": bool }
    and returns:
      { "latitude": float, "longitude": float }
    """
    room = get_job_context().room

    # Select the target participant (adjust selection logic for your app)
    # Example: pick the first remote participant
    participants = list(room.remote_participants.values())
    if not participants:
        raise ToolError("No remote participants available to forward RPC")

    target = participants[0]  # or find by identity/tag/metadata

    payload = json.dumps({"highAccuracy": high_accuracy})

    try:
        # perform_rpc returns a UTF-8 string payload from the remote handler
        response_str = await room.local_participant.perform_rpc(
            destination_identity=target.identity,
            method="getUserLocation",
            payload=payload,
            response_timeout=10.0 if high_accuracy else 5.0,
        )
        # Parse and return structured result
        return json.loads(response_str)
    except Exception as e:
        # Convert RPC failures/timeouts into a ToolError for the agent/LLM
        raise ToolError(f"RPC to Unity failed: {e}")
Notes: • Keep payloads small (use storage URLs for large data). • Ensure the Unity participant registers
getUserLocation
and returns JSON. • Adjust participant selection to reliably target the correct device identity.
b
Now I would also like the C# sample.
t
Below is a concise Unity (C#) example that registers an RPC method named "getUserLocation", parses the JSON payload, obtains device location (using Unity's
Input.location
), and returns a JSON response. Adjust for your Android-specific location implementation or native plugins if you need higher accuracy or permissions handling.
Copy code
using System;
using System.Threading.Tasks;
using UnityEngine;
using LiveKit;
using LiveKit.Rooms; // adjust namespaces based on SDK version

[Serializable]
public class GetUserLocationRequest
{
    public bool highAccuracy;
}

[Serializable]
public class GetUserLocationResponse
{
    public double latitude;
    public double longitude;
}

public class RpcHandlers : MonoBehaviour
{
    private Room room; // assign when you connect

    private void Start()
    {
        // Assume `room` is already connected and LocalParticipant is available.
        // Register the RPC handler.
        room.LocalParticipant.RegisterRpcMethod("getUserLocation", OnGetUserLocation);
    }

    private async Task<string> OnGetUserLocation(RpcInvocationData data)
    {
        try
        {
            var req = JsonUtility.FromJson<GetUserLocationRequest>(data.Payload);

            // Ensure location service is enabled and has permission.
            if (!Input.location.isEnabledByUser)
            {
                throw new RpcException(1, "Location disabled by user");
            }

            // Start location service if not running
            if (Input.location.status == LocationServiceStatus.Stopped)
            {
                Input.location.Start(req.highAccuracy ? 1f : 10f, req.highAccuracy ? 0.5f : 5f);
                int maxWait = 10;
                while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
                {
                    await Task.Delay(500);
                    maxWait--;
                }
            }

            if (Input.location.status != LocationServiceStatus.Running)
            {
                throw new RpcException(2, "Unable to start location service");
            }

            var last = Input.location.lastData;
            var resp = new GetUserLocationResponse
            {
                latitude = last.latitude,
                longitude = last.longitude
            };

            return JsonUtility.ToJson(resp);
        }
        catch (RpcException)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw new RpcException(3, $"Location error: {ex.Message}");
        }
    }

    private void OnDestroy()
    {
        // Unregister if needed when object destroyed
        if (room?.LocalParticipant != null)
        {
            room.LocalParticipant.UnregisterRpcMethod("getUserLocation");
        }
    }
}
Notes: • Replace
Room
and
LocalParticipant
types/namespaces if your LiveKit Unity SDK version differs. • For production on Android, handle runtime permissions (
ACCESS_FINE_LOCATION
) and consider using a native plugin for higher-accuracy or background location. • For large results (images, files), upload to storage and return a URL instead of embedding binary data in JSON.
b
This solution requires that the signatures of the Python and C# code be kept in sync. Ideally, the Python code would receive a list of tool signatures from Unity as part of initialization, so that the Python method to implement each tool was generated on-the-fly, and each of the resulting Python methods was just a wrapper for an RPC. I'd like Python and C# code for that approach.
t
Acknowledged — I'll provide a concise, runnable pattern showing: • C# (Unity) side: publish a list of tool signatures at participant connect (via an RPC "announceTools" or a participant metadata update) and register RPC handlers for each tool. • Python side: on agent start, retrieve the tool list (via an RPC call to the Unity participant or by reading published participant metadata), dynamically create Python tool functions that forward to Unity via
perform_rpc
, and register them with the agent framework. Below are compact examples you can adapt. They assume: • Both sides use JSON for signatures and RPC payloads. • Tool signatures include: method name, parameter names and types, and a short description. • Payloads and responses stay under the ~15 KiB limit; for large data use storage URLs. C# (Unity) — announce tools and register handlers
Copy code
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using LiveKit;
using LiveKit.Rooms; // adjust per SDK

[Serializable]
public class ToolSignature {
    public string name;
    public string description;
    public List<string> parameters; // simple list of param names (or objects for types)
}

public class ToolAnnouncer : MonoBehaviour {
    public Room room; // set when connected

    // Define your tool signatures here
    private List<ToolSignature> tools = new List<ToolSignature> {
        new ToolSignature {
            name = "getUserLocation",
            description = "Return device location",
            parameters = new List<string> { "highAccuracy" }
        },
        new ToolSignature {
            name = "capturePhoto",
            description = "Take photo and return URL",
            parameters = new List<string> { "resolution" }
        }
    };

    private void Start() {
        // Ensure room & LocalParticipant exist and are connected
        AnnounceToolsToAgent();
        RegisterRpcHandlers();
    }

    private async void AnnounceToolsToAgent() {
        try {
            var payload = JsonUtility.ToJson(new ToolListWrapper { tools = tools });
            // Broadcast via RPC to all (or call specific agent identity if known)
            await room.LocalParticipant.BroadcastRpc("announceTools", payload);
        } catch (Exception e) {
            Debug.LogError($"Failed to announce tools: {e}");
        }
    }

    private void RegisterRpcHandlers() {
        room.LocalParticipant.RegisterRpcMethod("getUserLocation", OnGetUserLocation);
        room.LocalParticipant.RegisterRpcMethod("capturePhoto", OnCapturePhoto);
        // Add additional handlers per tool
    }

    private async Task<string> OnGetUserLocation(RpcInvocationData data) {
        // parse payload
        var req = JsonUtility.FromJson<GetUserLocationRequest>(data.Payload);
        // ... get location (similar to earlier example) ...
        var resp = new GetUserLocationResponse { latitude = 1.0, longitude = 2.0 };
        return JsonUtility.ToJson(resp);
    }

    private async Task<string> OnCapturePhoto(RpcInvocationData data) {
        var req = JsonUtility.FromJson<CapturePhotoRequest>(data.Payload);
        // capture photo, upload to storage, return URL
        var resp = new CapturePhotoResponse { url = "https://..." };
        return JsonUtility.ToJson(resp);
    }

    [Serializable]
    private class ToolListWrapper { public List<ToolSignature> tools; }

    [Serializable] private class GetUserLocationRequest { public bool highAccuracy; }
    [Serializable] private class GetUserLocationResponse { public double latitude, longitude; }

    [Serializable] private class CapturePhotoRequest { public string resolution; }
    [Serializable] private class CapturePhotoResponse { public string url; }

    private void OnDestroy() {
        if (room?.LocalParticipant != null) {
            room.LocalParticipant.UnregisterRpcMethod("getUserLocation");
            room.LocalParticipant.UnregisterRpcMethod("capturePhoto");
            room.LocalParticipant.UnregisterRpcMethod("announceTools");
        }
    }
}
Python — fetch tool signatures and dynamically create wrappers
Copy code
import asyncio
import json
from types import SimpleNamespace
from livekit.agents import function_tool, get_job_context, RunContext, ToolError

# Helper to dynamically create an async wrapper that forwards via RPC
def make_rpc_wrapper(method_name, param_names, timeout=8.0):
    async def rpc_wrapper(context: RunContext, **kwargs):
        room = get_job_context().room
        participants = list(room.remote_participants.values())
        if not participants:
            raise ToolError("No remote participants available")

        target = participants[0]  # pick proper participant by identity if needed

        # Build payload only with declared params (validate)
        payload_obj = {k: kwargs.get(k) for k in param_names}
        payload = json.dumps(payload_obj)

        try:
            resp_str = await room.local_participant.perform_rpc(
                destination_identity=target.identity,
                method=method_name,
                payload=payload,
                response_timeout=timeout,
            )
            return json.loads(resp_str)
        except Exception as e:
            raise ToolError(f"RPC to Unity failed for {method_name}: {e}")

    # annotate param names so callers/tools know signature (optional)
    rpc_wrapper.__name__ = method_name
    rpc_wrapper.__doc__ = f"RPC wrapper for {method_name} params: {param_names}"
    return rpc_wrapper

# Call this at agent initialization to request tool list then register functions
async def initialize_tools_from_unity():
    room = get_job_context().room
    participants = list(room.remote_participants.values())
    if not participants:
        raise ToolError("No remote participants to query for tools")

    target = participants[0]  # or find by identity/metadata

    try:
        # Ask Unity to announce tools (Unity should handle "announceTools" RPC)
        resp = await room.local_participant.perform_rpc(
            destination_identity=target.identity,
            method="announceTools",
            payload="{}",  # empty or include agent identity
            response_timeout=5.0,
        )
        tool_list = json.loads(resp)  # expect {"tools": [ {name, parameters: [...]}, ... ]}
    except Exception as e:
        raise ToolError(f"Failed to get tools from Unity: {e}")

    # Dynamically create and register tool functions
    for t in tool_list.get("tools", []):
        name = t["name"]
        params = t.get("parameters", [])
        wrapper = make_rpc_wrapper(name, params)

        # Wrap the wrapper with function_tool so agent treats it as a tool
        wrapped_tool = function_tool()(wrapper)  # decorator returns a callable tool

        # Register into module globals so tooling/agent can find it by name
        globals()[name] = wrapped_tool

# Example usage on agent startup
async def on_agent_startup():
    await initialize_tools_from_unity()
    # Now you can call the generated tools by name, e.g. await getUserLocation(...)
Notes and recommendations • Tool discovery transport: I used an RPC "announceTools" that Unity will respond to with the tool list. Alternatively, Unity can set participant metadata or broadcast the tool list once on join — choose whichever fits your signaling model. • Parameter types: examples use simple param name lists. For richer typing, send parameter descriptors with types and required flags; the Python wrapper can coerce/validate accordingly. • Participant selection: replace the simple "first participant" logic with identity lookup (e.g., agent knows which participant it should target). • Security: authenticate/validate incoming tool lists before generating functions. • Persistence: generated Python functions are runtime-only. If you need static codegen, serialize the signatures and generate .py files at build time. • Large payloads: for photos/files, Unity should upload and return a URL; Python wrappers should expect URLs, not binary blobs. If you want, I can: • Produce a stricter JSON schema for tool signatures and an updated Python generator that enforces types and required params. • Convert the Python dynamic registration into static code generation that writes .py files on init. Which would you like next?