Is there any guidance on when to use `self.session...
# agents
g
Is there any guidance on when to use
self.session.userdata
vs
context.userdata
? Seems like they are interchangeable and its confusing when to use which one.
🔖 1
✅ 1
r
In the context of Python agents within the LiveKit framework,
self.session.userdata
and
context.userdata
serve similar purposes but are used in different contexts, which can indeed be confusing. Here’s a breakdown of when to use each: 1.
self.session.userdata
: • This is typically used within the methods of an agent class. It provides access to the user data associated with the current session of the agent. • Use this when you are within an instance method of an agent and you want to access or modify the user data that is persistent throughout the session. • Example usage:
Copy code
class MyAgent(Agent):
         async def some_method(self):
             self.session.userdata.some_attribute = "new value"
2.
context.userdata
: • This is accessed within function tools or asynchronous methods that are passed a
RunContext
. It allows you to interact with the user data in the context of a specific function call. • Use this when you are implementing a function tool and need to work with the user data that is passed through the context. • Example usage:
Copy code
class MyAgent(Agent):
         @function_tool
         async def add_task(self, context: RunContext_T, task: str):
             context.userdata.tasks.append(task)
### Summary • Use
self.session.userdata
when you are inside an agent method and want to access the session's user data. • Use
context.userdata
when you are within a function tool and need to access the user data passed through the context. This distinction helps maintain clarity about where the user data is being accessed and modified, ensuring that the correct context is used for each operation. Notes: • Both
self.session.userdata
and
context.userdata
refer to the same underlying user data structure but are accessed in different scopes. • Understanding the context in which you are operating (agent method vs. function tool) is key to deciding which to use. See https://github.com/livekit-examples/python-agents-examples/blob/main/context-readmes/USERDATA_GUIDE.md
g
Thanks @refined-appointment-81829, this is helpful when to use which. I will say that some of the livekit examples had function tools which use agent helper methods. The agent helper methods use
self.session.userdata
despite them only being invoked via function tools. In that case, would you pass
context
downstream to the agent helper methods or stick with it using
self.session.userdata
? A good example from livekit's documentation is:
Copy code
class IntakeAgent(Agent):
    def __init__(self):
        super().__init__(
            instructions="""You are an intake agent. Learn the user's name and age."""
        )
        
    @function_tool()
    async def record_name(self, context: RunContext[MySessionInfo], name: str):
        """Use this tool to record the user's name."""
        context.userdata.user_name = name
        return self._handoff_if_done()
    
    @function_tool()
    async def record_age(self, context: RunContext[MySessionInfo], age: int):
        """Use this tool to record the user's age."""
        context.userdata.age = age
        return self._handoff_if_done()
    
    def _handoff_if_done(self):
        if self.session.userdata.user_name and self.session.userdata.age:
            return CustomerServiceAgent()
        else:
            return None

class CustomerServiceAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are a friendly customer service representative.")

    async def on_enter(self) -> None:
        userdata: MySessionInfo = self.session.userdata
        await self.session.generate_reply(
            instructions=f"Greet {userdata.user_name} personally and offer your assistance."
        )