Metadata-Version: 2.4
Name: kristal
Version: 0.1.7
Summary: A multi-faceted memory framework for AI: pluggable memory facets on a shared multi-source substrate, unified consumption, auditable across apps.
Author: 2049lab
License-Expression: MIT
Project-URL: Homepage, https://github.com/2049lab/kristal
Project-URL: Repository, https://github.com/2049lab/kristal
Keywords: memory,ai,agent,llm,personal-ai,context,knowledge
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: <3.13,>=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.9
Requires-Dist: pydantic-settings>=2.6
Requires-Dist: loguru>=0.7
Requires-Dist: python-dotenv<2,>=1.0
Requires-Dist: httpx<1,>=0.27
Provides-Extra: server
Requires-Dist: fastapi==0.121.3; extra == "server"
Requires-Dist: uvicorn[standard]>=0.30; extra == "server"
Provides-Extra: mysql
Requires-Dist: SQLAlchemy<3,>=2.0; extra == "mysql"
Requires-Dist: PyMySQL<2,>=1.1; extra == "mysql"
Provides-Extra: redis
Requires-Dist: redis<7,>=6.0; extra == "redis"
Provides-Extra: s3
Requires-Dist: boto3==1.44.0; extra == "s3"
Requires-Dist: botocore==1.44.0; extra == "s3"
Provides-Extra: milvus
Requires-Dist: pymilvus<2.7,>=2.6.17; extra == "milvus"
Provides-Extra: langfuse
Requires-Dist: langfuse==3.15.0; extra == "langfuse"
Requires-Dist: openai==3.3.0; extra == "langfuse"
Requires-Dist: httpx2==2.12.0; extra == "langfuse"
Requires-Dist: httpcore2==2.12.0; extra == "langfuse"
Provides-Extra: zh
Requires-Dist: pypinyin<1,>=0.51; extra == "zh"
Requires-Dist: lunar_python<2,>=1.4.9; extra == "zh"
Provides-Extra: mem0
Requires-Dist: mem0ai==2.2.1; extra == "mem0"
Provides-Extra: all
Requires-Dist: kristal[langfuse,mem0,milvus,mysql,redis,s3,server,zh]; extra == "all"
Provides-Extra: dev
Requires-Dist: kristal[all]; extra == "dev"
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pyflakes<4,>=3.2; extra == "dev"
Requires-Dist: fakeredis<2.41,>=2.26; extra == "dev"
Requires-Dist: pytest-cov==7.1.0; extra == "dev"
Requires-Dist: coverage==7.17.3; extra == "dev"
Dynamic: license-file

# Kristal

**Kristal — a multi-faceted memory framework for AI: define any memory facet on a shared multi-source data substrate, consume them through one unified context layer, and audit every write and read across apps.**

> Status: pre-alpha. APIs will change. Prompts are currently tuned for Chinese, so generated memories are written in
> Chinese; an English prompt pack is planned.

## Why Kristal

Memory is not one thing. A person's timeline, relationships, preferences and habits each need their own shape, lifecycle and retrieval rules. Kristal treats memory as a crystal: every memory type is a **facet**, and all facets grow from the same substrate.

- **Multi-source substrate** — raw inputs (chats, transcripts, media, app events) land as immutable items and are normalized into an observation layer that every facet reads from.
- **Pluggable facets** — add a new memory type by implementing one model and registering it; ingestion, orchestration and consumption stay untouched.
- **Unified consumption** — all facets converge into a single context layer that apps and agents query, with consistent permissions.
- **People & profiles** — a shared person directory (social graph) and user profile, fed by the facets that know about them.
- **Auditable by design** — every memory traces back to its evidence, and every read is ticketed and logged.
- **Cross-app by default** — one user, many apps, one memory, governed by explicit authorization.

## Architecture

```
Items (raw input) ─► Observations / Segments ─► Facets (memory types) ─► Context (consumption)
   multi-source         shared substrate          pluggable                 unified, auditable
                                                      └─► Persons & Profiles
```

## Install

```bash
pip install kristal                 # library, standalone (SQLite + local files), no other services needed
pip install "kristal[server]"       # + HTTP service (kristal serve)
pip install "kristal[mem0]"         # + mem0 as a memory type (docs/internals/external-memory.md)
pip install "kristal[all]"          # + MySQL, Redis, S3, Milvus, Langfuse, Chinese name/calendar support, mem0
```

Python 3.11 or 3.12.

## Quickstart: as a library

Set `OPENAI_API_KEY` (or point `OPENAI_BASE_URL` at any OpenAI-compatible endpoint), then:

