# Stateful Conversations & History

> Deep dive into Conversation state, step history accumulation, and the low-level send/receive_steps API for granular interaction control.

- Repository: google-antigravity/antigravity-sdk-python
- GitHub: https://github.com/google-antigravity/antigravity-sdk-python
- Human wiki: https://grok-wiki.com/public/wiki/google-antigravity-antigravity-sdk-python-2abd361a7867
- Complete Markdown: https://grok-wiki.com/public/wiki/google-antigravity-antigravity-sdk-python-2abd361a7867/llms-full.txt

## Source Files

- `google/antigravity/conversation/conversation.py`
- `google/antigravity/conversation/README.md`
- `examples/deep_dives/async_chat.py`
- `google/antigravity/types.py`

---

<details>
<summary>Relevant source files</summary>
The following files were used as context for generating this wiki page:
- [google/antigravity/conversation/conversation.py](google/antigravity/conversation/conversation.py)
- [google/antigravity/conversation/README.md](google/antigravity/conversation/README.md)
- [google/antigravity/conversation/conversation_test.py](google/antigravity/conversation/conversation_test.py)
- [google/antigravity/types.py](google/antigravity/types.py)
- [examples/deep_dives/host_tool_hooks.py](examples/deep_dives/host_tool_hooks.py)
</details>

# Stateful Conversations & History

The `Conversation` class serves as the **Layer 2 Session API** within the Google Antigravity SDK, bridging the gap between high-level Agent logic and low-level transport protocols. While the `Agent` (Layer 1) manages configuration, tools, and hooks, the `Conversation` owns the live session state, including the accumulation of step history, turn tracking, and context window compaction indices.

By wrapping a `Connection` (Layer 3), a `Conversation` provides a stateful container that ensures continuity across multiple model interactions. It maintains a chronologically ordered transcript of `Step` objects, allowing developers to inspect the agent's trajectory, monitor token usage in real-time, and implement advanced memory management strategies like history trimming.

Sources: [google/antigravity/conversation/conversation.py:15-24](), [google/antigravity/conversation/README.md:11-35]()

## Session State & History Accumulation

At its core, a `Conversation` is a collector of `Step` objects received from the underlying connection. Each step represents a discrete event in the agent's reasoning or execution path, such as generating text, calling a tool, or finishing a turn.

### The History Transcript
The full transcript is exposed via the `history` property, which returns a copy of the internal step list. This list is uncompacted by default, preserving every model thought and environment interaction for debugging or logging purposes.

```python
# google/antigravity/conversation/conversation.py:231-238
@property
def history(self) -> list[types.Step]:
  """Returns all steps received across all turns."""
  return list(self._steps)
```

### Memory Management
To prevent unbounded memory growth in long-running sessions, the `Conversation` supports a `max_history_size` parameter. When the step count exceeds this limit, the oldest steps are discarded, and internal turn/compaction indices are automatically adjusted to reflect the new window.

| Property | Description | Source |
| :--- | :--- | :--- |
| `max_history_size` | Maximum steps to retain (default: 10,000). | `conversation.py:34` |
| `turn_count` | Number of user turns (send calls) in the session. | `conversation.py:249` |
| `clear_history()` | Resets the history list and all tracking indices. | `conversation.py:264` |

Sources: [google/antigravity/conversation/conversation.py:59-86](), [google/antigravity/conversation/conversation_test.py:718-777]()

## Turn & Compaction Tracking

Unlike a raw connection, a `Conversation` understands the concept of a "turn" and a "compacted context." It maintains specific indices to help the SDK and developers navigate the history.

*   **Turn Start Indices**: Every time `send()` is called, the current history length is recorded. This allows the SDK to group steps by user interaction.
*   **Compaction Indices**: When the backend model compacts its context window (often triggered by token limits), a `StepType.COMPACTION` step is yielded. The `Conversation` records the index of these steps, indicating that steps preceding the index may no longer be in the model's active memory.

```mermaid
stateDiagram-v2
    direction LR
    state "Turn 1" as T1
    state "Turn 2" as T2
    state "History List" as HL {
        s0: User Prompt
        s1: Model Thought
        s2: Model Response
        s3: Compaction Step
        s4: User Prompt 2
    }
    T1 --> s0
    T2 --> s4
    note right of s3: Recorded in compaction_indices
```

Sources: [google/antigravity/conversation/conversation.py:135-157](), [google/antigravity/conversation/conversation.py:254-263]()

## Low-Level Interaction: send() and receive_steps()

While `chat()` is the preferred method for most users, power users can utilize the granular `send()` and `receive_steps()` API for precise control over the interaction loop. This is particularly useful for building custom UIs or implementing complex agent-to-agent communication.

### Granular Step Iteration
The `receive_steps()` method is an async iterator that yields `Step` objects as they arrive. It blocks until the connection signals it is idle, marking the end of the turn.

```python
# Low-level interaction pattern
await conversation.send("Perform a complex task.")
async for step in conversation.receive_steps():
    if step.type == types.StepType.TOOL_CALL:
        print(f"Agent is calling: {step.tool_calls[0].name}")
    elif step.is_complete_response:
        print(f"Final: {step.content}")
```

### Automatic Draining
A key safety feature of the `send()` method is **automatic draining**. If a developer calls `send()` while a previous turn is still yielding steps, the `Conversation` will automatically drain and record the remaining steps of the active turn into history before initiating the new message.

Sources: [google/antigravity/conversation/conversation.py:109-158](), [examples/deep_dives/host_tool_hooks.py:193-210]()

## Token Usage Monitoring

The `Conversation` aggregates `UsageMetadata` from every step that reports token counts. This provides a unified view of the session's resource consumption.

*   **`total_usage`**: Cumulative token counts (prompt, candidates, thoughts) across the entire session.
*   **`last_turn_usage`**: Token counts specific to the most recent completed turn.

The usage metadata includes `prompt_token_count`, `candidates_token_count`, and `thoughts_token_count` (for reasoning models), allowing for detailed cost and performance analysis.

Sources: [google/antigravity/conversation/conversation.py:315-335](), [google/antigravity/types.py:472-500]()

## Summary

The `Conversation` class provides the stateful backbone for the Antigravity SDK, transforming a stateless transport into a coherent session. By managing step accumulation, turn boundaries, and memory limits, it enables sophisticated agentic workflows while shielding developers from the complexities of wire-protocol management.

Sources: [google/antigravity/conversation/conversation.py:15-24]()
