Context Observability & History

Track optimization events and debug context management

Diagram

Context Observability & History

📋 User Request

⚙️ Context Observability & History

✅ Result

Diagram
Context Observability & HistoryAgentUserContext Observability & HistoryAgentUserRequestProcess requestResultResponse
python
from praisonaiagents import Agent

agent = Agent(
    name="observable-agent",
    instructions="Run with full context observability enabled.",
)
agent.start("Trace all context events for this task.")

Context observability provides optimization history tracking, event logging, and debugging tools.

The user debugs a run; context observability logs compaction and overflow events with token savings.

Diagram

Context Observability

📝 Messages

⚙️ Process

🧠 Log Events

🤖 Agent

✅ History

How It Works

Diagram
HistoryContextManagerAgentUserHistoryContextManagerAgentUserRun taskprocess(messages)Log compaction / overflowEvent trail with token savings

Quick Start

  1. Process messages and read history
    python
    from praisonaiagents import ContextManager
    
    manager = ContextManager(model="gpt-4o-mini")
    result = manager.process(messages=messages)
    
    for event in manager.get_history():
        print(f"{event['event_type']}: {event['tokens_saved']} saved")
  2. Inspect via chat commands
    bash
    praisonai chat
    > /context history
    > /context show

Optimization Events

Event TypeDescription
overflow_detectedContext exceeded threshold
auto_compactAuto-compaction triggered
benefit_checkCompression benefit evaluated
revertCompression reverted (not beneficial)
cap_outputsTool outputs capped
prune_toolsOld tool outputs pruned
sliding_windowSliding window applied
summarizeMessages summarized
snapshotContext snapshot taken

OptimizationEvent

python
@dataclass
class OptimizationEvent:
    timestamp: str              # ISO timestamp
    event_type: str             # Event type
    strategy: str               # Strategy used
    tokens_before: int          # Tokens before
    tokens_after: int           # Tokens after
    tokens_saved: int           # Tokens saved
    messages_affected: int      # Messages changed
    details: Dict[str, Any]     # Additional info

History Tracking

python
# Get all history
history = manager.get_history()

# Filter by event type
compactions = [e for e in history if e['event_type'] == 'auto_compact']

# Get total tokens saved
total_saved = sum(e['tokens_saved'] for e in history)

CLI Commands

bash
# Show optimization history
praisonai chat
> /context history

# Output:
# Time                     Event                Tokens       Saved
# ----------------------------------------------------------------------
# 2024-01-01T12:00:00      overflow_detected       45,000          -
# 2024-01-01T12:00:01      auto_compact           45,000     -15,000
# 2024-01-01T12:00:01      benefit_check          30,000          -

Context Stats

python
stats = manager.get_stats()

print(f"Model: {stats['model']}")
print(f"Utilization: {stats['utilization']*100:.1f}%")
print(f"History events: {stats['history_events']}")
print(f"Warnings: {stats['warnings']}")

CLI Stats Commands

bash
# Show summary
> /context show

# Show token ledger
> /context stats

# Show budget allocation
> /context budget

Monitoring Integration

Events are included in monitor snapshots:

python
config = ManagerConfig(
    monitor_enabled=True,
    monitor_format="json",
)

# JSON snapshots include:
# - optimization_history
# - estimation_metrics
# - warnings

Best Practices

Review history after incidents

Check which optimisations ran when answers suddenly degrade mid-session.

Watch for reverts

A reverted compression means the strategy did not help — try retrieval or summarisation instead.

Track utilisation trends

Rising utilisation across turns signals you need tighter budgets or earlier compaction.

Act on warnings early

Treat overflow warnings as action items, not noise — fix before the API rejects the request.

Related