Updates Steward's output format to structured delegation format: - DELEGATE: [capability] to [action] [task] - REASON: [explanation] - COMPLEXITY: [simple/moderate/complex] - CONTEXT: [relevant history or "none"] Also adds guidance for conversation memory queries (handled by Tatlock directly, not delegated to Librarian). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
177 lines
6.1 KiB
Python
177 lines
6.1 KiB
Python
"""
|
|
Steward agent - First-tier request analyzer.
|
|
|
|
The Steward analyzes incoming requests, identifies relevant household
|
|
capabilities, and provides focused recommendations to Tatlock (the Butler).
|
|
This creates a two-tier architecture that prevents cognitive overload.
|
|
|
|
Uses plain text output (not JSON) for reliability with Ollama models.
|
|
"""
|
|
import httpx
|
|
from typing import Optional
|
|
|
|
from src.core.config import config
|
|
from src.core.household_registry import get_household_registry
|
|
from src.core.logging_config import get_logger
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
# System prompt for plain text recommendations
|
|
def build_steward_prompt(query: str, conversation_history: list[dict]) -> str:
|
|
"""Build the steward's analysis prompt with query and conversation history."""
|
|
|
|
# Get available capabilities from registry
|
|
registry = get_household_registry()
|
|
capabilities = registry.get_all_capabilities()
|
|
|
|
cap_list = []
|
|
for cap in capabilities:
|
|
cap_list.append(
|
|
f"• {cap.name} - {cap.description} (domains: {', '.join(cap.domains)})"
|
|
)
|
|
capabilities_text = "\n".join(cap_list)
|
|
|
|
# Format conversation history if present
|
|
history_text = ""
|
|
if conversation_history:
|
|
history_lines = []
|
|
for i, msg in enumerate(conversation_history):
|
|
role = msg.get("role", "unknown")
|
|
content = msg.get("content", "")[:100] # Truncate long messages
|
|
history_lines.append(f"{i}. {role}: {content}")
|
|
history_text = "\n\nCONVERSATION HISTORY:\n" + "\n".join(history_lines)
|
|
|
|
return f"""You are the Steward of the household, advising the Butler (Tatlock) on which capabilities to use.
|
|
|
|
AVAILABLE HOUSEHOLD CAPABILITIES:
|
|
{capabilities_text}
|
|
|
|
YOUR TASK:
|
|
Analyze the user's query and recommend which capabilities are needed, with specific delegation instructions.
|
|
{history_text}
|
|
|
|
USER QUERY: {query}
|
|
|
|
GUIDELINES:
|
|
- Be conservative - only recommend truly necessary capabilities
|
|
- Simple greetings/chat → no capabilities needed (conversational response only)
|
|
- Questions about prior conversation ("what did I say", "my name", "what we discussed") → no capabilities (Tatlock has full history)
|
|
- Math/calculations → tatlock_core
|
|
- Quick web searches → tatlock_core
|
|
- Time/date queries → tatlock_core
|
|
- Wiki creation ("create a page about X", "add X to wiki") → librarian with smart_create
|
|
- Wiki updates ("update the page", "add to dossier") → librarian with update
|
|
- Research queries ("find info", "what do we know about", "search for") → librarian with hybrid_search
|
|
- In-depth research, knowledge synthesis, document lookup → librarian with hybrid_search
|
|
- If conversation history is relevant, note which previous turns matter
|
|
- Assess complexity: simple (1 tool), moderate (2-3 tools), complex (multiple steps)
|
|
|
|
RESPOND IN THIS FORMAT:
|
|
DELEGATE: [capability name] to [action] [specific task]
|
|
REASON: [why this capability handles the request]
|
|
COMPLEXITY: [simple/moderate/complex]
|
|
CONTEXT: [any relevant conversation context, or "none"]
|
|
|
|
EXAMPLES:
|
|
- "DELEGATE: librarian to create a wiki page about CI/CD pipelines"
|
|
- "DELEGATE: librarian to search for information about Docker networking"
|
|
- "DELEGATE: tatlock_core to calculate the result"
|
|
- "DELEGATE: none (conversational response only)"
|
|
|
|
Be specific about what Tatlock should delegate - include the action verb (create, update, search, etc.).
|
|
Plain text only - no JSON, no special formatting."""
|
|
|
|
|
|
class StewardAgent:
|
|
"""
|
|
The Steward - Request analyzer and capability coordinator.
|
|
|
|
Analyzes requests with full conversation context and recommends
|
|
which household capabilities the Butler should use.
|
|
|
|
Uses plain text output for reliability with Ollama models.
|
|
"""
|
|
|
|
def __init__(self):
|
|
"""Initialize Steward with Ollama model (same as Tatlock for VRAM efficiency)."""
|
|
self.ollama_host = str(config.OLLAMA_HOST).rstrip('/')
|
|
self.model_name = config.OLLAMA_DEFAULT_MODEL
|
|
self.timeout = 30.0 # 30 second timeout for analysis
|
|
|
|
logger.info(
|
|
"steward_agent_created",
|
|
ollama_host=self.ollama_host,
|
|
model=self.model_name,
|
|
timeout=self.timeout,
|
|
)
|
|
|
|
async def analyze(
|
|
self,
|
|
query: str,
|
|
conversation_history: Optional[list[dict]] = None
|
|
) -> str:
|
|
"""
|
|
Analyze query and return plain text recommendation.
|
|
|
|
Args:
|
|
query: User's query to analyze
|
|
conversation_history: Previous conversation turns
|
|
|
|
Returns:
|
|
Plain text analysis from Steward
|
|
|
|
Example:
|
|
>>> text = await steward.analyze("What's 2 + 2?")
|
|
>>> print(text)
|
|
"This requires tatlock_core for mathematical calculations. Complexity: simple."
|
|
"""
|
|
history = conversation_history or []
|
|
prompt = build_steward_prompt(query, history)
|
|
|
|
logger.debug("steward_calling_ollama", query_preview=query[:100])
|
|
|
|
# Call Ollama API directly (more reliable than PydanticAI for plain text)
|
|
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
response = await client.post(
|
|
f"{self.ollama_host}/api/generate",
|
|
json={
|
|
"model": self.model_name,
|
|
"prompt": prompt,
|
|
"stream": False,
|
|
"options": {
|
|
"temperature": 0.3, # Lower = more consistent
|
|
"top_p": 0.9
|
|
}
|
|
}
|
|
)
|
|
|
|
response.raise_for_status()
|
|
result = response.json()
|
|
|
|
analysis_text = result["response"].strip()
|
|
|
|
logger.debug(
|
|
"steward_analysis_received",
|
|
text_preview=analysis_text[:150]
|
|
)
|
|
|
|
return analysis_text
|
|
|
|
|
|
# Global Steward instance
|
|
_steward_agent = None
|
|
|
|
|
|
def get_steward_agent() -> StewardAgent:
|
|
"""
|
|
Get the global Steward agent instance.
|
|
|
|
Returns:
|
|
StewardAgent instance
|
|
"""
|
|
global _steward_agent
|
|
if _steward_agent is None:
|
|
_steward_agent = StewardAgent()
|
|
return _steward_agent
|