Confucius Framework - Deep Dive Analysis

Overview

Confucius (also known as CCA - Claude Code Agent) is an LLM agent framework built on top of LangChain that emphasizes composability, observability, and extensibility. It uses a unique “Analect” abstraction for building reusable logic units and provides rich orchestration capabilities through an extension-based system.

Key Finding: Confucius IS built on LangChain. It uses langchain-core>=0.3.45 as a foundation, with Analects extending LangChain’s Runnable interface.

The “Analect” Naming

The name Analect is philosophically inspired by Confucius’s Analects (論語 - Lúnyǔ):

  • Analects: Classical collection of Confucius’s sayings and ideas
  • Philosophy: “Wisdom Through Composition” - Like Confucian philosophy, agents build wisdom through composable, reusable units of logic
  • The Analect is the fundamental abstraction: a reusable, composable unit of logic similar to a function but with full visibility into inputs, outputs, and runtime behavior

Key Insight: The Three-Axis Design (AX, UX, DX)

This is the most important architectural decision in Confucius. The framework explicitly separates three distinct experiences:

┌─────────────────────────────────────────────────────────────────────────────┐
│                     THREE-AXIS DESIGN: AX / UX / DX                          │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│                                                                              │
│   ┌─────────────────┐   ┌─────────────────┐   ┌─────────────────┐          │
│   │       AX        │   │       UX        │   │       DX        │          │
│   │ Agent Experience│   │ User Experience │   │ Dev Experience  │          │
│   └────────┬────────┘   └────────┬────────┘   └────────┬────────┘          │
│            │                     │                     │                    │
│            ▼                     ▼                     ▼                    │
│   ┌─────────────────┐   ┌─────────────────┐   ┌─────────────────┐          │
│   │ What the MODEL  │   │ What the USER   │   │ What DEVELOPERS │          │
│   │ sees internally │   │ sees externally │   │ can observe     │          │
│   └─────────────────┘   └─────────────────┘   └─────────────────┘          │
│            │                     │                     │                    │
│            │                     │                     │                    │
│   • Distilled memory    • Rich, formatted     • Full traces              │
│   • Compact summaries     output               • Both AX and UX           │
│   • Essential context   • Detailed diffs       • Debugging tools          │
│   • No verbose noise    • Progress updates     • Reproducibility          │
│   • Tool-use format     • Human-readable       • Ablation support         │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

Agent Experience (AX) vs User Experience (UX) - Concrete Example

┌─────────────────────────────────────────────────────────────────────────────┐
│                        AX vs UX: SAME ACTION, DIFFERENT VIEWS                │
└─────────────────────────────────────────────────────────────────────────────┘

╔═══════════════════════════════════════════════════════════════════════════╗
║                         UX (What User Sees)                                ║
╠═══════════════════════════════════════════════════════════════════════════╣
║                                                                            ║
║  Creating file at config.py                                                ║
║  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ║
║  File created successfully at config.py                                    ║
║                                                                            ║
║  + PORT=8080                                                               ║
║  + DEBUG=true                                                              ║
║  + DATABASE_URL=postgresql://localhost/mydb                                ║
║                                                                            ║
║  ✓ 3 lines added                                                          ║
║                                                                            ║
╚═══════════════════════════════════════════════════════════════════════════╝

╔═══════════════════════════════════════════════════════════════════════════╗
║                         AX (What Agent Sees)                               ║
╠═══════════════════════════════════════════════════════════════════════════╣
║                                                                            ║
║  Human: [previous user message about configuration]                        ║
║                                                                            ║
║  AI: <file_edit type="create" file_path="config.py">                      ║
║        PORT=8080                                                           ║
║        DEBUG=true                                                          ║
║        DATABASE_URL=postgresql://localhost/mydb                            ║
║      </file_edit>                                                          ║
║                                                                            ║
║  Human: <result status="success">File created successfully</result>       ║
║                                                                            ║
╚═══════════════════════════════════════════════════════════════════════════╝

Key Differences:
┌──────────────────┬────────────────────────────────────────────────────────┐
│ Aspect           │ Difference                                              │
├──────────────────┼────────────────────────────────────────────────────────┤
│ Formatting       │ UX: Rich, colored, with progress bars and icons        │
│                  │ AX: Minimal XML/tool-use format                         │
├──────────────────┼────────────────────────────────────────────────────────┤
│ Verbosity        │ UX: Detailed diffs, line counts, file paths            │
│                  │ AX: Compact result status only                          │
├──────────────────┼────────────────────────────────────────────────────────┤
│ Purpose          │ UX: Human understanding and trust                       │
│                  │ AX: Model reasoning and tool invocation                 │
├──────────────────┼────────────────────────────────────────────────────────┤
│ Memory Impact    │ UX: Not stored in agent memory                         │
│                  │ AX: Stored for context continuity                       │
└──────────────────┴────────────────────────────────────────────────────────┘

Why This Separation Matters

  1. AX Optimization: Agent context is kept minimal and focused

    • Verbose logs, raw diffs distract models and waste tokens
    • Summaries preserve essential state
  2. UX Quality: Users see rich, interpretable output

    • Builds trust through transparency
    • Detailed feedback on operations
  3. DX Power: Developers can observe everything

    • Full traces for debugging
    • Reproducible experiments
    • Ablation studies

Anthropic vs OpenAI Message Format

Confucius is Anthropic-native but supports OpenAI through adapters. Understanding this is crucial for customization.

Anthropic Tool-Use Format (Native)

# confucius/orchestrator/anthropic.py - Native format
 
class MessageContentToolUse(BaseModel):
    """Anthropic's native tool invocation format."""
    id: str                              # Unique tool call ID (e.g., "toolu_01abc...")
    name: str                            # Tool name (max 64 chars, [a-zA-Z0-9_-])
    input: dict[str, Any]               # Tool arguments as JSON
    type: Literal["tool_use"]
    cache_control: CacheControl | None   # Prompt caching hint
 
class MessageContentToolResult(BaseModel):
    """Anthropic's native tool result format."""
    tool_use_id: str                     # Must match the tool_use.id
    content: str | list[MessageContent]  # Result (text, image, etc.)
    type: Literal["tool_result"]
    is_error: bool | None                # Error flag
 
# Anthropic-specific content types:
# - TEXT: Plain text
# - TOOL_USE: Structured tool invocation
# - TOOL_RESULT: Tool execution result
# - IMAGE: Image content (base64 or URL)
# - THINKING: Extended thinking (Claude feature)
# - DOCUMENT: PDF or text documents

OpenAI Tool-Use Format (Adapted)

# confucius/core/chat_models/azure/openai.py - Adapted format
 
# OpenAI uses function_call / tool_calls structure:
{
    "role": "assistant",
    "content": null,
    "tool_calls": [
        {
            "id": "call_abc123",
            "type": "function",
            "function": {
                "name": "file_edit",
                "arguments": "{\"file_path\": \"config.py\", ...}"
            }
        }
    ]
}
 
# Confucius adapts this to Anthropic format internally:
class OpenAIChat(BaseChatModel):
    use_responses_api: bool = True  # Choose API variant
 
    # Compatibility fields - accept Anthropic format, convert internally
    thinking: ant.Thinking | None = None
    tool_choice: ant.ToolChoice | None = None
    tools: list[ant.ToolLike] | None = None

Format Comparison Table

┌──────────────────┬─────────────────────────────┬─────────────────────────────┐
│ Aspect           │ Anthropic (Native)          │ OpenAI (Adapted)            │
├──────────────────┼─────────────────────────────┼─────────────────────────────┤
│ Tool Call ID     │ toolu_01XYZ...              │ call_abc123                 │
├──────────────────┼─────────────────────────────┼─────────────────────────────┤
│ Name Constraints │ ^[a-zA-Z0-9_-]{1,64}$       │ More flexible               │
├──────────────────┼─────────────────────────────┼─────────────────────────────┤
│ Arguments        │ input: dict                  │ arguments: JSON string      │
├──────────────────┼─────────────────────────────┼─────────────────────────────┤
│ Result Format    │ tool_result with content    │ tool message with content   │
├──────────────────┼─────────────────────────────┼─────────────────────────────┤
│ Extended Think   │ Native (THINKING type)      │ Not supported               │
├──────────────────┼─────────────────────────────┼─────────────────────────────┤
│ Prompt Caching   │ Native (cache_control)      │ Not supported               │
├──────────────────┼─────────────────────────────┼─────────────────────────────┤
│ Beta Features    │ token-efficient-tools       │ N/A                         │
│                  │ interleaved-thinking        │                             │
└──────────────────┴─────────────────────────────┴─────────────────────────────┘

Tool Name Validation

# confucius/orchestrator/anthropic.py
 
TOOL_USE_NAME_PATTERN = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")
 
def _fix_tool_use(self, tool_use: ant.MessageContentToolUse):
    """Claude API requires tool names match '^[a-zA-Z0-9_-]{1,64}$'"""
    if not TOOL_USE_NAME_PATTERN.match(tool_use.name):
        # Replace invalid characters with underscores
        tool_use.name = NON_TOOL_USE_NAME_PATTERN.sub("_", tool_use.name)
        # Truncate if > 64 characters
        tool_use.name = tool_use.name[:64]

1. Code Structure

Directory Layout

confucius/
├── confucius/                    # Main package
│   ├── core/                     # Core abstractions
│   │   ├── analect/              # Analect base class
│   │   ├── entry/                # Entry points (main functions)
│   │   ├── io/                   # IOInterface (UX layer)
│   │   ├── memory.py             # Memory management (AX layer)
│   │   ├── artifact.py           # Versioned artifacts
│   │   ├── llm_manager/          # LLM management
│   │   └── chat_models/          # Provider implementations
│   ├── orchestrator/             # Orchestrator system
│   │   ├── base.py               # BaseOrchestrator
│   │   ├── llm.py                # LLMOrchestrator
│   │   ├── anthropic.py          # AnthropicLLMOrchestrator (native)
│   │   └── extensions/           # All tool extensions
│   ├── analects/                 # Built-in analects
│   │   ├── code/                 # Coding assistant (CCA)
│   │   └── note_taker/           # Note-taking agent
│   ├── lib/                      # Library utilities
│   ├── cli/                      # Command-line interface
│   └── output_parsers/           # XML/HTML parsing
├── docs/                         # Documentation
├── latex_source/                 # Paper source
└── requirements.txt              # Dependencies

Architecture with AX/UX Separation

