on livekit doc it says this "You can use the retur...
# ask-ai
a
on livekit doc it says this "You can use the return value to initiate a handoff to a different Agent within a workflow. Optionally, you can return a tool result to the LLM as well. The tool call and subsequent LLM reply are completed prior to the handoff."; how can i return a tool result to the LLM that will speak it? Can I also have the LLM speak while calling the tool (that speech isn't pre-generated)
t
Thanks for reaching out, Ali. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to help you with returning a tool result to the LLM so it can be spoken! You can simply return a string value from your tool function. This result is then sent to the LLM, which creates a reply that the agent will speak. Here's a quick example to illustrate:
Copy code
async def send_tool_result(self, call_id: str, result: str):
    event = ClientToolResultEvent(
        invocationId=call_id,
        result=result,
        agent_reaction="speaks",
    )
    self._send_client_event(event)
Now, about having the agent speak while the tool is still running—this isn't supported in the standard flow. But don't worry! You can use
session.say()
inside your tool to give immediate updates as it runs. Here's how you might do that:
Copy code
@function_tool
async def long_running_task(ctx: RunContext):
    await ctx.session.say("Starting your request...")
    result = perform_complex_operation()
    return result
This way, the agent can share progress updates during execution, and then the final response from the LLM will come once the tool finishes. I hope this helps clarify things! If you have any more questions or need further assistance, feel free to ask. Sources: Tool definition and use | LiveKit Docs | livekit-plugins/livekit-plugins-ultravox/livekit/plugins/ultravox/realtime/...
a
can it generate a reply; then do a function call; then use the result of the function call to decide what to say/generate reply (without user having spoken yet)
t
Absolutely! LiveKit is designed to make things smooth and seamless for you. It can generate a reply, perform a function call, and then use the result of that function call to decide what to say next—all without needing any extra input from you. Here’s a quick rundown of how it works: • The LLM creates an initial reply and figures out if a function call is necessary based on the conversation. • The function tool runs, and its result is sent back to the LLM. • Using that result, the LLM crafts the next response, which the agent can then share with you. For instance, if you ask about the weather, the agent might call a weather lookup tool. The tool’s response (like “sunny with a temperature of 70 degrees”) helps the agent say something like, “The weather in San Francisco is sunny with a temperature of 70 degrees.” And the best part? This all happens automatically, making your experience effortless. If you’d like me to walk you through more details or share some examples, just let me know—I’m here to help! Sources: Tool definition and use | LiveKit Docs | README.md | Agent speech and audio | LiveKit Docs
a
walk me through it and share example!
t
Let me guide you through a simple, step-by-step walkthrough of how LiveKit can generate a reply, perform a function call, and then use that result to decide what to say next. I’ve also included an example to make it clearer: 1. Initial User Input: Imagine the user asks, "What is the weather in San Francisco?" 2. LLM Determines a Function Call: Based on that question, the LLM decides to call a function tool, like
lookup_weather
, with the parameter
location="San Francisco"
. 3. Function Execution: The
lookup_weather
tool runs and returns a result, for example, "sunny with a temperature of 70 degrees." 4. LLM Generates a Response: Using that result, the LLM crafts a reply such as "The weather in San Francisco is sunny with a temperature of 70 degrees." 5. Agent Speaks the Response: Finally, the agent uses text-to-speech (TTS) to speak the generated reply. Example Code:
Copy code
@function_tool
def lookup_weather(location: str):
    """Fetches weather information for a given location."""
    # Simulate a weather lookup
    return f"sunny with a temperature of 70 degrees in {location}."

# User input triggers the following flow:
user_input = "What is the weather in San Francisco?"

# LLM decides to call the tool
result = lookup_weather(location="San Francisco")

# LLM generates a response based on the result
response = f"The weather in San Francisco is {result}"

# Agent speaks the response
print(response)  # Output: "The weather in San Francisco is sunny with a temperature of 70 degrees."
I hope this helps clarify how the system works! If you have any questions or want me to walk you through more examples, just let me know—I’m here to help!
a
but will the agent stream the response or wait for the llm to finish the generation to speak it?
t
I'm glad you asked! The LiveKit agent actually streams the response as the LLM generates it, instead of waiting for the entire response to finish before speaking. This happens thanks to a streaming architecture where the LLM sends out chunks of text bit by bit, and the agent processes and speaks these chunks right away. This way, you get minimal delay and a much smoother, more natural conversation experience. I hope this helps clarify things for you! Sources: Tool definition and use | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py
a
in the example you gave me; the agent always speak the same thing; i want the agent to generate a reply based on the tool call (A FULL REPLY!)
t
To help you get a full and clear reply using the tool call, the LLM can take the tool's result as context and craft a complete response. Here’s a friendly example to illustrate this:
Copy code
@function_tool
def lookup_weather(location: str):
    """Fetches weather information for a given location."""
    # Simulate a weather lookup
    return f"sunny with a temperature of 70 degrees in {location}."

# User input triggers the following flow:
user_input = "What is the weather in San Francisco?"

# LLM decides to call the tool
result = lookup_weather(location="San Francisco")

# LLM uses the tool result to generate a full reply
response = f"I checked the weather for you. The weather in San Francisco is {result}. It looks like a great day to go outside!"

# Agent speaks the response
print(response)  # Output: "I checked the weather for you. The weather in San Francisco is sunny with a temperature of 70 degrees. It looks like a great day to go outside!"
So, in this flow, the LLM takes the tool’s result and weaves it into a full, friendly response. The agent then shares this complete reply with you. If you’d like, I’m here to help with more details or additional examples—just let me know!
a
BUT THE RESPONSE IS PRESET IN THIS FLOW! I WANT THE RESPONSE TO BE BASED ON A PROMPT + the tool result; i.e. weather = ; prompt "Generate a reply based on the weather"
t
I'd love to help you understand how to generate a dynamic reply using a prompt and a tool result! You can use the
generate_reply()
method to guide the LLM in crafting a complete and thoughtful response. Here's a simple example to walk you through it:
Copy code
@function_tool()
def lookup_weather(location: str):
    """Fetches weather information for a given location."""
    # Simulate a weather lookup
    return f"sunny with a temperature of 70 degrees in {location}."

# User input triggers the following flow:
user_input = "What is the weather in San Francisco?"

# LLM decides to call the tool
result = lookup_weather(location="San Francisco")

# Generate a dynamic reply based on the tool result
session.generate_reply(
    instructions=f"Generate a reply based on the weather: {result}"
)
In this example, the tool result (like "sunny with a temperature of 70 degrees in San Francisco") is passed along with clear instructions to the LLM, helping it create a full, relevant reply. The agent then shares this dynamically generated response with the user. If you have any questions or want me to walk you through more examples, just let me know—I'm here to help! Sources: Agent speech and audio | LiveKit Docs | livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | Tool definition and use | LiveKit Docs | Real-time AI Models & Streaming | livekit/livekit_composite | DeepWiki
a
but what if i want the agent so speak first then call a tool then continue speaking based on the result of that tool
t
To help you have the agent speak first, then call a tool, and continue speaking based on the tool result, here’s a simple flow you can follow: 1. Initial Speech: The agent starts by generating and speaking an initial response, like "Let me check that for you." 2. Tool Execution: Next, the tool is called (for example, a weather lookup), and it returns its result. 3. Follow-Up Speech: Finally, the LLM uses that tool result to create a new response, which the agent then speaks. Here’s an example implementation to guide you:
Copy code
@function_tool()
def lookup_weather(location: str):
    """Fetches weather information for a given location."""
    # Simulate a weather lookup
    return f"sunny with a temperature of 70 degrees in {location}."

# Initial speech
session.say("Let me check the weather for you.")

# Call the tool
result = lookup_weather(location="San Francisco")

# Generate follow-up speech based on the tool result
session.generate_reply(
    instructions=f"Generate a reply based on the weather: {result}"
)
This way, the agent speaks first, then calls the tool, and continues the conversation based on what the tool returns. If you’d like me to walk you through this more or provide additional examples, just let me know—I’m here to help! Sources: agents/src/voice/agent_activity.ts | examples/warm-transfer/warm_transfer.py | Tool definition and use | LiveKit Docs
a
will that llm have context on what was first said?
t
Absolutely! The LLM does keep track of the initial context when it generates a follow-up reply after a tool call. LiveKit helps with this by using a chat context system that saves the entire conversation history, including the first thing said and any tool interactions. The results from the tool get added to this context, so the LLM can craft a response that thoughtfully combines both the original message and the tool’s output. This way, the agent’s follow-up feels natural and connected to the ongoing conversation. If you'd like, I’m here to walk you through more details or share some examples—just let me know! Sources: livekit-plugins/livekit-plugins-google/livekit/plugins/google/realtime/real...
a
what if i wanted this: LLM calls the tool; and generates an initial reply; when it has the result of the tool; it uses that to generate another reply; how would that work?
t
I'm happy to guide you through creating a flow where the LLM first calls a tool, generates an initial reply, and then follows up with another reply after receiving the tool result. Here's a simple way to approach it: 1. Initial Reply: The LLM starts by generating an initial response, like "Let me check that for you." 2. Tool Execution: The tool is called, and it returns the result. 3. Follow-Up Reply: The tool result is added to the chat context, and the LLM creates a new reply based on this information. Let me share an example implementation to make it clearer:
Copy code
@function_tool()
def lookup_weather(location: str):
    """Fetches weather information for a given location."""
    # Simulate a weather lookup
    return f"sunny with a temperature of 70 degrees in {location}."

# Initial reply
session.generate_reply(
    instructions="Let me check the weather for you."
)

# Call the tool
result = lookup_weather(location="San Francisco")

# Generate a follow-up reply based on the tool result
session.generate_reply(
    instructions=f"The weather in San Francisco is {result}."
)
This way, the LLM gives an initial response before the tool runs, then uses the tool's result to provide a thoughtful follow-up. If you have any questions or want me to walk you through more examples, just let me know—I'm here to help! Sources: Tool definition and use | LiveKit Docs | examples/voice_agents/multi_agent.py
a
can i add another generate reply after (i.e. before the utterance finishes?)
t
Thanks for your question! Just to clarify, you can’t start another
generate_reply
call before the previous one finishes without canceling the one that’s already running. If you do trigger a new
generate_reply
while the earlier one is still going, the first will be automatically canceled to make room for the new request. But don’t worry! If you want to stop the current speech smoothly before starting a new one, you can use the
SpeechHandle
object that
generate_reply
returns. This lets you gracefully interrupt the ongoing utterance. If you'd like, I’m here to help you with how to set this up—just let me know! Sources: plugins/google/src/beta/realtime/realtime_api.ts | tests/test_agent_session.py | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki