Metadata-Version: 2.4
Name: riverse
Version: 0.1.1
Summary: River Algorithm memory consolidation for AI applications
Author: JK
License: AGPL-3.0
Project-URL: Homepage, https://github.com/JKRiver/JKRiver
Project-URL: Repository, https://github.com/JKRiver/riverse
Keywords: memory,ai,llm,consolidation,profile
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: openai>=1.0
Dynamic: license-file

# Riverse

**River Algorithm** — AI 应用的记忆巩固引擎。

一个让你的 AI 拥有持久、进化记忆的 Python 包——类似 [mem0](https://github.com/mem0ai/mem0)，但具有 River Algorithm 独特的三层置信度模型、矛盾检测与离线巩固能力。

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 `suspected` → `confirmed` through cross-verification / 事实经过交叉验证从 `suspected` 晋升为 `confirmed`
- **Contradiction detection / 矛盾检测**: Automatically detects and resolves conflicting information / 自动检测并解决冲突信息
- **Sleep consolidation / 睡眠巩固**: Offline pipeline that processes conversations into structured memory / 离线管线将对话处理为结构化记忆
- **User profiling / 用户画像**: Builds rich profiles with categories, evidence chains, and decay / 构建包含分类、证据链和衰减的丰富画像
- **Trajectory tracking / 轨迹追踪**: Understands life phases, key anchors, and volatile areas / 理解人生阶段、关键锚点和不稳定领域
- **Multilingual / 多语言**: Built-in prompts for English, 中文, and 日本語 — set `language` parameter / 内置英中日三语提示词，通过 `language` 参数切换
- **Zero config storage / 零配置存储**: SQLite backend, no external database needed / SQLite 后端，无需外部数据库
- **OpenAI-compatible / OpenAI 兼容**: Works with OpenAI, DeepSeek, Ollama, Groq, and any compatible API

## Installation / 安装

```bash
pip install riverse
```

## Quick Start / 快速开始

### English

```python
from riverse import Riverse

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

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")

r.sleep(user_id="alex")

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

### 中文

```python
from riverse import Riverse

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

r.add(messages=[
    {"role": "user", "content": "我刚搬到东京，在 Google 找了份新工作。"},
    {"role": "assistant", "content": "太棒了！适应得怎么样？"},
], user_id="alex")

r.sleep(user_id="alex")

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

### 日本語

```python
from riverse import Riverse

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

r.add(messages=[
    {"role": "user", "content": "東京に引っ越して、Googleで新しい仕事を始めました。"},
    {"role": "assistant", "content": "すごいですね！慣れましたか？"},
], user_id="alex")

r.sleep(user_id="alex")
```

## Language / 语言设置

The `language` parameter controls the language of all internal prompts sent to the LLM during memory consolidation. Supported values:

`language` 参数控制记忆巩固过程中发送给 LLM 的所有内部提示词的语言。支持的值：

| Value | Language | 说明 |
|-------|----------|------|
| `"en"` | English | Default / 默认 |
| `"zh"` | 中文 | Chinese prompts / 中文提示词 |
| `"ja"` | 日本語 | Japanese prompts / 日本語プロンプト |

This affects how the LLM extracts observations, classifies facts, detects contradictions, and generates user profiles. Choose the language that matches your users' conversations for best results.

这会影响 LLM 如何提取观察、分类事实、检测矛盾和生成用户画像。选择与用户对话匹配的语言以获得最佳效果。

## Configuration / 配置

```python
r = Riverse(
    api_key="sk-...",
    api_base="https://api.openai.com",   # Or Ollama/DeepSeek/Groq URL
    model="gpt-4o-mini",
    language="zh",                        # "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 / 使用 DeepSeek

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

## API Reference / API 参考

### `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: / 运行完整的 River Algorithm 巩固管线：

1. Extracts observations, events, and relationships / 提取观察、事件和关系
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):

River Algorithm 模拟人类记忆巩固过程（类似睡眠）：

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 / 将观察与现有画像匹配
   - **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 / 被更新信息取代或过期

## Full Version / 完整版

`riverse` is the standalone Python SDK extracted from [JKRiver](https://github.com/JKRiver/JKRiver) — a full-featured AI assistant with River Algorithm memory built in.

`riverse` 是从 [JKRiver](https://github.com/JKRiver/JKRiver) 项目中提取的独立 Python SDK。JKRiver 是一个内置 River Algorithm 记忆系统的完整 AI 助手。

If you want:
- A ready-to-use AI assistant with persistent memory → use [JKRiver](https://github.com/JKRiver/JKRiver)
- To integrate River Algorithm memory into your own app → use `riverse`

如果你想要：
- 一个开箱即用的、具备持久记忆的 AI 助手 → 使用 [JKRiver](https://github.com/JKRiver/JKRiver)
- 将 River Algorithm 记忆能力集成到你自己的应用中 → 使用 `riverse`

## License / 许可证

AGPL-3.0
