SubAgent Middleware with Session Access Example
This example demonstrates how SubAgent middleware can access session history for post-execution processing.
Features Demonstrated
Pre-execution Processing
- Injecting context information (timestamps, user data, environment info)
- Modifying arguments before template rendering
Post-execution Processing
- Accessing session history via
result.Session
- Extracting metrics (message count, execution duration, token usage)
- Memory extraction from conversation history
- Modifying result data based on session analysis
Prerequisites
Set your OpenAI API key:
export OPENAI_API_KEY="your-api-key-here"
Running the Example
go run main.go
Code Structure
The middleware function demonstrates both phases:
func createMiddleware() func(gollem.SubAgentHandler) gollem.SubAgentHandler {
return func(next gollem.SubAgentHandler) gollem.SubAgentHandler {
return func(ctx context.Context, args map[string]any) (gollem.SubAgentResult, error) {
// Pre-execution: Inject context and start timer
startTime := time.Now()
args["_execution_time"] = startTime.Format(time.RFC3339)
args["_user_context"] = "Example user"
// Execute
result, err := next(ctx, args)
if err != nil {
return gollem.SubAgentResult{}, err
}
// Post-execution: Access session and extract insights
executionDuration := time.Since(startTime)
history, _ := result.Session.History()
if history != nil {
result.Data["metrics"] = map[string]any{
"message_count": len(history.Messages),
"execution_duration": executionDuration.String(),
}
}
return result, nil
}
}
}
Use Cases
This pattern is particularly useful for:
- Memory-aware Agents: Extract and save learned information from conversation history
- Record Extraction: Parse structured data from session responses
- Metrics Collection: Track token usage, execution time, and performance
- Context Injection: Add dynamic context based on user, environment, or system state
- Audit Logging: Record detailed execution traces for compliance
Key Concepts
- SubAgentResult: Contains both
Data (result for parent) and Session (for middleware)
- Session Access: Middleware can call
result.Session.History() to access conversation
- Read-only: Session is provided for analysis, not modification
- Error Handling: Session access errors should be handled gracefully (log and continue)
- See
CHANGELOG.md for migration guide from older versions
- See
docs/architecture.md for SubAgent architecture details