> ## 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 Snapshot Hooks

> Capture exact LLM call boundary state for debugging and verification

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Context Snapshot Hooks"
        Request[📋 User Request] --> Process[⚙️ Context Snapshot Hooks]
        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
```

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(name="snapshot-agent", instructions="Save and restore context snapshots.")
agent.start("Create a context snapshot before processing this long document.")
```

Snapshot hooks capture the exact state of messages and tools at the LLM call boundary, enabling verification that snapshots match actual payloads.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Context Snapshot Hooks"
        In[📝 LLM Call] --> Capture[📸 Capture Boundary]
        Capture --> Agent[🤖 Agent]
        Agent --> Out[✅ Verified Snapshot]
    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 Capture process
    class Agent agent
    class Out output
```

## Quick Start

<Steps>
  <Step title="Capture at the LLM boundary">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import ContextManager

    manager = ContextManager(model="gpt-4o-mini")
    hook_data = manager.capture_llm_boundary(messages, tools)
    print(f"Message hash: {hook_data.message_hash}")
    ```
  </Step>

  <Step title="Register a snapshot callback">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    def on_llm_call(hook_data):
        print(f"Sending {len(hook_data.messages)} messages")

    manager.register_snapshot_callback(on_llm_call)
    ```
  </Step>
</Steps>

## Architecture

The user registers snapshot hooks; each context change triggers a callback for auditing or custom pipelines.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant A as Agent
    participant C as ContextManager
    participant L as LLM
    
    A->>C: process(messages)
    C->>C: Optimize if needed
    A->>C: capture_llm_boundary(messages, tools)
    C->>C: Compute hashes
    C->>C: Store snapshot
    C-->>A: SnapshotHookData
    A->>L: Send to LLM
    Note over A,L: Hashes can verify<br/>snapshot == payload
```

classDef agent fill:#8B0000,color:#fff
classDef tool fill:#189AB4,color:#fff

## SnapshotHookData

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
@dataclass
class SnapshotHookData:
    timestamp: str           # ISO timestamp
    messages: List[Dict]     # Exact messages
    tools: List[Dict]        # Exact tool schemas
    message_hash: str        # SHA256 hash (16 chars)
    tools_hash: str          # SHA256 hash (16 chars)
    ledger: ContextLedger    # Token accounting
    budget: BudgetAllocation # Budget info
```

## Snapshot Callbacks

Register callbacks to be notified at every LLM boundary:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
def on_llm_call(hook_data):
    """Called before each LLM request."""
    print(f"Sending {len(hook_data.messages)} messages")
    print(f"Hash: {hook_data.message_hash}")
    
    # Log for debugging
    with open("llm_calls.log", "a") as f:
        f.write(f"{hook_data.timestamp}: {hook_data.message_hash}\n")

manager.register_snapshot_callback(on_llm_call)
```

## Hash Verification

Verify snapshot matches actual payload:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import hashlib
import json

# Capture snapshot
hook_data = manager.capture_llm_boundary(messages, tools)

# Later, verify payload matches
def verify_payload(actual_messages, expected_hash):
    actual_json = json.dumps(actual_messages, sort_keys=True, default=str)
    actual_hash = hashlib.sha256(actual_json.encode()).hexdigest()[:16]
    return actual_hash == expected_hash

# Before sending to LLM
assert verify_payload(messages, hook_data.message_hash)
```

## Snapshot Timing

Configure when snapshots are taken:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import ManagerConfig

config = ManagerConfig(
    snapshot_timing="both",  # pre_optimization, post_optimization, or both
)
```

| Timing              | Description                  |
| ------------------- | ---------------------------- |
| `pre_optimization`  | Before any optimization      |
| `post_optimization` | After optimization (default) |
| `both`              | Capture both states          |

## Drift Detection

Detect if context drifted between snapshot and LLM call:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Take snapshot
hook1 = manager.capture_llm_boundary(messages, tools)

# ... some operations ...

# Take another snapshot
hook2 = manager.capture_llm_boundary(messages, tools)

# Check for drift
if hook1.message_hash != hook2.message_hash:
    print("Warning: Context changed between snapshots")
```

## Integration with Monitor

Snapshots are automatically included in monitor output:

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

# Snapshots include hash metadata
# {
#   "timestamp": "...",
#   "message_hash": "abc123...",
#   "tools_hash": "def456...",
#   ...
# }
```

## CLI Usage

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Enable monitoring to capture snapshots
praisonai chat --context-monitor

# Snapshots written to context.txt
# Include message/tool hashes for verification
```

## Use Cases

1. **Debugging** - Verify exact state sent to LLM
2. **Auditing** - Log all LLM calls with hashes
3. **Testing** - Assert snapshot == expected payload
4. **Replay** - Reproduce exact LLM calls

## Best Practices

<AccordionGroup>
  <Accordion title="Hash payloads for regression tests">
    Compare snapshot hashes in CI to detect unintended context changes between releases.
  </Accordion>

  <Accordion title="Use hooks for audit trails">
    Log hashes and token counts when compliance requires proof of what was sent to the model.
  </Accordion>

  <Accordion title="Keep hooks lightweight">
    Avoid heavy I/O inside snapshot hooks — queue writes asynchronously when possible.
  </Accordion>

  <Accordion title="Include tool results in snapshots">
    Verify tool output formatting matches what the model receives, not just user messages.
  </Accordion>
</AccordionGroup>

## Related

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

  <Card title="Context Observability" icon="chart-line" href="/docs/features/context-observability">
    Optimisation event history
  </Card>
</CardGroup>
