Hello AI! I need to send data to my client app fro...
# ask-ai
a
Hello AI! I need to send data to my client app from within
agent.py
. How to do that?
t
Thanks for reaching out, Guid. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to send data from your
agent.py
to the client app — what kind of data and delivery guarantees do you need? Please choose one (or tell me if mixed): • Text messages (chat, transcriptions) — reliable text stream via
send_text
. • Files / binary (images, audio) — byte/file stream via
send_file
or byte streams. • Low-level packets (fast, optional loss) —
publish_data
with
reliable=True|False
. • RPC (call a client method, get a response) — perform RPC to a specific participant. • Participant attributes (key/value state sync) —
set_attributes
on the local participant. Tell me which option you want and whether you need guaranteed delivery or low-latency; I’ll give the exact
agent.py
code snippet and the client-side handler for that case. Sources: Sending text | LiveKit docs | Sending files & bytes | LiveKit docs | Data packets | LiveKit docs | Tool definition and use | LiveKit docs | Job lifecycle | LiveKit docs
a
I need to send some extra information from the tool call that is not needed by the LLM but that is important to show visual cues in the client UI.
t
Regarding sending extra tool-call info for UI visual cues: two good approaches are Participant Attributes (for state synced to all clients) and RPC or Text Streams (for targeted, structured updates). Which you pick depends on whether the data is shared to everyone and persistent (attributes) or targeted/ephemeral (RPC/text). 1) Participant Attributes — best if the info should be visible to all participants and automatically syncs. • Agent side (in
agent.py
):
Copy code
await room.local_participant.set_attributes({
  "tool.last_result": "ok",
  "tool.highlight": json.dumps({"color":"#ff0","region":"top-right"})
})
• Client side: listen for participant attribute changes and update UI when
tool.*
keys change. 2) RPC — best if you need to call a specific client to show a UI cue or return an acknowledgement. • Agent side:
Copy code
response = await room.local_participant.perform_rpc(
  destination_identity="user123",
  method="showToolCue",
  payload=json.dumps({"cue":{"color":"#ff0","region":"top-right"}}),
  response_timeout=5.0
)
• Client side: register an RPC handler for
showToolCue
that parses payload and displays the visual cue, then returns an ack. 3) Text or Byte Streams — good for broadcasting ephemeral messages to any client subscribed to a topic. • Agent side:
Copy code
await room.local_participant.send_text(
  "tool_cue:"+json.dumps({"color":"#ff0","region":"top-right"}),
  topic="ui-cues"
)
• Client side: subscribe to
ui-cues
topic and parse messages to update UI. Which option do you prefer (attributes, RPC, or text stream)? Tell me whether the cue should go to all participants or a single user and whether it must be persisted; I’ll provide the exact
agent.py
snippet and matching client handler for your chosen flow.
a
With the proposed solutions, is there any risk that the data I am sending is shared across rooms?
t
Good question — regarding the three options you mentioned (participant attributes, RPC, and text/byte streams): any data you send from
agent.py
is scoped to the current room and will not be shared across other rooms. • Participant attributes and metadata are tied to a participant in that room and sync only to participants in the same room. • RPC calls can only be made between participants in the same room. • Text/byte streams and topics are room-scoped; two different rooms can use the same topic name without cross-talk. If you want, tell me which method you plan to use and whether the cue should be persistent or ephemeral; I’ll provide the exact
agent.py
snippet and the matching client handler. Sources: Rooms, participants, and tracks | LiveKit docs | Participant attributes and metadata | LiveKit docs | Remote method calls | LiveKit docs | Text and transcriptions | LiveKit docs | Sending text | LiveKit docs
a
Ok, great. What about perfomance: is any of the 3 methods faster in delivering the text? I would like the text to be sent using the already established WebRTC / WebSocket connection
t
Short answer: use text streams — they’re the fastest for delivering text over the existing LiveKit session (they use the WebRTC data channel for low-latency streaming). Quick comparison relevant to your need (real-time UI cues over the existing WebRTC/WebSocket connection): • Text streams: fastest and best for high-frequency or streaming text (low latency, incremental writes). • RPC: good for targeted request-response with acknowledgements, not optimized for streaming frequent text. • Participant attributes: stateful sync to all participants, simple but slower and not suitable for frequent updates. If you want, I can provide the exact
agent.py
snippet to stream text and the matching client handler (or an RPC/attributes example if you prefer). Which one do you want code for? Sources: Sending text | LiveKit docs | Remote method calls | LiveKit docs | Participant attributes and metadata | LiveKit docs | Text and transcriptions | LiveKit docs
a
Write me the snippet for a text stream, please.
t
Below are concise, ready-to-use examples: a Python
agent.py
snippet that opens a text stream and writes incremental cues, and a JavaScript client handler that receives those cues and updates UI. Python (agent.py)
Copy code
import asyncio
import json

