Agent System
Section titled “Agent System”Note: The template-based agent creation (
AgentTemplate, factory functions,BaseAgent) is deprecated. New code should useAgentManager.create_agent()which loads configuration from TOML files inconfig/courses/.
Migration Guide
Section titled “Migration Guide”The agent system has migrated from Python-based templates to TOML-based configuration.
Before (Deprecated)
Section titled “Before (Deprecated)”# Old approach - templates.pyfrom youlab_server.agents.templates import TUTOR_TEMPLATE, templatesfrom youlab_server.agents.default import create_custom_agentfrom youlab_server.memory.blocks import PersonaBlock, HumanBlock
agent = create_custom_agent( client=letta_client, name="tutor", role="AI tutor", capabilities=["Guide students", "Provide feedback"], ...)After (Recommended)
Section titled “After (Recommended)”[agent]type = "tutor"display_name = "My Course Coach"system_prompt = "You are an AI tutor..."
[agent.blocks.persona]name = "persona"label = "Persona"value = """[IDENTITY] Course Coach | AI tutor[CAPABILITIES] Guide students, Provide feedback[STYLE] warm, adaptive"""# Python code - use AgentManagerfrom youlab_server.server.agents import AgentManagerfrom youlab_server.curriculum.loader import load_course_config
config = load_course_config("my-course")agent_manager = AgentManager(letta_client)agent_state = await agent_manager.create_agent( user_id="user123", course_config=config,)Migration Steps
Section titled “Migration Steps”- Convert PersonaBlock to TOML blocks: Define your agent’s persona as a
[agent.blocks.persona]section in your course TOML file - Replace factory functions: Use
AgentManager.create_agent()instead ofcreate_*_agent()functions - Update imports: Remove imports from deprecated modules (
agents/templates,agents/default,agents/base,memory/blocks,memory/manager) - Use curriculum loader: Load configuration via
load_course_config()fromcurriculum/loader.py
Deprecated Modules
Section titled “Deprecated Modules”| Deprecated Module | Replacement |
|---|---|
agents/templates.py | config/courses/*/course.toml |
agents/default.py | AgentManager.create_agent() |
agents/base.py | Direct Letta agents via AgentManager |
memory/blocks.py (PersonaBlock/HumanBlock) | TOML-defined blocks |
memory/manager.py | Agent-driven memory via edit_memory_block tool |
memory/strategies.py | Not needed with agent-driven memory |
These modules emit DeprecationWarning on import and will be removed in a future version.
AgentManager (Recommended)
Section titled “AgentManager (Recommended)”The AgentManager class is the recommended way to create and manage agents.
Location: src/youlab_server/server/agents.py
Key Methods
Section titled “Key Methods”class AgentManager: async def create_agent( self, user_id: str, course_config: CourseConfig, user_name: str | None = None, ) -> AgentState: """Create a new agent from TOML course configuration."""
async def get_or_create_agent( self, user_id: str, course_config: CourseConfig, ) -> AgentState: """Get existing agent or create new one."""
async def send_message( self, user_id: str, message: str, course_config: CourseConfig, ) -> str: """Send message to user's agent."""
async def delete_agent(self, user_id: str, course_id: str) -> bool: """Delete user's agent."""Agent Naming Convention
Section titled “Agent Naming Convention”Agents are named using the pattern: youlab_{user_id}_{course_id}
This allows each user to have separate agents for different courses.
Legacy Documentation
Section titled “Legacy Documentation”Warning: The following sections document deprecated APIs. They are kept for reference during migration but should not be used in new code.
The agent system provides templates, factories, and runtime management for Letta agents.
Overview
Section titled “Overview”┌───────────────────────────────────────────────────────────────┐│ AgentTemplateRegistry ││ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ││ │ tutor │ │ coding │ │ research │ ... ││ │ Template │ │ Template │ │ Template │ ││ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │└─────────┼────────────────┼───────────────┼───────────────────┘ │ │ │ ▼ ▼ ▼┌───────────────────────────────────────────────────────────────┐│ Factory Functions ││ create_default_agent() create_coding_agent() create_...() │└─────────────────────────────┬─────────────────────────────────┘ │ ▼┌───────────────────────────────────────────────────────────────┐│ BaseAgent ││ • Integrated memory management (MemoryManager) ││ • Observability (Tracer, structlog) ││ • Message handling with Letta SDK │└─────────────────────────────────┬─────────────────────────────┘ │ ▼┌───────────────────────────────────────────────────────────────┐│ AgentRegistry ││ • Multi-agent coordination ││ • Named agent storage and retrieval │└───────────────────────────────────────────────────────────────┘Agent Templates
Section titled “Agent Templates”Templates define agent types with pre-configured personas.
Location: src/youlab_server/agents/templates.py
AgentTemplate Class
Section titled “AgentTemplate Class”class AgentTemplate(BaseModel): type_id: str # Unique identifier ("tutor") display_name: str # Human-readable ("College Essay Coach") description: str # Template description persona: PersonaBlock # Agent identity human: HumanBlock # Initial user context (usually empty) tools: list[Callable] # Tool functions available to agentTUTOR_TEMPLATE
Section titled “TUTOR_TEMPLATE”The primary template for college essay coaching:
TUTOR_TEMPLATE = AgentTemplate( type_id="tutor", display_name="College Essay Coach", description="Primary tutor for college essay writing course", persona=PersonaBlock( name="YouLab Essay Coach", role="AI tutor specializing in college application essays", capabilities=[ "Guide students through self-discovery exercises", "Help brainstorm and develop essay topics", "Provide constructive feedback on drafts", "Support emotional journey of college applications", ], expertise=[ "College admissions", "Personal narrative", "Reflective writing", "Strengths-based coaching", ], tone="warm", verbosity="adaptive", constraints=[ "Never write essays for students", "Always ask clarifying questions before giving advice", "Celebrate small wins and progress", ], ), human=HumanBlock(), # Empty, filled during onboarding)AgentTemplateRegistry
Section titled “AgentTemplateRegistry”Global registry for templates:
templates = AgentTemplateRegistry()
# Get templatetemplate = templates.get("tutor")
# List all typestypes = templates.list_types() # ["tutor"]
# Get all templatesall_templates = templates.get_all() # {"tutor": AgentTemplate(...)}
# Register custom templatetemplates.register(my_template)Factory Functions
Section titled “Factory Functions”Factory functions create agents with pre-configured settings.
Location: src/youlab_server/agents/default.py
Available Factories
Section titled “Available Factories”| Function | Persona | Use Case |
|---|---|---|
create_default_agent() | General assistant | Default conversations |
create_coding_agent() | Code helper | Development tasks |
create_research_agent() | Researcher | Analysis and synthesis |
create_custom_agent() | Custom | Fully configurable |
create_default_agent
Section titled “create_default_agent”agent = create_default_agent( client=letta_client, name="my-agent", tracer=optional_tracer,)Uses DEFAULT_PERSONA:
- Name: “Assistant”
- Tone: “friendly”
- Verbosity: “adaptive”
create_coding_agent
Section titled “create_coding_agent”agent = create_coding_agent( client=letta_client, name="code-helper", tracer=optional_tracer,)Uses CODING_ASSISTANT_PERSONA:
- Name: “CodeHelper”
- Expertise: Python, JavaScript, System design, Testing
- Constraints: Include error handling, prefer readability
Pre-configures preferences:
- “Type hints in code”
- “Detailed explanations”
create_research_agent
Section titled “create_research_agent”agent = create_research_agent( client=letta_client, name="researcher", tracer=optional_tracer,)Uses RESEARCH_ASSISTANT_PERSONA:
- Name: “Researcher”
- Expertise: Research methodology, Data analysis, Critical thinking
Pre-configures preferences:
- “Thorough analysis”
- “Cited sources”
create_custom_agent
Section titled “create_custom_agent”Fully customizable:
agent = create_custom_agent( client=letta_client, name="custom-agent", role="Custom agent role", capabilities=["Capability 1", "Capability 2"], expertise=["Domain 1", "Domain 2"], tone="professional", verbosity="concise", constraints=["Constraint 1"], user_name="Alice", user_role="Student", tracer=optional_tracer,)BaseAgent
Section titled “BaseAgent”The core agent class with integrated memory and observability.
Location: src/youlab_server/agents/base.py
Initialization
Section titled “Initialization”agent = BaseAgent( name="my-agent", persona=my_persona_block, human=my_human_block, client=letta_client, tracer=optional_tracer, max_memory_chars=1500,)On init:
- Serialize memory blocks
- Create agent in Letta (or retrieve existing)
- Initialize MemoryManager
- Log initialization
Core Methods
Section titled “Core Methods”send_message
Section titled “send_message”response = agent.send_message( message="Help me brainstorm essay topics", session_id="session-123",)Flow:
- Log “message_received”
- Wrap in
tracer.trace_llm_call() - Call
_send_message_internal() - Extract token usage for metrics
- Extract response text
- Log “message_sent”
- Return text
update_context
Section titled “update_context”agent.update_context( task="Brainstorm essay topics", note="Student interested in identity themes",)Updates the human block via MemoryManager.
agent.learn( preference="Prefers Socratic questions", fact="Studies computer science",)Records learned information in human block.
get_memory_summary
Section titled “get_memory_summary”summary = agent.get_memory_summary()# Returns:# {# "agent_id": "...",# "persona_usage": "45.2%",# "human_usage": "62.1%",# "session_state": "active_task",# "current_task": "Brainstorm topics",# ...# }search_memory
Section titled “search_memory”results = agent.search_memory( query="essay topics discussed", limit=5,)# Returns list of matching archival entriesAgentRegistry
Section titled “AgentRegistry”Manages multiple agent instances.
Location: src/youlab_server/agents/default.py:160-261
registry = AgentRegistry(client, tracer)
# Create and registeragent = registry.create_and_register( name="coding-assistant", agent_type="coding",)
# Get agentagent = registry.get("coding-assistant")
# List allnames = registry.list_agents()
# Removeremoved = registry.remove("coding-assistant")
# Countcount = len(registry)
# Check existenceif "coding-assistant" in registry: ...Supported Agent Types
Section titled “Supported Agent Types”| Type | Factory Used |
|---|---|
"default" | create_default_agent() |
"coding" | create_coding_agent() |
"research" | create_research_agent() |
HTTP Service Integration
Section titled “HTTP Service Integration”The HTTP service uses AgentManager (different from AgentRegistry):
# AgentManager for HTTP serviceclass AgentManager: # Naming convention def _agent_name(user_id, agent_type): return f"youlab_{user_id}_{agent_type}"
# Creates from template def create_agent(user_id, agent_type="tutor", user_name=None): template = templates.get(agent_type) # ... creates via Letta SDKKey differences:
| AgentRegistry | AgentManager |
|---|---|
| Multi-agent coordination | Per-user agent management |
| Named agents | User/type-based naming |
| In-memory storage | Letta storage + cache |
| For library use | For HTTP service |
Creating Custom Templates
Section titled “Creating Custom Templates”from youlab_server.agents.templates import AgentTemplate, templatesfrom youlab_server.memory.blocks import PersonaBlock, HumanBlock
# Define templateMY_TEMPLATE = AgentTemplate( type_id="counselor", display_name="College Counselor", description="Specialized counselor for college admissions", persona=PersonaBlock( name="Counselor", role="College admissions counselor", capabilities=[...], expertise=[...], tone="supportive", verbosity="detailed", constraints=[...], ), human=HumanBlock(),)
# Registertemplates.register(MY_TEMPLATE)
# Usetemplate = templates.get("counselor")Related Pages
Section titled “Related Pages”- Memory System - Memory blocks and strategies
- HTTP Service - AgentManager for web service
- Letta Reference - Underlying SDK patterns