# Riverse

**River Algorithm** memory consolidation for AI applications.

A Python package that gives your AI persistent, evolving memory — similar to [mem0](https://github.com/mem0ai/mem0), but with the River Algorithm's unique three-layer confidence model, contradiction detection, and offline consolidation.

## Features

- **Three-layer confidence model**: Facts progress from `suspected` → `confirmed` through cross-verification
- **Contradiction detection**: Automatically detects and resolves conflicting information
- **Sleep consolidation**: Offline pipeline that processes conversations into structured memory
- **User profiling**: Builds rich user profiles with categories, evidence chains, and decay
- **Trajectory tracking**: Understands life phases, key anchors, and volatile areas
- **Multilingual**: Built-in prompts for English, Chinese, and Japanese
- **Zero config storage**: SQLite backend, no external database needed
- **OpenAI-compatible**: Works with OpenAI, DeepSeek, Ollama, Groq, and any compatible API

## Installation

```bash
pip install riverse
```

## Quick Start

```python
from riverse import Riverse

# Initialize
r = Riverse(api_key="sk-...", model="gpt-4o-mini")

# Add conversation memory
r.add(messages=[
    {"role": "user", "content": "I just moved to Tokyo for a new job at Google."},
    {"role": "assistant", "content": "That's exciting! How's the transition going?"},
], user_id="alex")

# Run Sleep consolidation (River Algorithm core)
result = r.sleep(user_id="alex")

# Get user profile
profile = r.get_profile(user_id="alex")
for fact in profile:
    print(f"[{fact['category']}] {fact['subject']}: {fact['value']} ({fact['layer']})")

# Search memory
results = r.search("Where does he live?", user_id="alex")

# Get user model (personality + trajectory)
model = r.get_user_model(user_id="alex")
```

## Configuration

```python
r = Riverse(
    api_key="sk-...",
    api_base="https://api.openai.com",   # Or Ollama/DeepSeek/Groq URL
    model="gpt-4o-mini",
    language="en",                        # en / zh / ja
    db_path="~/.riverse/memory.db",       # SQLite path
    temperature=0.7,
    max_tokens=4096,
)
```

### Using with Ollama

```python
r = Riverse(
    api_base="http://localhost:11434",
    model="llama3.1",
    language="en",
)
```

### Using with DeepSeek

```python
r = Riverse(
    api_key="sk-...",
    api_base="https://api.deepseek.com",
    model="deepseek-chat",
)
```

## API Reference

### `r.add(messages, user_id, session_id=None)`

Store conversation messages for later consolidation.

- `messages`: List of `{"role": "user"|"assistant", "content": "..."}`
- `user_id`: User identifier
- `session_id`: Optional session grouping (auto-generated if omitted)

### `r.sleep(user_id)`

Run the full River Algorithm consolidation pipeline. This:
1. Extracts observations, events, and relationships from unprocessed conversations
2. Classifies observations against existing profile
3. Creates new facts and detects contradictions
4. Cross-verifies suspected facts for promotion
5. Resolves disputed fact pairs
6. Updates maturity decay and user model
7. Generates trajectory summary

Returns a summary dict with counts of actions taken.

### `r.get_profile(user_id)`

Returns all active profile facts as a list of dicts.

### `r.get_user_model(user_id)`

Returns `{"dimensions": [...], "trajectory": {...}}` with personality analysis and life trajectory.

### `r.search(query, user_id, top_k=10)`

Keyword search across profile facts, events, and observations.

## How It Works

The River Algorithm models human memory consolidation (like sleep):

1. **Awake phase** (`add()`): Raw conversations are stored
2. **Sleep phase** (`sleep()`): A multi-step pipeline processes memories:
   - **Extract**: Pull observations, events, relationships from dialogue
   - **Classify**: Match observations to existing profile (support/contradict/new)
   - **Consolidate**: Create facts, resolve contradictions, promote verified facts
   - **Synthesize**: Update user model and trajectory summary

Facts have a **three-layer confidence model**:
- `suspected`: Initial extraction, unverified
- `confirmed`: Cross-verified through multiple mentions or corroboration
- `closed`: Superseded by newer information or expired

## License

AGPL-3.0