┌─────────────────────────────────────────────────────────────────────────────┐
│                        CONFUCIUS ARCHITECTURE                                │
│                     (with AX/UX/DX Separation)                               │
└─────────────────────────────────────────────────────────────────────────────┘

                           ┌──────────────────────┐
                           │     Entry Point      │
                           │  (CLI / Application) │
                           └──────────┬───────────┘
                                      │
            ┌─────────────────────────┼─────────────────────────┐
            │                         │                         │
            ▼                         ▼                         ▼
   ┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
   │   IOInterface   │     │  AnalectRunner  │     │   Callbacks     │
   │   (UX Layer)    │     │  (AX Layer)     │     │   (DX Layer)    │
   │                 │     │                 │     │                 │
   │ • Rich console  │     │ • Memory mgmt   │     │ • Tracing       │
   │ • Progress bars │     │ • Context       │     │ • Logging       │
   │ • Colored diffs │     │ • Tool-use      │     │ • Metrics       │
   └─────────────────┘     └─────────────────┘     └─────────────────┘
            │                         │                         │
            └─────────────────────────┼─────────────────────────┘
                                      │
                                      ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                           ORCHESTRATOR LAYER                                 │
│                                                                              │
│  ┌────────────────────────────────────────────────────────────────────┐     │
│  │                    AnthropicLLMOrchestrator                         │     │
│  │                                                                      │     │
│  │   ┌─────────────────────────────────────────────────────────────┐   │     │
│  │   │ Anthropic-Native Features:                                   │   │     │
│  │   │ • Native tool_use / tool_result format                       │   │     │
│  │   │ • Extended thinking (THINKING content type)                  │   │     │
│  │   │ • Prompt caching (cache_control)                            │   │     │
│  │   │ • Beta tags: token-efficient-tools, interleaved-thinking    │   │     │
│  │   └─────────────────────────────────────────────────────────────┘   │     │
│  └────────────────────────────────────────────────────────────────────┘     │
│                                      │                                       │
│         ┌───────────────────────────┬┴────────────────────────────┐         │
│         ▼                           ▼                              ▼         │
│  ┌─────────────┐           ┌─────────────┐              ┌─────────────┐     │
│  │  Extension  │           │  Extension  │              │  Extension  │     │
│  │ CommandLine │           │  FileEdit   │              │  Thinking   │     │
│  │             │           │             │              │             │     │
│  │ Outputs to: │           │ Outputs to: │              │ Outputs to: │     │
│  │ • AX: <result>          │ • AX: <result>             │ • AX: stored│     │
│  │ • UX: formatted         │ • UX: diff view            │ • UX: hidden│     │
│  └─────────────┘           └─────────────┘              └─────────────┘     │
└─────────────────────────────────────────────────────────────────────────────┘
                                      │
                                      ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                               CORE LAYER                                     │
│                                                                              │
│  ┌───────────────────┐   ┌───────────────────┐   ┌───────────────────┐     │
│  │   CfMemoryManager │   │    IOInterface    │   │     Artifacts     │     │
│  │   (AX Storage)    │   │   (UX Output)     │   │   (Versioned)     │     │
│  │                   │   │                   │   │                   │     │
│  │ • Compact format  │   │ • print()         │   │ • DataFrames      │     │
│  │ • XML tags        │   │ • log()           │   │ • Plots           │     │
│  │ • Tool results    │   │ • ai() / human()  │   │ • HTML/Markdown   │     │
│  └───────────────────┘   └───────────────────┘   └───────────────────┘     │
└─────────────────────────────────────────────────────────────────────────────┘

2. Four Key Mechanisms (from Paper)

The paper identifies four key mechanisms that make Confucius effective:

1. Context Management (Long-Context Reasoning)

┌─────────────────────────────────────────────────────────────────────────────┐
│                         CONTEXT MANAGEMENT                                   │
└─────────────────────────────────────────────────────────────────────────────┘

Problem: Long conversations exceed context windows, degrade performance

Solution: Hierarchical working-memory with adaptive compression

┌─────────────────────────────────────────────────────────────────────────────┐
│                                                                              │
│   Full History (100k+ tokens)                                               │
│   ┌─────────────────────────────────────────────────────────────────────┐   │
│   │ Message 1 → Message 2 → ... → Message 50 → ... → Message 100        │   │
│   └─────────────────────────────────────────────────────────────────────┘   │
│                                    │                                         │
│                                    ▼                                         │
│                         ┌─────────────────────┐                             │
│                         │  Architect Planner  │                             │
│                         │  (Summarization)    │                             │
│                         └─────────────────────┘                             │
│                                    │                                         │
│                                    ▼                                         │
│   Compressed Context (fits in window)                                       │
│   ┌─────────────────────────────────────────────────────────────────────┐   │
│   │ ┌─────────────────────────────────────────────────────────────────┐ │   │
│   │ │ Structured Summary:                                              │ │   │
│   │ │ • Task goals: Fix authentication bug in auth.py                 │ │   │
│   │ │ • Decisions made: Using JWT instead of sessions                 │ │   │
│   │ │ • Open TODOs: Update tests, review security                     │ │   │
│   │ │ • Critical errors: TypeError at line 42 (fixed)                 │ │   │
│   │ └─────────────────────────────────────────────────────────────────┘ │   │
│   │ + Rolling window of last N messages                                 │   │
│   └─────────────────────────────────────────────────────────────────────┘   │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

Implementation: LLMPlannerExtension with TokenEstimatorExtension

2. Note-Taking Agent (Long-Term Memory)

┌─────────────────────────────────────────────────────────────────────────────┐
│                         NOTE-TAKING AGENT                                    │
└─────────────────────────────────────────────────────────────────────────────┘

Problem: Knowledge lost between sessions, rediscovering solutions

Solution: Persistent hierarchical Markdown notes with hindsight

┌─────────────────────────────────────────────────────────────────────────────┐
│                                                                              │
│   Memory Structure:                                                         │
│   hierarchical_memory/                                                       │
│   └── project_qutebrowser/                                                   │
│       ├── architecture.md          # System overview                        │
│       ├── research/                                                          │
│       │   └── findings.md          # Investigation notes                    │
│       └── solutions/                                                         │
│           ├── bug_fix_001.md       # Solution + hindsight                   │
│           └── performance.md       # Optimization notes                     │
│                                                                              │
│   Hindsight Notes (Key Innovation):                                         │
│   ┌─────────────────────────────────────────────────────────────────────┐   │
│   │ ## Bug Fix: Process Cleanup Issue                                    │   │
│   │                                                                      │   │
│   │ **Error**: RuntimeError: Event loop is closed                        │   │
│   │                                                                      │   │
│   │ **Root Cause**: Calling asyncio.run() after loop shutdown           │   │
│   │                                                                      │   │
│   │ **Solution**: Use asyncio.get_event_loop().run_until_complete()     │   │
│   │                                                                      │   │
│   │ **Hindsight**: Check loop state before running async code           │   │
│   │ in cleanup handlers. This pattern appears in signal handlers.       │   │
│   └─────────────────────────────────────────────────────────────────────┘   │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

Implementation: HierarchicalMemoryExtension, NoteTakerEntry

3. Extension System (Modular Tools)

# Each extension is a self-contained capability with hooks at every stage
 
class Extension(BaseModel):
    name: str
    included_in_system_prompt: bool
 
    # Lifecycle hooks (AX/UX separation happens here)
    async def on_input_messages(self, messages, context) -> messages  # Pre-process
    async def on_invoke_llm(self, messages, context) -> messages      # Before LLM
    async def on_llm_response(self, message, context) -> message      # After LLM
    async def on_llm_output(self, text, context) -> text              # Post-process
    async def on_tag(self, tag, context) -> None                      # Handle XML tag
    async def on_tool_use(self, tool_use, context) -> ToolResult      # Anthropic tool
 
# Example: FileEditExtension outputs differently to AX and UX
class FileEditExtension(Extension):
    async def on_tag(self, tag, context):
        # Execute the file operation
        result = await self._edit_file(tag)
 
        # AX: Compact result for model context
        context.memory_manager.add_message(CfMessage(
            type=MessageType.AI,
            content=f"<result status='{result.status}'>{result.summary}</result>"
        ))
 
        # UX: Rich output for user
        await context.io.print(f"[green]File edited: {tag['file_path']}[/green]")
        await context.io.print(result.diff_view)  # Colored diff

4. Meta-Agent (Automated Agent Design)

The Meta-Agent automates agent improvement through a build-test-improve loop:

  1. Build: Synthesize agent configurations (prompts, extensions)
  2. Test: Evaluate against regression tasks
  3. Improve: Propose modifications based on failures
  4. Repeat: CCA itself is the outcome of Meta-agent iterations

3. IOInterface - The UX Layer

# confucius/core/io/base.py
 
class IOInterface(ABC):
    """Abstract base for all user-facing output."""
 
    # Basic output
    async def print(self, text: str, **kwargs) -> None: ...
    async def log(self, text: str, **kwargs) -> None: ...
    async def error(self, text: str, **kwargs) -> None: ...
    async def warning(self, text: str, **kwargs) -> None: ...
 
    # Message-type specific (for conversation display)
    async def human(self, text: str, **kwargs) -> None: ...
    async def ai(self, text: str, **kwargs) -> None: ...
 
    # System status (progress, run info)
    async def system(
        self, text: str,
        progress: int | None = None,
        run_status: RunStatus | None = None,
        run_label: str | None = None,
        run_description: str | None = None,
        **kwargs
    ) -> None: ...
 
# confucius/core/io/std.py - Console implementation
class StdIOInterface(IOInterface):
    console: Console  # Rich library for styled output
 
    async def print(self, text, style=None, **kwargs):
        self.console.print(text, style=style)
 
    async def ai(self, text, **kwargs):
        self.console.print(f"[blue]AI:[/blue] {text}")

4. Performance Results (from Paper)

SWE-Bench-Pro Results

Backbone ModelScaffoldResolve Rate (Pass@1)
Claude 4 SonnetSWE-Agent42.7%
Claude 4 SonnetCCA (Confucius)45.5%
Claude 4.5 SonnetSWE-Agent43.6%
Claude 4.5 SonnetLive-SWE-Agent45.8%
Claude 4.5 SonnetCCA (Confucius)52.7%
Claude 4.5 OpusAnthropic System52.0%
Claude 4.5 OpusCCA (Confucius)54.3%

Key Insight: Agent scaffolding is as important as model capability. A weaker model with strong scaffolding (4.5 Sonnet + CCA = 52.7%) outperforms a stronger model with weaker scaffolding (4.5 Opus + proprietary = 52.0%).

Ablation Study Results

ModelContext MgmtTool UseResolve Rate
Claude 4 SonnetNoadvanced42.0%
Claude 4 SonnetYesadvanced48.6% (+6.6%)
Claude 4.5 SonnetNosimple44.0%
Claude 4.5 SonnetNoadvanced51.0%
Claude 4.5 SonnetYesadvanced51.6%

