> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Context Observability & History

> Track optimization events and debug context management

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Context Observability & History"
        Request[📋 User Request] --> Process[⚙️ Context Observability & History]
        Process --> Result[✅ Result]
    end

    classDef input fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff

    class Request input
    class Process process
    class Result output
```

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant Feature as Context Observability & History

    User->>Agent: Request
    Agent->>Feature: Process request
    Feature-->>Agent: Result
    Agent-->>User: Response
```

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Context Observability"
        In[📝 Messages] --> Proc[⚙️ Process]
        Proc --> Log[🧠 Log Events]
        Log --> Agent[🤖 Agent]
        Agent --> Out[✅ History]
    end

    classDef input fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef process fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff

    class In input
    class Proc,Log process
    class Agent agent
    class Out output
```

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant ContextManager
    participant History

    User->>Agent: Run task
    Agent->>ContextManager: process(messages)
    ContextManager->>History: Log compaction / overflow
    History-->>User: Event trail with token savings
```

## Quick Start

<Steps>
  <Step title="Process messages and read history">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    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")
    ```
  </Step>

  <Step title="Inspect via chat commands">
    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    praisonai chat
    > /context history
    > /context show
    ```
  </Step>
</Steps>

## Optimization Events

| Event Type          | Description                           |
| ------------------- | ------------------------------------- |
| `overflow_detected` | Context exceeded threshold            |
| `auto_compact`      | Auto-compaction triggered             |
| `benefit_check`     | Compression benefit evaluated         |
| `revert`            | Compression reverted (not beneficial) |
| `cap_outputs`       | Tool outputs capped                   |
| `prune_tools`       | Old tool outputs pruned               |
| `sliding_window`    | Sliding window applied                |
| `summarize`         | Messages summarized                   |
| `snapshot`          | Context snapshot taken                |

## OptimizationEvent

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
@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
```

<Note>
  Sinks may see a result with `emergency_truncated: True` even when the configured `strategy` raised. This is the failure-fallback path from PraisonAI PR #4242 — the strategy failed, so the manager fell back to emergency truncation to keep the request inside the model window. Treat it as expected, not an error state, and distinguish it from a normal strategy-driven optimization event (where `emergency_truncated` is absent). See [Context Strategies → Failure Fallback](/docs/features/context-strategies#failure-fallback).
</Note>

## History Tracking

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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 theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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 theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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 theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Show summary
> /context show

# Show token ledger
> /context stats

# Show budget allocation
> /context budget
```

## Monitoring Integration

Events are included in monitor snapshots:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
config = ManagerConfig(
    monitor_enabled=True,
    monitor_format="json",
)

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

## Best Practices

<AccordionGroup>
  <Accordion title="Review history after incidents">
    Check which optimisations ran when answers suddenly degrade mid-session.
  </Accordion>

  <Accordion title="Watch for reverts">
    A reverted compression means the strategy did not help — try retrieval or summarisation instead.
  </Accordion>

  <Accordion title="Track utilisation trends">
    Rising utilisation across turns signals you need tighter budgets or earlier compaction.
  </Accordion>

  <Accordion title="Act on warnings early">
    Treat overflow warnings as action items, not noise — fix before the API rejects the request.
  </Accordion>
</AccordionGroup>

## Related

<CardGroup cols={2}>
  <Card title="Context Monitor" icon="eye" href="/docs/features/context-monitor">
    Real-time context snapshots
  </Card>

  <Card title="Context Strategies" icon="sliders" href="/docs/features/context-strategies">
    Optimisation strategies and defaults
  </Card>

  <Card title="Gateway Tracing Hook" icon="route" href="/docs/features/gateway-tracing-hook">
    Emit OpenTelemetry spans across each gateway pipeline stage
  </Card>
</CardGroup>