```python
from kristal import Kristal

with Kristal() as k:                                   # data lives in ~/.kristal (SQLite + local files)
    k.add([
        {"role": "user", "content": "We fixed the release plan for Friday afternoon today.",
         "at": "2026-11-20T09:00:00+08:00"},
        {"role": "assistant", "content": "Are the two open bugs fixed by then?"},
        {"role": "user", "content": "Yes, by Thursday. I'll write the release notes."},
    ], user_id="alice")
    k.flush()                                          # wait until the day's narrative is readable

    print(k.memories("alice")["memories"][0]["content"])      # the day's narrative
    ctx = k.context("alice", "What did Alice decide about the release?")
    print(k.trace("alice", ctx["sections"][0]["memories"][0]["memory_id"])["items"])  # memory → evidence
```

`flush()` returns once what you wrote can be read (the day narratives); event stories, month and year rollups and
profiles keep running in the background, and `flush(full=True)` waits for them too. Methods return plain data and raise `KristalError` with the same error codes as the HTTP API. Use
`k.app("glasses")` to write and read as another app: several apps feed the same user, and each app's data stays
under its own visibility and authorization rules.

To use other providers, write a `kristal.toml` (see [examples/config/](examples/config/) for OpenAI, DeepSeek,
Gemini, Qwen and Ollama) and pass it: `Kristal("kristal.toml")`.

## Quickstart: as a service

```bash
pip install "kristal[server]"
export OPENAI_API_KEY=...
export KRISTAL_ADMIN_TOKEN=$(openssl rand -hex 16)   # enables the admin API
kristal serve --port 8000
```

Register an app (the response contains its AK/SK; the SK is shown only once):

```bash
curl -s -X POST localhost:8000/admin/v1/apps -H "X-Admin-Token: $KRISTAL_ADMIN_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"app_id": "notes", "name": "Notes", "owner": "me", "account_domain": "home", "trust": "first_party"}'
```

Every request is signed with the app's AK/SK. `KristalClient` does this for you and has the same methods as the
library:

```python
from kristal import KristalClient

c = KristalClient("http://localhost:8000", ak="...", sk="...")
c.add([{"role": "user", "content": "..."}], user_id="alice")
print(c.context("alice", "What did Alice decide?"))
```

Interactive API docs are at `http://localhost:8000/docs`, and the built-in read-only **Memory Workbench** for browsing memories, social graphs, profiles and segments across apps and users is at `http://localhost:8000/workbench`. For local development only, `KRISTAL_AUTH_MODE=relaxed`
skips signature checks.

## Inputs and memory types

**Inputs.** Recordings with transcripts (`media/recording.*`), transcripts (`conversation/transcript.*`), instant
messaging chats (`conversation/chat.*`) and assistant sessions (`conversation/agent.session`) are cleaned, segmented and
understood; each kind has its own segmentation rules. Images and files inside messages travel with the segment as
attachments. Other kinds are stored and traceable but not yet turned into memories. In the library, pick the kind with
`k.add(messages, user_id=..., subtype="chat.im")`.

**Memory types.** A memory type turns segments into memories. Kristal ships `life_timeline` (narratives of the user's
days, months and years) and `social_graph` (user-centered interpersonal relationship graph and character memories), and
can plug in open-source memory frameworks as memory types; storage and retrieval are theirs,
while authorization, tracing, audit and erasure stay Kristal's
([docs/internals/external-memory.md](docs/internals/external-memory.md)). The first adapter is mem0:

```toml
# kristal.toml; install with: pip install "kristal[mem0]"
[memory_types.mem0]
enabled = true                       # external frameworks are off by default
sources = ["conversation/chat.*", "conversation/agent.session"]

[memory_types.life_timeline]
sources = ["conversation/transcript.*", "media/recording.*", "conversation/chat.*"]
```

Which memory types receive a segment is the intersection of the deployment (`[memory_types.<name>]`: `enabled`,
`sources`) and the writing app, which can limit it in its App Profile with `memory_types`.

## Deployment

Kristal uses whatever infrastructure you configure and falls back to defaults for the rest:

| Component | Configured | Default |
|---|---|---|
| database | MySQL | SQLite file in `KRISTAL_DATA_DIR` |
| file storage | S3-compatible store | local directory |
| vectors | Milvus | a table in the database |
| locks, dedup, tokens | Redis | in-process / database |
| task queue | Redis Streams | in-process queue + sweeper |

- **Standalone** (no Redis): one process. A lease in the database makes a second process refuse to start. After a
  restart, unfinished work is recovered from the database.
- **Cluster** (Redis configured): any number of replicas; requires MySQL and S3. `kristal worker` runs background
  processing without serving HTTP.

## Configuration

Settings resolve in this order: constructor arguments → `KRISTAL_*` environment variables (and `.env`) →
`kristal.toml` (current directory or `KRISTAL_CONFIG`) → defaults. See [kristal.toml.template](kristal.toml.template)
and [.env.template](.env.template) for all settings and stage-level model routing (`[models.*]`, `[stages]`,
`[embedding]`, `[rerank]`).

## License

[MIT](LICENSE)