Context management provides +6.6% improvement on Claude 4 Sonnet.


5. Typical Workflow - Agent Lifecycle

┌─────────────────────────────────────────────────────────────────────────────┐
│                    CONFUCIUS AGENT LIFECYCLE (with AX/UX)                    │
└─────────────────────────────────────────────────────────────────────────────┘

    ┌────────────────┐
    │  User Input    │
    │  (Question)    │
    └───────┬────────┘
            │
            ▼
┌───────────────────────────────────────────────────────────────────────────────┐
│                           ORCHESTRATOR LOOP                                    │
│                                                                                │
│  ┌──────────────────────────────────────────────────────────────────────────┐ │
│  │ FOR iteration IN range(max_iterations):                                   │ │
│  │                                                                           │ │
│  │   ┌─────────────────────────────────────────────────────────────────┐    │ │
│  │   │ 1. COLLECT MEMORY (AX)                                           │    │ │
│  │   │    • Apply HistoryVisibility filter                              │    │ │
│  │   │    • Compress if needed (Context Management)                     │    │ │
│  │   │    • Format as Anthropic messages                                │    │ │
│  │   └─────────────────────────────────────────────────────────────────┘    │ │
│  │                              │                                            │ │
│  │                              ▼                                            │ │
│  │   ┌─────────────────────────────────────────────────────────────────┐    │ │
│  │   │ 2. LLM INVOCATION (Anthropic Native)                             │    │ │
│  │   │                                                                  │    │ │
│  │   │   messages = [system_prompt, ...memory_messages]                 │    │ │
│  │   │   tools = [ext.tools for ext in extensions]  # Anthropic format │    │ │
│  │   │                                                                  │    │ │
│  │   │   response = await claude.messages.create(                       │    │ │
│  │   │       model="claude-sonnet-4-5-20250929",                        │    │ │
│  │   │       messages=messages,                                         │    │ │
│  │   │       tools=tools,                                               │    │ │
│  │   │       betas=["token-efficient-tools", "interleaved-thinking"]    │    │ │
│  │   │   )                                                              │    │ │
│  │   └─────────────────────────────────────────────────────────────────┘    │ │
│  │                              │                                            │ │
│  │                              ▼                                            │ │
│  │   ┌─────────────────────────────────────────────────────────────────┐    │ │
│  │   │ 3. PROCESS RESPONSE                                              │    │ │
│  │   │                                                                  │    │ │
│  │   │   FOR content IN response.content:                               │    │ │
│  │   │                                                                  │    │ │
│  │   │     IF content.type == "tool_use":                               │    │ │
│  │   │       ┌─────────────────────────────────────────────────────┐   │    │ │
│  │   │       │ Execute tool via Extension.on_tool_use()             │   │    │ │
│  │   │       │                                                      │   │    │ │
│  │   │       │ AX: Store compact result in memory                   │   │    │ │
│  │   │       │     <result status="success">...</result>           │   │    │ │
│  │   │       │                                                      │   │    │ │
│  │   │       │ UX: Display rich output to user                      │   │    │ │
│  │   │       │     [green]✓ File created[/green]                   │   │    │ │
│  │   │       │     + line 1                                         │   │    │ │
│  │   │       │     + line 2                                         │   │    │ │
│  │   │       └─────────────────────────────────────────────────────┘   │    │ │
│  │   │                                                                  │    │ │
│  │   │     ELIF content.type == "thinking":                             │    │ │
│  │   │       • AX: Store thinking in context                            │    │ │
│  │   │       • UX: Optionally display (configurable)                    │    │ │
│  │   │                                                                  │    │ │
│  │   │     ELIF content.type == "text":                                 │    │ │
│  │   │       • Parse XML tags → Extension.on_tag()                      │    │ │
│  │   │       • Plain text → Extension.on_plain_text()                   │    │ │
│  │   └─────────────────────────────────────────────────────────────────┘    │ │
│  │                              │                                            │ │
│  │                              ▼                                            │ │
│  │   ┌─────────────────────────────────────────────────────────────────┐    │ │
│  │   │ 4. CHECK COMPLETION                                              │    │ │
│  │   │    IF has_tool_calls: CONTINUE LOOP                              │    │ │
│  │   │    ELSE: EXIT LOOP                                               │    │ │
│  │   └─────────────────────────────────────────────────────────────────┘    │ │
│  └──────────────────────────────────────────────────────────────────────────┘ │
└───────────────────────────────────────────────────────────────────────────────┘
            │
            ▼
    ┌────────────────┐
    │  User Output   │
    │  (via UX)      │
    └────────────────┘

6. CodeAssistEntry - The SWE-Bench Agent

This is the actual entry point for the coding assistant used in SWE-bench evaluations.

File: confucius/analects/code/entry.py

The Entry Point

@public
class CodeAssistEntry(Analect[EntryInput, EntryOutput], EntryAnalectMixin):
    """Coding Assist Analect - LLM-powered coding assistant"""
 
    async def impl(self, inp: EntryInput, context: AnalectRunContext) -> EntryOutput:
        # 1. Build task/system prompt
        task_def: str = get_task_definition(current_time=datetime.now().isoformat())
 
        # 2. Configure extensions (tools)
        extensions: list[Extension] = [
            LLMCodingArchitectExtension(),  # Context compression
            FileEditExtension(max_output_lines=1000, enable_tool_use=True),
            CommandLineExtension(allowed_commands=get_allowed_commands(), ...),
            FunctionExtension(functions=get_functions(), enable_tool_use=True),
            PlainTextExtension(),
            ThinkingExtension(enable_tool_use=True),
            TodoReminder(),
            HierarchicalMemoryExtension(),
            AnthropicPromptCaching(),
        ]
 
        # 3. Create orchestrator
        orchestrator = AnthropicLLMOrchestrator(
            llm_params=[CLAUDE_4_5_SONNET_THINKING],
            extensions=extensions,
        )
 
        # 4. Invoke with user question
        await context.invoke_analect(
            orchestrator,
            OrchestratorInput(
                messages=[CfMessage(type=MessageType.HUMAN, content=inp.question)],
                task=task_def,
            ),
        )
        return EntryOutput()

What Gets Passed to the LLM

┌─────────────────────────────────────────────────────────────────────────────┐
│                    LLM API CALL STRUCTURE                                    │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│ 1. SYSTEM PROMPT (task_def from tasks.py)                                   │
├─────────────────────────────────────────────────────────────────────────────┤
│ # Coding Assistant Task                                                      │
│                                                                              │
│ You are a coding assistant working inside a developer's repository.         │
│                                                                              │
│ Environment                                                                  │
│ - Current time: 2024-01-15T10:30:00                                         │
│ - You can plan your approach and then execute edits and commands            │
│                                                                              │
│ Your goals                                                                   │
│ 1. Understand the user's request and the current codebase context          │
│ 2. Propose a concrete plan (high level steps)                               │
│ 3. Execute the plan using tool-use tags provided by the extensions          │
│ 4. Keep outputs concise; prefer diffs and focused explanations              │
│                                                                              │
│ Rules                                                                        │
│ - Only use allowed commands surfaced by the command-line extension          │
│ - Prefer reading files before editing; show diffs when changing files       │
│ - Keep changes minimal, safe, and reversible                                │
│ - You MUST always use `str_replace_editor` tool to view or edit files       │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│ 2. TOOLS (collected from extensions with enable_tool_use=True)              │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│ From FileEditExtension:                                                      │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ {                                                                        │ │
│ │   "name": "str_replace_editor",                                         │ │
│ │   "type": "text_editor_20250124",  // Anthropic text editor tool        │ │
│ │   "description": "A tool for viewing and editing files..."             │ │
│ │ }                                                                        │ │
│ │                                                                          │ │
│ │ Commands: view, create, str_replace, insert, undo_edit                  │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│                                                                              │
│ From CommandLineExtension:                                                   │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ {                                                                        │ │
│ │   "name": "bash",                                                        │ │
│ │   "type": "bash_20250124",  // Anthropic bash tool                      │ │
│ │   "description": "Run bash commands..."                                 │ │
│ │ }                                                                        │ │
│ │                                                                          │ │
│ │ Allowed commands: pwd, ls, cat, head, tail, grep, find, git, python3...│ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│                                                                              │
│ From ThinkingExtension:                                                      │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ Extended thinking enabled via LLM params:                               │ │
│ │ {                                                                        │ │
│ │   "thinking": {"type": "enabled", "budget_tokens": 8192}               │ │
│ │ }                                                                        │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│ 3. MESSAGES (from memory_manager.get_memory_by_visibility)                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│ Initial Call:                                                               │
│ [                                                                            │
│   {"role": "user", "content": "Fix the bug in auth.py line 42"}            │
│ ]                                                                            │
│                                                                              │
│ After First Tool Use:                                                        │
│ [                                                                            │
│   {"role": "user", "content": "Fix the bug in auth.py line 42"},           │
│   {"role": "assistant", "content": [                                        │
│     {"type": "thinking", "thinking": "I need to view the file..."},        │
│     {"type": "tool_use", "id": "toolu_01X", "name": "str_replace_editor",  │
│      "input": {"command": "view", "path": "/workspace/auth.py",            │
│                "view_range": [35, 50]}}                                     │
│   ]},                                                                        │
│   {"role": "user", "content": [                                             │
│     {"type": "tool_result", "tool_use_id": "toolu_01X",                    │
│      "content": "<view file_path=\"/workspace/auth.py\">\n35: def..."}     │
│   ]}                                                                         │
│ ]                                                                            │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

Extensions and Their Tools

ExtensionTool NameOperationsPurpose
FileEditExtensionstr_replace_editorview, create, str_replace, insert, undo_editFile viewing/editing
CommandLineExtensionbashRun allowed commandsShell execution
ThinkingExtension(via LLM params)Extended thinkingChain-of-thought reasoning
LLMCodingArchitectExtension(internal)Context compressionMemory management
HierarchicalMemoryExtension(internal)Note-takingCross-session memory
TodoReminder(internal)Todo trackingTask management
AnthropicPromptCaching(internal)Cache controlToken efficiency

Allowed Commands (from commands.py)

def get_allowed_commands() -> Dict[str, str]:
    return {
        # Filesystem
        "pwd": "Print current working directory",
        "ls": "List directory contents",
        "cat": "Print file contents",
        "head": "Show first lines of a file",
        "tail": "Show last lines of a file",
        "find": "Search for files in a directory hierarchy",
        "cp": "Copy files and directories",
        "mv": "Move (rename) files",
        "rm": "Remove files or directories",
        "mkdir": "Create directories",
 
        # Text processing
        "grep": "Search for patterns in files",
        "sed": "Stream editor for filtering",
        "awk": "Text processing and data extraction",
        "sort": "Sort lines of text files",
 
        # Git
        "git": "Git version control (status, diff, add, commit, ...)",
 
        # Python
        "python3": "Run Python scripts",
 
        # Network
        "curl": "Transfer data from or to a server",
        "wget": "Non-interactive network downloader",
    }