async def send_visual_cues(room):
    # open a text stream on topic "visual_cue"
    writer = await room.local_participant.stream_text(
        topic="visual_cue",
        name="agent_visual_cue"
    )
    print(f"Opened text stream: {writer.stream_id}")

    # send incremental cues (can be any short text or JSON)
    await writer.write("thinking")
    await asyncio.sleep(0.5)
    await writer.write(json.dumps({"cue":"highlight","color":"#ff0","region":"top-right"}))
    await asyncio.sleep(0.5)
    await writer.write("speaking")

    # close when done
    await writer.aclose()
    print("Closed text stream")
Client (JavaScript / TypeScript)
Copy code
// register a handler for the same topic used by the agent
room.registerTextStreamHandler("visual_cue", async (reader, participant) => {
  // reader is async-iterable; handle chunks as they arrive
  try {
    for await (const chunk of reader) {
      // chunk is a string (text or JSON). Parse if needed.
      let data = chunk;
      try { data = JSON.parse(chunk); } catch { /* plain text */ }

      // update UI based on data
      // e.g., if data is string: "thinking" / "speaking"
      // if object: data.cue, data.color, data.region
      handleVisualCue(participant.identity, data);
    }
  } catch (err) {
    console.error("Text stream error:", err);
  }
});

function handleVisualCue(identity, data) {
  // implement UI update logic here
  console.log("Cue from", identity, data);
  // example: show highlight if data.cue === "highlight"
}
Notes • Use JSON for structured cues when you need fields (color, region, type). • Text streams use the existing LiveKit WebRTC data channel for low-latency delivery. • Open/close the stream per logical sequence (or keep it open for continuous updates). Sources: Sending text | LiveKit docs
a
Can I send text from within a
function_tool
tool call?
t
Yes — you can send text from inside a
function_tool
call. Options: • Use the agent session speech helpers (if speech text is acceptable): ◦
context.session.say("text")
or
await context.session.generate_reply("instruction")
◦ Spoken output and transcriptions are forwarded to the frontend automatically. • Send custom text over the room (for visual cues): ◦ From the tool you can access
context.session.room
and use a text stream:
Copy code
writer = await context.session.room.local_participant.stream_text(topic="visual_cue")
    await writer.write(json.dumps({"cue":"highlight","color":"#ff0"}))
    await writer.aclose()
• Client must register a handler for the same topic to receive and display the cue. • Use RPC for targeted messages/ack:
Copy code
resp = await context.session.room.local_participant.perform_rpc(
    destination_identity="user123",
    method="showToolCue",
    payload=json.dumps({"cue":"highlight","color":"#ff0"}),
    response_timeout=5.0
  )
Tell me which behavior you need (speech vs structured cue, broadcast vs single user, persistent vs ephemeral) and I’ll give the exact
function_tool
snippet wired into your tool signature. Sources: Tasks and task groups | LiveKit docs | Agent speech and audio | LiveKit docs | Text and transcriptions | LiveKit docs | Tool definition and use | LiveKit docs
a
If instead I used
send_text
, what connection will be used?
t
send_text
uses the WebRTC data channel (not the signaling WebSocket). It sends text over the existing LiveKit WebRTC connection (peer/data-channel or SFU-relayed path), giving low-latency, ordered delivery suitable for real-time UI cues. Sources: Data packets | LiveKit docs | Sending text | LiveKit docs | Realtime data | LiveKit Docs | OpenAI and LiveKit partner to turn Advanced Voice into an API | client-sdk-swift | livekit/livekit_composite | DeepWiki