Using Context
Access request context for user tracking and custom data
This example shows how to use the optional ctx parameter to access request context like user IDs, conversation IDs, and custom fields.
The Agent
from reminix.runtime import Agent, serve, Context
agent = Agent("support", metadata={"description": "Customer support agent"})
@agent.invoke
async def handle_invoke(input_data: dict, ctx: Context) -> dict:
"""Process requests with user context."""
user_id = ctx.get("user_id")
custom = ctx.get("custom", {})
tenant_id = custom.get("tenant_id")
task = input_data.get("task", "")
return {
"output": f"Processing '{task}' for user {user_id} (tenant: {tenant_id})"
}
@agent.chat
async def handle_chat(messages: list, ctx: Context) -> dict:
"""Handle chat with conversation tracking."""
conversation_id = ctx.get("conversation_id")
user_id = ctx.get("user_id")
last_message = messages[-1]["content"] if messages else ""
# Use conversation_id for stateful conversations
greeting = f"[Conv: {conversation_id}] " if conversation_id else ""
user_note = f"(User: {user_id}) " if user_id else ""
return {
"message": {
"role": "assistant",
"content": f"{greeting}{user_note}You said: {last_message}",
}
}
if __name__ == "__main__":
serve(agent, port=8080)Context Fields
The ctx parameter is a TypedDict with these optional fields:
| Field | Type | Description |
|---|---|---|
conversation_id | str | Track multi-turn conversations |
user_id | str | Identify the user |
custom | dict | Any additional custom fields |
Testing
# Invoke with context
curl -X POST http://localhost:8080/agent/support/invoke \
-H "Content-Type: application/json" \
-d '{
"input": {"task": "check order status"},
"context": {
"user_id": "user_123",
"custom": {"tenant_id": "acme_corp"}
}
}'
# Chat with conversation context
curl -X POST http://localhost:8080/agent/support/chat \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": "Hello!"}],
"context": {
"conversation_id": "conv_abc",
"user_id": "user_123"
}
}'Response Examples
Invoke response:
{"output": "Processing 'check order status' for user user_123 (tenant: acme_corp)"}Chat response:
{"message": {"role": "assistant", "content": "[Conv: conv_abc] (User: user_123) You said: Hello!"}}Backward Compatibility
The ctx parameter is optional. Handlers without it continue to work:
# This still works - no ctx parameter
@agent.invoke
async def handle_invoke(input_data: dict) -> dict:
return {"output": "processed"}Next Steps
- Basic Agent - Simple agent setup
- Streaming - Stream responses