LLM Parameters (from llm_params.py)

CLAUDE_4_5_SONNET_THINKING = LLMParams(
    model="claude-sonnet-4-5",
    initial_max_tokens=16384,
    temperature=0.3,
    top_p=0.7,
    additional_kwargs={
        "thinking": ant.Thinking(
            type=ant.ThinkingType.ENABLED,
            budget_tokens=8192,  # 8k tokens for thinking
        ).dict(),
    },
)

Tool Use Flow in Detail

# 1. Tools are collected from extensions
@property
async def tools(self) -> list[ant.ToolLike]:
    return [
        tool
        for ext in self._enabled_tool_use_extensions
        for tool in await ext.tools
    ]
 
# 2. Tools are added to LLM params
async def get_llm_params(self) -> LLMParams:
    llm_params = (await super().get_llm_params()).copy()
    if tools := (await self.tools):
        llm_params.additional_kwargs["tools"] = tools
        # Add beta tags for Claude 4.x
        if "claude-sonnet-4" in llm_params.model:
            llm_params = self._add_beta_tag(llm_params, INTERLEAVED_THINKING_TAG)
    return llm_params
 
# 3. LLM is called with tools
response = await claude.messages.create(
    model="claude-sonnet-4-5",
    messages=messages,
    tools=tools,           # <-- Tools passed here
    max_tokens=16384,
    temperature=0.3,
    betas=["interleaved-thinking-2025-05-14"],
    thinking={"type": "enabled", "budget_tokens": 8192},
)
 
# 4. Response is processed
async def _process_response(self, msg: BaseMessage, context) -> str:
    response = ant.Response.parse_obj(msg.response_metadata)
    for ct in response.content:
        if isinstance(ct, ant.MessageContentText):
            text_responses.append(ct.text)
        elif isinstance(ct, ant.MessageContentThinking):
            await self.on_thinking(ct, context)  # Store in memory (AX)
        elif isinstance(ct, ant.MessageContentToolUse):
            self._tool_use_queue.append(ct)      # Queue for execution
 
# 5. Tool uses are processed
async def _process_tool_use(self, tool_use, all_tool_names, context):
    # Add tool_use to memory (AX)
    context.memory_manager.add_messages([
        CfMessage(type=MessageType.AI, content=[tool_use.dict()])
    ])
 
    # Execute tool via extension
    for ext in self._enabled_tool_use_extensions:
        tool_result = await ext._on_tool_use(tool_use=tool_use, context=context)
        if tool_result:
            # Add tool_result to memory (AX)
            context.memory_manager.add_messages([
                CfMessage(type=MessageType.HUMAN, content=[tool_result.dict()])
            ])
            return tool_result
 
# 6. If tools were executed, loop again
async def _process_messages(self, task: str, context) -> None:
    await super()._process_messages(task, context)
    if self._tool_use_queue:
        await self._process_tool_use_queue(context)
        self._tool_use_queue.clear()
        await self._process_messages(task, context)  # LOOP AGAIN

Visual Flow for CodeAssistEntry

┌─────────────────────────────────────────────────────────────────────────────┐
│                     CODE ASSIST ENTRY FLOW                                   │
└─────────────────────────────────────────────────────────────────────────────┘

User: "Fix bug in auth.py"
         │
         ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ CodeAssistEntry.impl()                                                       │
│  │                                                                           │
│  ├── task_def = get_task_definition()   // System prompt                    │
│  ├── extensions = [FileEdit, CommandLine, Thinking, ...]  // 9 extensions  │
│  ├── orchestrator = AnthropicLLMOrchestrator(extensions)                    │
│  └── context.invoke_analect(orchestrator, OrchestratorInput(...))           │
└─────────────────────────────────────────────────────────────────────────────┘
         │
         ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ AnthropicLLMOrchestrator._process_messages()                                │
│  │                                                                           │
│  ├── get_llm_params()                                                        │
│  │   └── Collect tools: [str_replace_editor, bash]                          │
│  │   └── Add betas: [interleaved-thinking-2025-05-14]                       │
│  │                                                                           │
│  ├── LLM Call:                                                               │
│  │   ┌─────────────────────────────────────────────────────────────────────┐│
│  │   │ claude.messages.create(                                              ││
│  │   │   model="claude-sonnet-4-5",                                         ││
│  │   │   messages=[{"role": "user", "content": "Fix bug in auth.py"}],     ││
│  │   │   tools=[str_replace_editor, bash],                                 ││
│  │   │   thinking={"type": "enabled", "budget_tokens": 8192}               ││
│  │   │ )                                                                    ││
│  │   └─────────────────────────────────────────────────────────────────────┘│
│  │                                                                           │
│  ├── Response:                                                               │
│  │   ┌─────────────────────────────────────────────────────────────────────┐│
│  │   │ {                                                                    ││
│  │   │   "content": [                                                       ││
│  │   │     {"type": "thinking", "thinking": "Need to view auth.py..."},    ││
│  │   │     {"type": "tool_use", "name": "str_replace_editor",              ││
│  │   │      "input": {"command": "view", "path": "/workspace/auth.py"}}    ││
│  │   │   ]                                                                  ││
│  │   │ }                                                                    ││
│  │   └─────────────────────────────────────────────────────────────────────┘│
│  │                                                                           │
│  ├── Store thinking in memory (AX)                                          │
│  ├── Queue tool_use for execution                                           │
│  │                                                                           │
│  └── _process_tool_use_queue():                                              │
│      ├── Add tool_use to memory:                                             │
│      │   CfMessage(type=AI, content=[{tool_use...}])                        │
│      │                                                                       │
│      ├── Execute via FileEditExtension:                                     │
│      │   result = await ext._on_tool_use(tool_use)                          │
│      │   → Returns file content                                              │
│      │                                                                       │
│      ├── Add tool_result to memory:                                          │
│      │   CfMessage(type=HUMAN, content=[{tool_result...}])                  │
│      │                                                                       │
│      └── LOOP: await self._process_messages() again                         │
└─────────────────────────────────────────────────────────────────────────────┘
         │
         ▼
    (Continue until no more tool_use in response)
         │
         ▼
    Return EntryOutput()

7. Complete Orchestrator Cycle - Step by Step

The orchestrator is the heart of Confucius. Here’s the complete cycle with code and data flow:

Orchestrator Entry Point

# confucius/orchestrator/base.py
 
async def impl(
    self, inp: OrchestratorInput, context: AnalectRunContext
) -> OrchestratorOutput:
    # Step 1: Process and add input messages
    inp_msgs = await self.on_input_messages(inp.messages, context)
    await self.add_messages(inp_msgs, context)
 
    # Step 2: Main processing loop
    try:
        await self._process_messages(inp.task, context)
    except OrchestratorTermination:
        pass  # Clean exit
 
    return OrchestratorOutput()

The Main Loop

# confucius/orchestrator/base.py
 
async def _process_messages(self, task: str, context: AnalectRunContext) -> None:
    # Check iteration limit (default: 250)
    if self.max_iterations and self._num_iterations >= self.max_iterations:
        raise MaxIterationsReachedError(f"Max iterations: {self.max_iterations}")
 
    self._num_iterations += 1
 
    # Step 1: Get LLM response (returns parsed XML)
    root_tag = await self.get_root_tag(task, context)
 
    # Step 2: Process the XML response
    try:
        await self._process_root_tag(root_tag, context)
        await self.on_process_messages_complete(context)
    except OrchestratorInterruption as exc:
        # Extension interrupted - add messages and loop again
        await self._process_interruption(exc, context)
        await self._process_messages(task, context)  # Recursive call

LLM Invocation Details

# confucius/orchestrator/llm.py
 
async def get_root_tag(self, task: str, context: AnalectRunContext) -> bs4.Tag:
    # ┌─────────────────────────────────────────────────────────┐
    # │ STEP 1: COLLECT MEMORY (based on HistoryVisibility)     │
    # └─────────────────────────────────────────────────────────┘
    memory = context.memory_manager.get_memory_by_visibility(
        self.history_visibility,  # SESSION, ENTRY, ANALECT, or RUNNABLE
        include_children=self.include_child_history
    )
 
    # ┌─────────────────────────────────────────────────────────┐
    # │ STEP 2: EXTENSION HOOK - on_memory()                    │
    # │ (Context compression happens here via LLMPlannerExt)    │
    # └─────────────────────────────────────────────────────────┘
    memory = await self.on_memory(memory, context)
 
    # ┌─────────────────────────────────────────────────────────┐
    # │ STEP 3: CONVERT TO LLM MESSAGES                         │
    # └─────────────────────────────────────────────────────────┘
    mem_messages = await memory.to_lc_messages()  # CfMessage → BaseMessage
 
    # ┌─────────────────────────────────────────────────────────┐
    # │ STEP 4: FORMAT PROMPT WITH TASK                         │
    # └─────────────────────────────────────────────────────────┘
    messages = (self.prompt + mem_messages).format_messages(
        task=await self.get_task(task)
    )
 
    # ┌─────────────────────────────────────────────────────────┐
    # │ STEP 5: EXTENSION HOOK - on_invoke_llm()                │
    # │ (Plan injection happens here)                           │
    # └─────────────────────────────────────────────────────────┘
    messages = await self.on_invoke_llm(messages=messages, context=context)
 
    # ┌─────────────────────────────────────────────────────────┐
    # │ STEP 6: GET LLM AND INVOKE                              │
    # └─────────────────────────────────────────────────────────┘
    chat = context.llm_manager._get_chat(params=await self.get_llm_params())
    res: str = await self._invoke_llm_impl(chat=chat, messages=messages, context=context)
 
    # ┌─────────────────────────────────────────────────────────┐
    # │ STEP 7: EXTENSION HOOK - on_llm_output()                │
    # └─────────────────────────────────────────────────────────┘
    res = await self.on_llm_output(res, context)
 
    # ┌─────────────────────────────────────────────────────────┐
    # │ STEP 8: PARSE AS XML                                    │
    # └─────────────────────────────────────────────────────────┘
    parsed = await context.invoke(self.raw_output_parser, res)
    return parsed.soup.find(self.raw_output_parser.root_tag)

Anthropic Response Processing

# confucius/orchestrator/anthropic.py
 
