i need to access the chat context from within a to...
# ask-ai
r
i need to access the chat context from within a tool, how to do that? the tool is defined outside the agent class initialisation
t
Thanks for reaching out, Taresh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To access the chat context from within a tool when the tool is defined outside the agent class initialization, follow these steps: 1. Define the Tool with Access to RunContext: Ensure the tool includes the
RunContext
as a parameter. This provides access to the current session and chat context.
Copy code
from livekit.agents import function_tool, RunContext

@function_tool()
async def my_tool(context: RunContext, other_params: str) -> dict:
    # Access chat context via context.chat_ctx
    chat_context = context.chat_ctx
    # Use the chat context as needed
    return {"result": "success"}
2. Add the Tool to the Agent Dynamically: After defining your agent, add the tool to its list of available tools using the
update_tools()
method.
Copy code
class MyAgent(Agent):
    async def __init__(self):
        super().__init__(instructions="My agent instructions")
        # Add the tool to the agent's tools
        await self.update_tools([my_tool])
3. Access Chat Context Within the Tool: The
RunContext
object passed to your tool includes the current chat context. You can access it via the
context.chat_ctx
property.
Copy code
@function_tool()
async def my_tool(context: RunContext, user_id: str) -> dict:
    chat_context = context.chat_ctx
    user_history = chat_context.items
    # Access the conversation history or other chat context details
    return {"user_history": user_history}
Let me know if you need further clarification or a more specific example!
r
getting this error using this method AttributeError: 'RunContext' object has no attribute 'chat_ctx'
t
Hey there! The error happens because the
RunContext
object doesn’t have a
chat_ctx
attribute directly. Instead, you can get to the chat context through the
session
property of
RunContext
. Here’s a quick fix for you:
Copy code
@function_tool()
async def example_function(context: RunContext):
    chat_context = context.session.chat_ctx
    # Use chat_context as needed
This way, you’re grabbing the chat context the right way according to LiveKit’s setup. If you want me to walk you through anything else, just let me know—I’m happy to help!
r
okay now how do I transfer the chat context from one agent to another during a handoff via a tool call?
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!