The Context Object

The context parameter provides access to conversation data and user information in your agent functions:
@agent("my-agent",auth=True)
async def my_agent(context):
    # Access conversation history
    user_info= context.user
    messages = context.messages
    
    yield f"user_info: {user_info}"
    yield f"\n\n messages: {messages}"
agent.push()

Context Properties

context
Context Object

Message Format

The context.messages follows the OpenAI message format:
[
    {"role": "user", "content": "Hello"},
    {"role": "assistant", "content": "Hi there!"},
    {"role": "user", "content": "How are you?"}
]

Working with Messages

@agent()
async def conversation_agent(context):
    # Get the latest user message
    latest_message = context.messages[-1]["content"]
    
    # Get all user messages
    user_messages = [msg for msg in context.messages if msg["role"] == "user"]
    
    # Get conversation length
    message_count = len(context.messages)
    
    return f"Last message: {latest_message}"

The User Object

When authentication is enabled, you can access user information through context.user:
The user object is only available when the agent is running on Cycls cloud. It will not be available during local development with agent.run().
@agent("my-agent", auth=True)
async def user_agent(context):
    # Access user information
    user_id = context.user.id
    user_name = context.user.name
    user_email = context.user.email
    user_org = context.user.org
    user_plans = context.user.plans
    
    return f"Hello, {user_name}!"

User Object Properties

context.user
User Object

Working with User Data

@agent("my-agent", auth=True)
async def personalized_agent(context):
    # Check user's subscription
    if "pro" in context.user.plans:
        return "Welcome back, Pro user!"
    
    # Use user's organization
    if context.user.org == "Acme Corp":
        return "Welcome to the Acme Corp team!"
    
    # Personalize response
    return f"Hello, {context.user.name}! How can I help you today?"

Authentication Requirements

Enabling Authentication

To access user data, you must enable authentication in your agent:
# In decorator
@agent("my-agent", auth=True)
async def authenticated_agent(context):
    return f"Hello, {context.user.name}!"

Authentication Flow

  1. User Authentication: Users must provide a JWT token
  2. Token Validation: Cycls validates the token and extracts user data
  3. User Object: The context.user object contains the decoded user information
  4. Agent Access: Your agent can now access personalized user data