async def _process_response(self, msg: BaseMessage, context: AnalectRunContext) -> str:
    response = ant.Response.parse_obj(msg.response_metadata)
    text_responses = []
 
    for ct in response.content:
        if isinstance(ct, ant.MessageContentText):
            # Text content → will be parsed as XML
            text_responses.append(ct.text)
 
        elif isinstance(ct, ant.MessageContentThinking):
            # Extended thinking → stored in AX, optionally shown in UX
            await self.on_thinking(ct, context)
 
        elif isinstance(ct, ant.MessageContentToolUse):
            # Tool call → queued for execution after text processing
            self._tool_use_queue.append(self._fix_tool_use(ct))
 
    return "\n".join(text_responses)

Tool Use Cycle

# confucius/orchestrator/anthropic.py
 
async def _process_messages(self, task: str, context: AnalectRunContext) -> None:
    # Process text response first
    await super()._process_messages(task, context)
 
    # Then process any queued tool uses
    if self._tool_use_queue:
        try:
            await self._process_tool_use_queue(context)
        finally:
            self._tool_use_queue.clear()
 
        # After tool execution, LOOP AGAIN for next LLM response
        await self._process_messages(task, context)
 
async def _process_tool_use_queue(self, context: AnalectRunContext) -> None:
    for tool_use in self._tool_use_queue:
        # 1. Before hook for extensions
        for ext in self._tool_use_observers:
            await ext.on_before_tool_use(tool_use=tool_use, context=context)
 
        # 2. Add tool_use to memory (AX)
        context.memory_manager.add_messages([
            CfMessage(type=MessageType.AI, content=[tool_use.dict()])
        ])
 
        # 3. Execute tool via extension
        tool_result = await self._process_tool_use(tool_use, all_tool_names, context)
 
        # 4. Add tool_result to memory (AX)
        context.memory_manager.add_messages([
            CfMessage(type=MessageType.HUMAN, content=[tool_result.dict()])
        ])
 
        # 5. After hook for extensions
        for ext in self._tool_use_observers:
            await ext.on_after_tool_use_result(
                tool_use=tool_use, tool_result=tool_result, context=context
            )

Visual Flow Diagram

┌─────────────────────────────────────────────────────────────────────────────┐
│                       COMPLETE ORCHESTRATOR CYCLE                            │
└─────────────────────────────────────────────────────────────────────────────┘

     User Input
         │
         ▼
    ┌─────────────────────────────────────────────────────────────────────┐
    │ ITERATION LOOP (max_iterations: 250)                                 │
    │                                                                      │
    │    ┌─────────────────────────────────────────────────────────────┐  │
    │    │ 1. COLLECT MEMORY                                           │  │
    │    │    memory = get_memory_by_visibility(SESSION)               │  │
    │    │    └── Returns: [msg1, msg2, ..., msgN]                     │  │
    │    └─────────────────────────────────────────────────────────────┘  │
    │                              │                                       │
    │                              ▼                                       │
    │    ┌─────────────────────────────────────────────────────────────┐  │
    │    │ 2. CONTEXT COMPRESSION (LLMPlannerExtension.on_memory)      │  │
    │    │    IF tokens > 70k:                                         │  │
    │    │       • Mark old messages for omission                      │  │
    │    │       • Generate structured plan summary                    │  │
    │    │       • Inject plan as new human message                    │  │
    │    │    └── Returns: compressed memory                           │  │
    │    └─────────────────────────────────────────────────────────────┘  │
    │                              │                                       │
    │                              ▼                                       │
    │    ┌─────────────────────────────────────────────────────────────┐  │
    │    │ 3. LLM INVOCATION                                           │  │
    │    │    response = claude.messages.create(                       │  │
    │    │        model="claude-sonnet-4-5",                           │  │
    │    │        messages=[system_prompt, ...memory],                 │  │
    │    │        tools=[ext.tools for ext in extensions],             │  │
    │    │        betas=["token-efficient-tools"]                      │  │
    │    │    )                                                        │  │
    │    └─────────────────────────────────────────────────────────────┘  │
    │                              │                                       │
    │         ┌────────────────────┼────────────────────┐                 │
    │         ▼                    ▼                    ▼                 │
    │    ┌─────────┐         ┌──────────┐        ┌───────────┐           │
    │    │  TEXT   │         │ THINKING │        │ TOOL_USE  │           │
    │    │ content │         │ content  │        │ content   │           │
    │    └────┬────┘         └────┬─────┘        └─────┬─────┘           │
    │         │                   │                    │                  │
    │         ▼                   ▼                    ▼                  │
    │    Parse XML &         Store in AX         Queue for              │
    │    Extension.on_tag    (optionally UX)     execution              │
    │                                                  │                  │
    │    ┌─────────────────────────────────────────────┘                 │
    │    │                                                                │
    │    ▼                                                                │
    │    ┌─────────────────────────────────────────────────────────────┐  │
    │    │ 4. TOOL EXECUTION LOOP                                      │  │
    │    │    FOR tool_use IN _tool_use_queue:                         │  │
    │    │        • Add tool_use to memory (AX)                        │  │
    │    │        • Execute via Extension.on_tool_use()                │  │
    │    │        • Add tool_result to memory (AX)                     │  │
    │    │        • Display in UX                                      │  │
    │    └─────────────────────────────────────────────────────────────┘  │
    │                              │                                       │
    │                              ▼                                       │
    │    ┌─────────────────────────────────────────────────────────────┐  │
    │    │ 5. CHECK COMPLETION                                         │  │
    │    │    IF _tool_use_queue was not empty:                        │  │
    │    │        → LOOP AGAIN (step 1)                                │  │
    │    │    ELSE:                                                    │  │
    │    │        → EXIT LOOP                                          │  │
    │    └─────────────────────────────────────────────────────────────┘  │
    └─────────────────────────────────────────────────────────────────────┘
         │
         ▼
    Return OrchestratorOutput()

LLM Call Output Format

Each LLM call returns an Anthropic Response with structured content:

# Example LLM Response (what Claude returns)
{
    "id": "msg_01XYZ...",
    "type": "message",
    "role": "assistant",
    "content": [
        {
            "type": "thinking",
            "thinking": "I need to analyze the bug in auth.py..."
        },
        {
            "type": "text",
            "text": "I'll fix the authentication bug by updating the token validation."
        },
        {
            "type": "tool_use",
            "id": "toolu_01ABC...",
            "name": "file_edit",
            "input": {
                "file_path": "/workspace/auth.py",
                "old_string": "if token:",
                "new_string": "if token and validate_token(token):"
            }
        }
    ],
    "stop_reason": "tool_use",
    "usage": {"input_tokens": 1234, "output_tokens": 567}
}

How LLM Calls Chain Together

Call 1: Initial analysis
    → Response: THINKING + TEXT (no tools)
    → Result: Observation stored, no loop

Call 2: Tool execution
    → Response: THINKING + TOOL_USE(file_edit)
    → Result: Execute file_edit, store result, LOOP

Call 3: Verify change
    → Response: THINKING + TOOL_USE(command_line: "python -m pytest")
    → Result: Execute tests, store result, LOOP

Call 4: Report success
    → Response: TEXT only (no tools)
    → Result: No tool calls, EXIT LOOP

7. Key Components

AnthropicLLMOrchestrator

# confucius/orchestrator/anthropic.py
 
class AnthropicLLMOrchestrator(LLMOrchestrator):
    """Orchestrator optimized for Anthropic Claude models."""
 
    tool_choice: ant.ToolChoice | None = None  # auto, any, tool
    _tool_use_queue: list[ant.MessageContentToolUse] = []
 
    # Beta feature tags
    TOKEN_EFFICIENT_BETA_TAG = "token-efficient-tools-2025-02-19"
    INTERLEAVED_THINKING_TAG = "interleaved-thinking-2025-05-14"
 
    async def _process_response(self, msg, context):
        """Process Anthropic response with native tool-use."""
        response = ant.Response.parse_obj(msg.response_metadata)
 
        for content in response.content:
            if isinstance(content, ant.MessageContentToolUse):
                # Queue for execution
                self._tool_use_queue.append(self._fix_tool_use(content))
 
            elif isinstance(content, ant.MessageContentThinking):
                # Extended thinking (AX only, optionally UX)
                await self.on_thinking(content, context)
 
            elif isinstance(content, ant.MessageContentText):
                # Text content (may contain XML tags)
                await self._process_text(content.text, context)

Extension Examples

# FileEditExtension - Different AX/UX outputs
class FileEditExtension(ToolUseExtension):
    display_diff: bool = True           # UX: Show colored diff
    display_diff_context_lines: int = 5 # UX: Context around changes
 
    async def on_tool_use(self, tool_use, context):
        result = await self._edit_file(tool_use.input)
 
        # AX: Compact result for model
        # (via ToolResult return value)
 
        # UX: Rich output for user
        if self.display_diff:
            await context.io.print(result.colored_diff)
 
        return ant.MessageContentToolResult(
            tool_use_id=tool_use.id,
            content=f"File edited: {result.summary}"  # AX sees this
        )
 
# CommandLineExtension - Command execution
class CommandLineExtension(ToolUseExtension):
    max_output_lines: int = 100         # Limit for AX
    allowed_commands: dict[str, str]    # Whitelist
    disallowed_commands: dict[str, str] # Blacklist
 
    async def on_tool_use(self, tool_use, context):
        # Execute command
        output = await self._run_command(tool_use.input["command"])
 
        # AX: Truncated output
        ax_output = self._truncate(output, self.max_output_lines)
 
        # UX: Full output with styling
        await context.io.print(f"[dim]$ {tool_use.input['command']}[/dim]")
        await context.io.print(output)
 
        return ant.MessageContentToolResult(
            tool_use_id=tool_use.id,
            content=ax_output
        )

7. Memory Hierarchy - In Depth

The memory hierarchy is central to how Confucius manages context. Each level represents a different scope of message visibility.

HistoryVisibility Enum

# confucius/core/memory.py
 
class HistoryVisibility(Enum):
    SESSION = "session"   # Broadest: all messages in entire session
    ENTRY = "entry"       # Filter by entry_name (e.g., "Code", "Research")
    ANALECT = "analect"   # Current context only (local messages)
    RUNNABLE = "runnable" # Filter by runnable class name

Visual Hierarchy

