I am using the react chat component in my frontend...
# ask-ai
f
I am using the react chat component in my frontend to allow the user to send text messages. How can I detect on the backend with my agent whether the message was spoken by the user or sent via text?
t
Thanks for reaching out, Gauthier. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to help you out! Could you share a bit more about your backend setup? For instance, are you using LiveKit's Webhooks, or do you have a custom API handling your messages? Knowing this will really help me guide you on how to tell if a message was spoken or sent as text.
f
The backend is simply running an instance of a livekit agent session
t
I'm happy to help you understand how to detect whether a message was spoken or sent via text in your LiveKit agent session. Here are some friendly tips you can use: • Transcription Events: The
TranscriptEvent
has a
medium
field that tells you if the message came through as
voice
or
text
. For example: ◦
medium: "voice"
means it was a spoken message. ◦
medium: "text"
means it was a text message. • Text Input via
lk.chat
Topic:
Any messages you see on the
lk.chat
topic are text-based. These come from the frontend when
sendText()
is used with the topic
lk.chat
. By keeping an eye on these events and topics, you’ll be able to easily tell the difference between spoken and text messages in your backend. If you have any questions or want to dive deeper, I’m here to support you! Sources: tests/test_agent_session.py | Text and transcriptions | LiveKit Docs | VoiceAgent/Chat/Message.swift
f
Can you please show an example where you identify messages spoken by the user vs messages written in chat based on events?
t
I'd love to walk you through an example that shows how you can tell if a message was spoken or written in chat by looking at the events: Example:
Copy code
// Example of handling a TranscriptEvent
function handleTranscriptEvent(event) {
    const { role, medium, text, final } = event;

    if (role === "user") { // Check if the message is from the user
        if (medium === "voice") {
            console.log("Spoken message from user:", text);
        } else if (medium === "text") {
            console.log("Text message from user:", text);
        }
    }
}

// Example of handling messages from the lk.chat topic
function handleChatMessage(message) {
    console.log("Text message from user:", message.text);
}

// Simulated events
const transcriptEvent = {
    role: "user",
    medium: "voice", // or "text"
    text: "Hello, how can I help you?",
    final: true
};

const chatMessage = {
    text: "I need assistance with my account."
};

// Process the events
handleTranscriptEvent(transcriptEvent);
handleChatMessage(chatMessage);
So, in this example: • The
TranscriptEvent
helps us figure out if a message was spoken (
medium: "voice"
) or typed out (
medium: "text"
). • Messages coming through the
lk.chat
topic are always text, and we can handle those a bit differently. If you have any questions or want me to share more examples, just let me know—I’m here to help!
f
How would you subscribe to lk.chat in the backend?
t
To subscribe to the
lk.chat
topic in the backend, here’s a friendly step-by-step guide to help you out: 1. Register a Text Stream Handler: You can use the LiveKit Agents framework to register a handler for the
lk.chat
topic. Here’s an example in Python to get you started:
Copy code
room.register_text_stream_handler(
    topic='lk.chat', handler=your_message_handler
)

async def your_message_handler(reader, participant_identity):
    async for chunk in reader:
        print(f"Received chat message from {participant_identity}: {chunk}")
1. Use Predefined Constants: Just a heads-up, the
lk.chat
topic is already predefined in the SDKs. Here’s how you can use it in Python:
Copy code
from livekit.agents.types import TOPIC_CHAT

room.register_text_stream_handler(topic=TOPIC_CHAT, handler=your_message_handler)
1. Ensure Agent Permissions: Make sure your agent has the right room grants, like
room_join
and
room
permissions, so everything runs smoothly. 2. Frontend Integration: Don’t forget to have your frontend send messages to the
lk.chat
topic. Here’s a quick JavaScript example:
Copy code
await room.localParticipant.sendText("Hello", { topic: 'lk.chat' });
If you’d like, I’m here to help with more examples or any other questions you might have—just let me know! Sources: agents/src/constants.ts | packages/core/src/components/chat.ts | Subscribing to tracks | LiveKit Docs | examples/other/text_only.py | examples/demo/demo.ts
f
show where room is imported from
t
In the backend, the
room
object is usually created using the LiveKit Agents SDK. Here’s a simple example in Python to help you get started:
Copy code
from livekit.agents import Room

# Create a Room instance
room = Room(
    url="your_livekit_server_url",
    token="your_agent_token"
)
Just be sure to replace
your_livekit_server_url
with the URL of your LiveKit server and
your_agent_token
with a valid token that has the right permissions, like
room_join
. If you have any questions or want me to walk you through more examples, feel free to ask—I’m here to help!
f
Basically I have some logic that runs in on_user_turn_completed node, however this gets bypassed when the user sends a text message via chat. How can I catch this?
t
I’m glad you’re looking into handling text messages in
on_user_turn_completed
! To make sure your logic runs for text messages sent via chat, you can simply override this method in your custom
Agent
subclass. This method is called for both spoken and text inputs, which makes it really handy. Here’s a little example to guide you:
Copy code
async def on_user_turn_completed(self, turn_ctx, new_message):
    if new_message.text_content:
        print("User sent a text message:", new_message.text_content)
    else:
        print("User spoke a message:", new_message.text_content)

    # Add your custom logic here
    # For example, modify the message or inject additional context
    new_message.content = ["Processed: " + new_message.text_content]
Here’s what’s happening in this example: • The
new_message
object holds the latest input from the user, whether it’s spoken or typed. • You can tell if it’s text or speech by checking the
text_content
field. • Feel free to tweak or process the message as you like before it’s added to the conversation context. If you’d like, I’m here to help with more examples or to walk you through your specific scenario—just let me know! Sources: Text and transcriptions | LiveKit Docs | agents/src/voice/agent_activity.ts | External data and RAG | LiveKit Docs | examples/other/transcription/translator.py | Docs::Agents