┌─────────────────────────────────────────────────────────────────────────────┐
│                           MEMORY HIERARCHY                                   │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ROOT_SESSION_CONTEXT (entry_name=None, path=[])                            │
│  ├── memory: CfMemory(messages=[initial system message])                    │
│  ├── parent_memory: None                                                     │
│  │                                                                           │
│  └── ENTRY_CONTEXT (entry_name="Code", path=["CodeEntry"])                  │
│      ├── memory: CfMemory(messages=[user question, agent response, ...])    │
│      ├── parent_memory: ROOT_SESSION_CONTEXT ◄─── Link to parent            │
│      │                                                                       │
│      └── ORCHESTRATOR_CONTEXT (path=["CodeEntry", "LLMOrchestrator"])       │
│          ├── memory: CfMemory(messages=[tool calls, tool results, ...])     │
│          ├── parent_memory: ENTRY_CONTEXT ◄─── Link to parent               │
│          │                                                                   │
│          └── EXTENSION_CONTEXT (path=["CodeEntry", "LLMOrch", "FileEdit"])  │
│              ├── memory: CfMemory(messages=[file edit results])              │
│              └── parent_memory: ORCHESTRATOR_CONTEXT                         │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

Concrete Examples

Example 1: SESSION Level

# Gets ALL messages from root to current, including all entries
memory = context.memory_manager.get_memory_by_visibility(
    HistoryVisibility.SESSION,
    include_children=True
)
 
# Result: All messages ever exchanged in this session
# [
#   CfMessage(type=SYS, content="System initialized"),           # Root
#   CfMessage(type=HUMAN, entry_name="Code", content="Fix bug"), # Code entry
#   CfMessage(type=AI, entry_name="Code", content="<file_edit>"),
#   CfMessage(type=HUMAN, entry_name="Code", content="<result>"),
#   CfMessage(type=HUMAN, entry_name="Research", content="..."), # Research entry
# ]

Example 2: ENTRY Level

# Gets only messages tagged with current entry_name
memory = context.memory_manager.get_memory_by_visibility(
    HistoryVisibility.ENTRY,  # Filter by entry_name="Code"
    include_children=True
)
 
# Result: Only "Code" entry messages, excluding "Research" entry
# [
#   CfMessage(type=HUMAN, entry_name="Code", content="Fix bug in auth.py"),
#   CfMessage(type=AI, entry_name="Code", content="<file_edit>"),
#   CfMessage(type=HUMAN, entry_name="Code", content="<result>"),
# ]

Example 3: ANALECT Level

# Gets only messages in current local memory (no parent search)
memory = context.memory_manager.get_memory_by_visibility(
    HistoryVisibility.ANALECT,
    include_children=False  # Exclude child contexts too
)
 
# Result: Only messages added by current orchestrator/analect
# [
#   CfMessage(type=AI, content="<file_edit file_path='auth.py'>"),
#   CfMessage(type=HUMAN, content="<result status='success'>"),
# ]

Example 4: RUNNABLE Level

# Gets messages from a specific runnable class across the hierarchy
memory = context.memory_manager.get_memory_by_visibility(
    HistoryVisibility.RUNNABLE  # Filters by runnable_name
)
 
# Result: Only messages from FileEditExtension across all levels
# [
#   CfMessage(runnable_name="FileEditExtension", content="<result>"),
#   CfMessage(runnable_name="FileEditExtension", content="<result>"),
# ]

Message Structure (CfMessage)

class CfMessage(BaseModel):
    # Tagging fields (auto-populated by add_messages)
    entry_name: Optional[str] = None      # Which entry: "Code", "Research"
    runnable_name: Optional[str] = None   # Which class: "LLMOrchestrator"
    path: List[str] = []                  # Hierarchy: ["CodeEntry", "LLMOrch"]
 
    # Content fields
    type: MessageType = MessageType.HUMAN  # HUMAN, AI, SYS, ERR, ARTIFACT
    content: str | list[dict] = ""         # Text or tool_use/tool_result
    attachments: List[MessageAttachment] = []
 
    # Metadata
    additional_kwargs: dict = {}           # For filter_status, etc.
    _sequence_id: int                      # Auto-assigned ordering
 
# When you call add_messages(), the manager auto-tags:
context.memory_manager.add_messages([
    CfMessage(type=MessageType.AI, content="Hello")
])
# Result message has: entry_name="Code", runnable_name="LLMOrchestrator",
#                     path=["CodeEntry", "LLMOrchestrator"]

How Messages Flow Between Levels

# confucius/core/analect/analect.py - Child context creation
 
async with self.child_context_and_callbacks(
    runnable=FileEditExtension(),
    child_context_options=options
) as (child_context, callbacks):
 
    # Child has its own memory manager linked to parent
    # child_context.memory_manager.parent_memory = parent_memory_manager
 
    # Child adds messages to its local memory
    child_context.memory_manager.add_messages([
        CfMessage(type=MessageType.HUMAN, content="File edit result")
    ])
 
# On exit: consolidate_messages() pulls child messages up to parent
# with optional filtering by message type

Note: This is AX memory (what the model sees).
UX output is separate and managed by IOInterface.


9. Concrete SWE-Bench Example - Full Lifecycle

Here’s a complete walkthrough of how Confucius handles a real SWE-bench task:

Task: Fix Bug in Django Issue #12345

Problem: QuerySet.filter() raises TypeError when using __in lookup with empty list.

Step-by-Step Lifecycle

┌─────────────────────────────────────────────────────────────────────────────┐
│                    SWE-BENCH TASK LIFECYCLE                                  │
└─────────────────────────────────────────────────────────────────────────────┘

INITIAL STATE:
├── User Input: "Fix the bug where QuerySet.filter(id__in=[]) raises TypeError"
├── Repository: /workspace/django
└── Test: tests/queries/test_lookups.py::TestInLookup::test_empty_list

════════════════════════════════════════════════════════════════════════════════

ITERATION 1: EXPLORATION
─────────────────────────

┌── LLM Call 1 ───────────────────────────────────────────────────────────────┐
│ Input (AX):                                                                  │
│   System: "You are a coding assistant. Task: Fix bug..."                    │
│   Human: "Fix the bug where QuerySet.filter(id__in=[]) raises TypeError"    │
│                                                                              │
│ Output:                                                                      │
│   {                                                                          │
│     "content": [                                                             │
│       {"type": "thinking", "thinking": "I need to locate the __in lookup   │
│        implementation and understand when it receives an empty list..."},   │
│       {"type": "tool_use", "name": "command_line",                          │
│        "input": {"command": "grep -r 'def.*__in' django/db/models/"}}       │
│     ]                                                                        │
│   }                                                                          │
└──────────────────────────────────────────────────────────────────────────────┘

┌── Memory After Iteration 1 (AX) ────────────────────────────────────────────┐
│ [                                                                            │
│   CfMessage(type=HUMAN, content="Fix the bug..."),                          │
│   CfMessage(type=AI, content=[{tool_use: command_line, ...}]),              │
│   CfMessage(type=HUMAN, content=[{tool_result: "Found: lookups.py:245"}])   │
│ ]                                                                            │
└──────────────────────────────────────────────────────────────────────────────┘

┌── UX Output ────────────────────────────────────────────────────────────────┐
│ [dim]$ grep -r 'def.*__in' django/db/models/[/dim]                          │
│ django/db/models/lookups.py:245:    def resolve_expression_in(self, ...     │
│ django/db/models/lookups.py:267:    class In(Lookup):                       │
└──────────────────────────────────────────────────────────────────────────────┘

════════════════════════════════════════════════════════════════════════════════

ITERATION 2: READ FILE
──────────────────────

┌── LLM Call 2 ───────────────────────────────────────────────────────────────┐
│ Input (AX): [Previous memory + tool result]                                 │
│                                                                              │
│ Output:                                                                      │
│   {                                                                          │
│     "content": [                                                             │
│       {"type": "thinking", "thinking": "I found the In lookup at line 267. │
│        Let me read the implementation to understand the empty list case."}, │
│       {"type": "tool_use", "name": "file_read",                             │
│        "input": {"file_path": "django/db/models/lookups.py",                │
│                  "line_start": 260, "line_end": 320}}                       │
│     ]                                                                        │
│   }                                                                          │
└──────────────────────────────────────────────────────────────────────────────┘

┌── Memory After Iteration 2 (AX) ────────────────────────────────────────────┐
│ [                                                                            │
│   ...previous messages...,                                                   │
│   CfMessage(type=AI, content=[{tool_use: file_read, ...}]),                 │
│   CfMessage(type=HUMAN, content=[{tool_result:                              │
│     "class In(Lookup):\n    lookup_name = 'in'\n\n    def get_rhs_op..."    │
│   }])                                                                        │
│ ]                                                                            │
└──────────────────────────────────────────────────────────────────────────────┘

════════════════════════════════════════════════════════════════════════════════

ITERATION 3: IDENTIFY BUG
─────────────────────────

┌── LLM Call 3 ───────────────────────────────────────────────────────────────┐
│ Input (AX): [Previous memory + file content]                                 │
│                                                                              │
│ Output:                                                                      │
│   {                                                                          │
│     "content": [                                                             │
│       {"type": "thinking", "thinking": "I see the issue! Line 289:          │
│        'for val in self.rhs:' will fail if rhs is empty and gets            │
│        processed differently. The fix should check for empty list first."}, │
│       {"type": "text", "text": "Found the bug! The In lookup doesn't        │
│        handle empty lists before processing."}                              │
│     ]                                                                        │
│   }                                                                          │
└──────────────────────────────────────────────────────────────────────────────┘

┌── Memory After Iteration 3 (AX) ────────────────────────────────────────────┐
│ [                                                                            │
│   ...previous messages...,                                                   │
│   CfMessage(type=AI, content="Found the bug! The In lookup...")             │
│ ]                                                                            │
│                                                                              │
│ Note: No tool call → EXIT LOOP... Wait, more work needed → CONTINUE         │
└──────────────────────────────────────────────────────────────────────────────┘

════════════════════════════════════════════════════════════════════════════════

ITERATION 4: APPLY FIX
──────────────────────

┌── LLM Call 4 ───────────────────────────────────────────────────────────────┐
│ Input (AX): [Previous memory]                                                │
│                                                                              │
│ Output:                                                                      │
│   {                                                                          │
│     "content": [                                                             │
│       {"type": "thinking", "thinking": "Now I'll fix it by adding an        │
│        early return for empty lists that returns a valid empty expression."},│
│       {"type": "tool_use", "name": "file_edit",                             │
│        "input": {                                                            │
│          "file_path": "django/db/models/lookups.py",                        │
│          "old_string": "    def get_rhs_op(self, connection, rhs):\n        │
│                         return 'IN (%s)' % rhs",                            │
│          "new_string": "    def get_rhs_op(self, connection, rhs):\n        │
│                         if not self.rhs:\n                                  │
│                             return '1=0'  # Empty list, no matches\n        │
│                         return 'IN (%s)' % rhs"                             │
│        }}                                                                    │
│     ]                                                                        │
│   }                                                                          │
└──────────────────────────────────────────────────────────────────────────────┘

┌── Memory After Iteration 4 (AX) ────────────────────────────────────────────┐
│ [                                                                            │
│   ...previous messages...,                                                   │
│   CfMessage(type=AI, content=[{tool_use: file_edit, ...}]),                 │
│   CfMessage(type=HUMAN, content=[{tool_result: "File edited successfully",  │
│                                   is_error: false}])                        │
│ ]                                                                            │
└──────────────────────────────────────────────────────────────────────────────┘

┌── UX Output ────────────────────────────────────────────────────────────────┐
│ [green]✓ Edited django/db/models/lookups.py[/green]                         │
│                                                                              │
│    def get_rhs_op(self, connection, rhs):                                   │
│ +      if not self.rhs:                                                     │
│ +          return '1=0'  # Empty list, no matches                           │
│        return 'IN (%s)' % rhs                                               │
│                                                                              │
│ [dim]3 lines added, 0 removed[/dim]                                         │
└──────────────────────────────────────────────────────────────────────────────┘

════════════════════════════════════════════════════════════════════════════════

ITERATION 5: RUN TESTS
──────────────────────

┌── LLM Call 5 ───────────────────────────────────────────────────────────────┐
│ Input (AX): [Previous memory + file edit result]                            │
│                                                                              │
│ Output:                                                                      │
│   {                                                                          │
│     "content": [                                                             │
│       {"type": "thinking", "thinking": "Fix applied. Now I need to          │
│        verify it works by running the relevant tests."},                    │
│       {"type": "tool_use", "name": "command_line",                          │
│        "input": {"command": "cd /workspace/django && python -m pytest       │
│                  tests/queries/test_lookups.py::TestInLookup -v"}}          │
│     ]                                                                        │
│   }                                                                          │
└──────────────────────────────────────────────────────────────────────────────┘

┌── Memory After Iteration 5 (AX) ────────────────────────────────────────────┐
│ [                                                                            │
│   ...previous messages...,                                                   │
│   CfMessage(type=AI, content=[{tool_use: command_line, ...}]),              │
│   CfMessage(type=HUMAN, content=[{tool_result:                              │
│     "===== 5 passed in 0.42s =====" }])                                     │
│ ]                                                                            │
└──────────────────────────────────────────────────────────────────────────────┘

════════════════════════════════════════════════════════════════════════════════

ITERATION 6: COMPLETION
───────────────────────

┌── LLM Call 6 ───────────────────────────────────────────────────────────────┐
│ Input (AX): [Previous memory + test results]                                │
│                                                                              │
│ Output:                                                                      │
│   {                                                                          │
│     "content": [                                                             │
│       {"type": "text", "text": "The bug has been fixed. The In lookup       │
│        now handles empty lists by returning '1=0' which is a valid SQL      │
│        expression that matches no rows. All 5 tests pass."}                 │
│     ]                                                                        │
│   }                                                                          │
└──────────────────────────────────────────────────────────────────────────────┘

┌── No tool_use → EXIT ORCHESTRATOR LOOP ─────────────────────────────────────┐
│ Total iterations: 6                                                          │
│ Total LLM calls: 6                                                           │
│ Tools used: command_line (2), file_read (1), file_edit (1)                  │
└──────────────────────────────────────────────────────────────────────────────┘

Memory Snapshot at Each Stage

# After Iteration 1 (initial search)
memory.messages = [
    CfMessage(type=HUMAN, entry_name="Code",
              content="Fix the bug where QuerySet.filter(id__in=[])..."),
    CfMessage(type=AI, entry_name="Code", runnable_name="LLMOrchestrator",
              content=[{"type": "tool_use", "name": "command_line", ...}]),
    CfMessage(type=HUMAN, entry_name="Code", runnable_name="CommandLineExt",
              content=[{"type": "tool_result", "content": "Found: lookups.py:245"}]),
]
 
# After Iteration 6 (completion)
memory.messages = [
    CfMessage(type=HUMAN, content="Fix the bug..."),
    CfMessage(type=AI, content=[{tool_use: command_line}]),
    CfMessage(type=HUMAN, content=[{tool_result: "Found: lookups.py:245"}]),
    CfMessage(type=AI, content=[{tool_use: file_read}]),
    CfMessage(type=HUMAN, content=[{tool_result: "class In(Lookup):..."}]),
    CfMessage(type=AI, content="Found the bug! The In lookup..."),
    CfMessage(type=AI, content=[{tool_use: file_edit}]),
    CfMessage(type=HUMAN, content=[{tool_result: "File edited successfully"}]),
    CfMessage(type=AI, content=[{tool_use: command_line}]),
    CfMessage(type=HUMAN, content=[{tool_result: "5 passed in 0.42s"}]),
    CfMessage(type=AI, content="The bug has been fixed..."),
]

10. Context Management - The Architect Mechanism

When conversations grow too long, the LLMPlannerExtension (the “Architect”) intelligently compresses context.

Token Thresholds

# confucius/orchestrator/extensions/plan/llm.py
 
class LLMPlannerExtension(TokenEstimatorExtension):
    max_prompt_length: int = 70000  # Trigger compression above this
    min_prompt_length: int = 50000  # Target size after compression
    max_num_messages: int = 500     # Alternative trigger
    start_index: int = 1            # Skip first message (user's original request)

Compression Decision Algorithm

async def on_memory(self, memory: CfMemory, context: AnalectRunContext) -> CfMemory:
    # Step 1: Filter out previously omitted messages
    memory.messages = [
        msg for msg in memory.messages
        if msg.additional_kwargs.get("_filter_status") != "OMITTED"
    ]
 
    # Step 2: Estimate total tokens
    prompt_lengths = await self.get_prompt_token_lengths(memory.messages)
    total_length = sum(prompt_lengths)
 
    # Step 3: Check if compression needed
    if total_length <= self.max_prompt_length and len(memory.messages) <= self.max_num_messages:
        return memory  # No compression needed
 
    # Step 4: Mark messages for omission (keep first message)
    for i in range(self.start_index, len(memory.messages)):
        if total_length <= self.min_prompt_length and memory.messages[i].type == MessageType.AI:
            break  # Reached target size
 
        memory.messages[i].additional_kwargs["_filter_status"] = "WILL_BE_OMITTED"
        self._messages_to_be_omitted.append(memory.messages[i])
        total_length -= prompt_lengths[i]
 
    return memory

Plan Generation

When messages are marked for omission, the Architect generates a structured summary:

async def _on_invoke_llm(self, messages: list[BaseMessage], context: AnalectRunContext):
    if not self._messages_to_be_omitted:
        return messages
 
    # Generate plan using LLM
    plan_text = await self._get_plan_text(messages, context)
 
    # Add plan as new message
    plan_msg = CfMessage(content=plan_text, type=MessageType.HUMAN)
    context.memory_manager.add_messages([plan_msg])
 
    # Remove omitted messages, keep plan
    messages = [
        msg for msg in messages
        if msg.additional_kwargs.get("_filter_status") != "WILL_BE_OMITTED"
    ] + [await plan_msg.to_lc_message()]
 
    return messages

Structured Plan Format

┌─────────────────────────────────────────────────────────────────────────────┐
│                     ARCHITECT PLAN STRUCTURE                                 │
└─────────────────────────────────────────────────────────────────────────────┘

[CONVERSATION CONTEXT]
- Initial Requirements: Fix QuerySet.filter(id__in=[]) TypeError
- Scope Changes: None
- User Preferences: Minimal changes, maintain backwards compatibility

[TECHNICAL DECISIONS]
- Architecture Decisions: Handle empty list at lookup level, not query level
- Technology Stack: Django ORM, SQLite/PostgreSQL compatible
- Design Patterns: Early return pattern for edge cases

[IMPLEMENTATION PROGRESS]
- Completed Work: Located bug in lookups.py:267-290
- Current State: Fix applied to get_rhs_op method
- Failed Attempts: None
- Debugging History: Traced through In lookup class

[TECHNICAL DETAILS]
- Data Structures: In(Lookup) class with rhs attribute
- Algorithms: SQL generation with empty list check
- Edge Cases: Empty list, None values, mixed types

[OUTSTANDING ITEMS]
- Known Issues: None after fix
- Open Questions: None
- TODOs: Run full test suite

[PLAN]
<thinking>Fix applied successfully, tests pass.</thinking>
<step sequence_num="1">Verify fix with additional edge cases if needed</step>

Visual Flow

┌─────────────────────────────────────────────────────────────────────────────┐
│                       CONTEXT COMPRESSION FLOW                               │
└─────────────────────────────────────────────────────────────────────────────┘

BEFORE COMPRESSION (85k tokens):
┌─────────────────────────────────────────────────────────────────────────────┐
│ [User Request] [Msg2] [Msg3] ... [Msg45] [Msg46] ... [Msg100] [Latest...]   │
│      1k          5k     5k        40k      5k         20k       9k          │
│                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                       │
│                      TO BE COMPRESSED (65k tokens)                          │
└─────────────────────────────────────────────────────────────────────────────┘

                                    │
                                    ▼
                         ┌─────────────────────┐
                         │  ARCHITECT PLANNER  │
                         │  (Summarization)    │
                         └─────────────────────┘
                                    │
                                    ▼

AFTER COMPRESSION (25k tokens):
┌─────────────────────────────────────────────────────────────────────────────┐
│ [User Request] [STRUCTURED PLAN SUMMARY] [Latest Msg46...Msg100]           │
│      1k               5k                       19k                          │
│              ^^^^^^^^^^^^^^^^^^^^                                           │
│              Replaces 65k of history                                        │
└─────────────────────────────────────────────────────────────────────────────┘

Token Estimation

# confucius/orchestrator/extensions/token/utils.py
 
async def get_prompt_token_lengths(
    messages: list[CfMessage],
    num_chars_per_token: float = 3.0,  # Default estimate
) -> list[int]:
    lengths = []
    for msg in messages:
        attachment_length = await _get_text_attachment_length(msg)
        lengths.append(
            math.ceil(
                (len(get_content_str(msg.content)) + attachment_length)
                / num_chars_per_token
            )
        )
    return lengths

11. How Conversation is Stored

In-Memory Storage (Default)

# During execution, messages are stored in CfMemoryManager
 
class CfMemoryManager(BaseModel):
    memory: CfMemory = CfMemory()           # Local messages
    parent_memory: CfMemoryManager | None   # Link to parent context
 
    def add_messages(self, messages: List[CfMessage]) -> None:
        with self._memory_lock:  # Thread-safe
            for msg in messages:
                # Auto-tag with context info
                msg.entry_name = self.entry_name
                msg.runnable_name = self.runnable.get_name() if self.runnable else None
                msg.path = self.path.copy()
            self.memory.add_messages(messages)

Persistence (Optional)

# Save to disk
await context.memory_manager.save("/path/to/session.json")
 
# Load from disk
manager = await CfMemoryManager().load("/path/to/session.json")
 
# JSON format:
{
    "memory": {
        "messages": [
            {
                "entry_name": "Code",
                "runnable_name": "LLMOrchestrator",
                "path": ["CodeEntry", "LLMOrchestrator"],
                "type": "HUMAN",
                "content": "Fix the bug...",
                "_sequence_id": 1
            },
            ...
        ]
    },
    "parent_memory": null,
    "entry_name": "Code",
    "path": ["CodeEntry"]
}

Cross-Session via Notes

# HierarchicalMemoryExtension persists knowledge to markdown files
 
hierarchical_memory/
└── project_django/
    ├── architecture.md       # System overview
    ├── research/
    │   └── orm_internals.md  # ORM investigation notes
    └── solutions/
        ├── empty_list_fix.md # This solution + hindsight
        └── performance.md    # Performance notes
 
# Example note (empty_list_fix.md):
"""
## Bug Fix: QuerySet.filter(id__in=[]) TypeError
 
**Error**: TypeError when filtering with empty list
 
**Root Cause**: In lookup class doesn't handle empty rhs
 
**Solution**: Added early return with '1=0' SQL expression
 
**Hindsight**: Always check for empty iterables before processing
in database lookup implementations. This pattern should be applied
to other lookups like __range and __between.
"""

12. Training with RL via Agent Lightning

Agent Lightning can train Confucius agents using RL algorithms. Here’s how to connect them:

Integration Architecture

┌─────────────────────────────────────────────────────────────────────────────┐
│                    AGENT LIGHTNING + CONFUCIUS                               │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│                         AGENT LIGHTNING                                      │
│  ┌─────────────┐   ┌─────────────┐   ┌─────────────┐   ┌─────────────┐     │
│  │   Trainer   │   │  Algorithm  │   │    Store    │   │   Runners   │     │
│  │             │──▶│  (APO/PPO)  │──▶│ (rollouts)  │──▶│  (workers)  │     │
│  └─────────────┘   └─────────────┘   └─────────────┘   └──────┬──────┘     │
│                                                                │            │
└────────────────────────────────────────────────────────────────│────────────┘
                                                                 │
                                                                 ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                           LitAgent WRAPPER                                   │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │ class ConfuciusTrainableAgent(LitAgent[dict]):                        │   │
│  │                                                                       │   │
│  │     def training_rollout(self, task: dict) -> float:                 │   │
│  │         # Run Confucius on task                                       │   │
│  │         result = self.confucius.run(entry, input)                    │   │
│  │         # Evaluate and return reward                                  │   │
│  │         return self._evaluate(result, task["expected"])              │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                         │
└────────────────────────────────────│─────────────────────────────────────────┘
                                     │
                                     ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                            CONFUCIUS                                         │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                    CodeAssistEntry                                    │    │
│  │  ├── LLMOrchestrator                                                 │    │
│  │  ├── Extensions (FileEdit, CommandLine, ...)                         │    │
│  │  └── CfMemoryManager                                                 │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────────────────┘

Complete Training Code

# train_confucius.py
 
from agentlightning import Trainer, LitAgent
from agentlightning.algorithm import APO  # Automatic Prompt Optimization
from agentlightning.store import InMemoryLightningStore
from confucius import Confucius
from confucius.analects.code import CodeAssistEntry
from confucius.core.entry import EntryInput, EntryOutput
 
 
class ConfuciusTrainableAgent(LitAgent[dict]):
    """Wraps Confucius for Agent Lightning training."""
 
    def __init__(self):
        super().__init__()
        self.cf = Confucius()
        self.entry = CodeAssistEntry()
 
    async def training_rollout(self, task: dict) -> float:
        """
        Execute one training episode.
        Returns reward (0.0-1.0) based on task success.
        """
        # Run Confucius on the SWE-bench task
        try:
            result: EntryOutput = await self.cf.run(
                entry=self.entry,
                input=EntryInput(
                    question=task["problem_statement"],
                    workspace=task["repo_path"],
                )
            )
 
            # Evaluate the result
            return self._evaluate(result, task)
 
        except Exception as e:
            # Failed execution = 0 reward
            self.log(f"Rollout failed: {e}")
            return 0.0
 
    def _evaluate(self, result: EntryOutput, task: dict) -> float:
        """
        Evaluate agent output against expected solution.
        """
        # Run the test suite
        import subprocess
        test_result = subprocess.run(
            ["python", "-m", "pytest", task["test_file"], "-v"],
            cwd=task["repo_path"],
            capture_output=True,
            timeout=60
        )
 
        if test_result.returncode == 0:
            return 1.0  # All tests pass
 
        # Partial credit based on tests passed
        output = test_result.stdout.decode()
        if "passed" in output:
            passed = int(output.split(" passed")[0].split()[-1])
            total = passed + int(output.split(" failed")[0].split()[-1])
            return passed / total
 
        return 0.0  # All tests failed
 
    @property
    def resources(self) -> dict:
        """
        Return learnable resources that APO can optimize.
        These are the prompts/configurations that will be improved.
        """
        return {
            "system_prompt": self.entry.orchestrator.prompt,
            "extensions_config": [ext.dict() for ext in self.entry.orchestrator.extensions],
            "llm_params": self.entry.orchestrator.llm_params,
        }
 
    def update_resources(self, new_resources: dict) -> None:
        """
        Apply optimized resources from APO.
        """
        if "system_prompt" in new_resources:
            self.entry.orchestrator.prompt = new_resources["system_prompt"]
        # ... apply other resource updates
 
 
# Training script
async def main():
    # Load SWE-bench tasks
    swe_bench_tasks = [
        {
            "problem_statement": "Fix QuerySet.filter(id__in=[]) TypeError",
            "repo_path": "/workspace/django",
            "test_file": "tests/queries/test_lookups.py",
            "expected_patch": "...",
        },
        # ... more tasks
    ]
 
    # Initialize trainer with APO algorithm
    trainer = Trainer(
        algorithm=APO(
            n_rounds=5,         # Number of optimization rounds
            beam_size=3,        # Keep top 3 prompts per round
            mutation_rate=0.2,  # Prompt mutation rate
        ),
        store=InMemoryLightningStore(),
    )
 
    # Train the agent
    agent = ConfuciusTrainableAgent()
 
    await trainer.fit(
        agent=agent,
        train_dataset=swe_bench_tasks[:100],  # Training set
        val_dataset=swe_bench_tasks[100:120], # Validation set
        epochs=10,
    )
 
    # Save optimized resources
    optimized_resources = trainer.get_best_resources()
    with open("optimized_confucius.json", "w") as f:
        json.dump(optimized_resources, f)
 
 
if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Using VERL PPO for RL Training

from agentlightning.algorithm import VERLPPO
 
trainer = Trainer(
    algorithm=VERLPPO(
        learning_rate=1e-5,
        ppo_epochs=4,
        clip_range=0.2,
        value_loss_coef=0.5,
        entropy_coef=0.01,
    ),
    store=SQLiteLightningStore("training_runs.db"),
)
 
# VERL PPO optimizes the LLM weights directly
# Requires access to model parameters

What Gets Optimized

ResourceAPOVERL PPO
System promptsYesYes
Extension configsYesNo
Tool descriptionsYesYes
LLM weightsNoYes
Few-shot examplesYesNo

Collecting Training Spans

Agent Lightning collects execution traces (spans) for training:

class ConfuciusTrainableAgent(LitAgent[dict]):
    async def training_rollout(self, task: dict) -> float:
        # Spans are automatically collected
        with self.span("analyze_task"):
            analysis = await self._analyze(task)
 
        with self.span("execute_solution"):
            result = await self.cf.run(...)
 
        with self.span("evaluate_result"):
            reward = self._evaluate(result, task)
 
        return reward
 
# Spans provide:
# - Execution traces for debugging
# - Input/output pairs for training
# - Timing information for optimization
# - Error traces for failure analysis

Evaluation Loop

# After training, evaluate on held-out test set
test_results = await trainer.evaluate(
    agent=agent,
    test_dataset=swe_bench_tasks[120:],
)
 
print(f"Test accuracy: {test_results.accuracy:.2%}")
print(f"Average reward: {test_results.avg_reward:.3f}")
print(f"Pass@1: {test_results.pass_at_1:.2%}")

13. Dependencies

Core Dependencies

langchain==0.3.21
langchain-community>=0.3.0
langchain-core>=0.3.45
pydantic==2.11.7
boto3==1.39.10              # AWS (Bedrock)
anthropic                    # Native Anthropic SDK
openai==1.99.9              # OpenAI (adapted)
google-genai==1.11.0        # Google Gemini
beautifulsoup4==4.12.3      # XML/HTML parsing
pexpect==4.9.0              # Shell control
rich==14.0.0                # Console UI (UX layer)

Summary

FeatureConfucius Approach
Core AbstractionAnalect (typed, composable units)
Design PhilosophyThree-Axis: AX (Agent) / UX (User) / DX (Developer)
Message FormatAnthropic-native with OpenAI adapters
Agent LoopOrchestrator with extension hooks
ToolsExtension-based with tool-use API
MemoryHierarchical with visibility levels (AX)
OutputIOInterface for rich display (UX)
Context ManagementAdaptive compression via Architect
Long-Term MemoryHierarchical notes with hindsight
Performance54.3% on SWE-Bench-Pro (SOTA)

Key Takeaways

  1. AX ≠ UX: What the model sees is different from what the user sees
  2. Anthropic-first: Native tool-use, thinking, caching support
  3. Composable: Analects + Extensions for modular agent design
  4. Efficient: Context management prevents token waste (70k→50k compression)
  5. Persistent: Note-taking enables cross-session learning
  6. Trainable: Integrates with Agent Lightning for RL/APO training

Complete Lifecycle Summary

User Request → Entry → Orchestrator Loop:
    1. Collect memory (SESSION/ENTRY/ANALECT/RUNNABLE visibility)
    2. Compress if needed (LLMPlannerExtension at 70k tokens)
    3. Invoke LLM (Anthropic native: tool_use, thinking, cache_control)
    4. Process response (TEXT → XML parse, TOOL_USE → execute)
    5. Add to memory (AX format)
    6. Display to user (UX format via IOInterface)
    7. Loop if tools executed, else exit
→ Output to User

Training Pipeline Summary

SWE-Bench Tasks → Agent Lightning:
    1. Wrap Confucius in LitAgent
    2. Execute training_rollout() on each task
    3. Evaluate with pytest, return reward (0.0-1.0)
    4. APO optimizes prompts / VERL PPO optimizes weights
    5. Save optimized resources
→ Improved Agent