Universal AI Brain for AI Agents โ Tiered Memory, Context Scoring, Intent Planning. Zero dependencies.
Project description
๐ง SimpleContext
Universal AI Brain for AI Agents
Tiered Memory ยท Context Scoring ยท Intent Planning ยท Zero Dependencies
SimpleContext is not another vector database wrapper. It's a structured context brain โ tiered memory, intent-aware retrieval, fact extraction, and importance scoring. Without a single external dependency.
Quick Start ยท Architecture ยท Agent System ยท API Reference ยท Ecosystem ยท Contribute
๐ค Why SimpleContext?
Most AI agent frameworks treat memory as a flat list of messages. This breaks down fast:
โ Flat memory: [msg1, msg2, ... msg500] โ retrieval gets noisy
โ
Tiered memory: working ยท episodic ยท semantic โ structured, scored, evolved
SimpleContext gives your agent a structured brain โ not just a chat log.
โจ Features
| Feature | Description | |
|---|---|---|
| ๐ง | 3-Tier Memory | working (active) ยท episodic (sessions) ยท semantic (long-term facts) |
| ๐ฏ | Intent Planning | Auto-detect intent โ smart retrieval strategy per query type |
| ๐ | Context Scoring | relevanceร0.55 + importanceร0.25 + recencyร0.10 + path_priorityร0.10 |
| ๐ | Fact Extraction | Rule-based: "user uses Proxmox", "user project Mangafork" |
| โป๏ธ | Memory Evolution | Jaccard dedup ยท conflict resolution ยท importance decay |
| โก | LRU Cache | 30s TTL cache for repeated queries โ reduces DB load |
| ๐ค | Agent YAML | Define agents in YAML ยท hot-reload without restart |
| ๐ | Agent Chaining | Agent A handoff to Agent B based on user message |
| ๐พ | Multi-Storage | SQLite (default, zero install) ยท Redis ยท PostgreSQL |
| ๐ | Plugin System | Hooks + persistent state + dependency resolver |
| ๐ | Backward Compat | All v3 API still works โ zero breaking changes |
| ๐ฆ | Zero Dependencies | Only Python built-ins: sqlite3, json, re, datetime |
๐๏ธ Architecture
User Message
โ
โผ
AgentRouter โโโโโโโโ agents/*.yaml (hot-reload, TF-IDF routing)
โ
โผ
ContextPlanner
โ intent : coding | personal | task | knowledge | conversation
โ budget : { working:5, episodic:2, semantic:4, skills:3 }
โผ
ContextEngine
โโโ Retriever โ collect candidates
โโโ Resolver โ TTL check, mark expired
โโโ Filter โ active nodes only
โโโ Scorer โ rank by relevance + importance + recency + path
โโโ Selector โ enforce budget + max_nodes + max_chars
โ
โผ
PromptBuilder (deterministic, bullet-format per tier)
โ
โผ
LLM โโ Gemini / OpenAI / Claude / Ollama / any
โ
โผ
MemoryProcessor
โโโ store messages โ working tier
โโโ extract facts โ semantic tier (rule-based, no LLM)
โโโ dedup โ Jaccard similarity โฅ 0.65
โโโ conflict resolve โ confidence-based supersedes
โโโ update importance scores
๐ Quick Start
No install needed. Copy simplecontext/ folder into your project.
from simplecontext import SimpleContext
sc = SimpleContext("config.yaml")
# Simple mode (v3 API โ backward compatible)
result = sc.router.route(user_id, message)
messages = sc.prepare_messages(user_id, message, result)
reply = your_llm(messages)
reply = sc.process_response(user_id, message, reply, result)
# Full mode (v4 API โ one liner)
ctx = sc.chat(user_id, message)
reply = your_llm(ctx.messages)
reply = ctx.save(reply)
Works with any LLM
# Gemini
import litellm
reply = litellm.completion(model="gemini/gemini-2.0-flash",
messages=ctx.messages).choices[0].message.content
# OpenAI
from openai import OpenAI
reply = OpenAI().chat.completions.create(
model="gpt-4o", messages=ctx.messages).choices[0].message.content
# Ollama (local)
import ollama
reply = ollama.chat(model="llama3", messages=ctx.messages)["message"]["content"]
# Anthropic Claude
import anthropic
sys_msg = next(m["content"] for m in ctx.messages if m["role"] == "system")
history = [m for m in ctx.messages if m["role"] != "system"]
reply = anthropic.Anthropic().messages.create(
model="claude-3-5-sonnet-20241022",
system=sys_msg, messages=history, max_tokens=1024).content[0].text
๐ค Agent System
Define agents in YAML. Bot doesn't need to restart when you edit or add agents.
# agents/coding.yaml
name: coding
description: Expert programmer for all languages
triggers:
keywords: [code, bug, error, python, javascript, debug, fix]
priority: 10
personality:
default: |
You are a senior software engineer.
Always use proper code blocks with language tags.
beginner: |
You are a patient programming teacher.
Explain every step with simple examples.
expert: |
Principal engineer. Be concise and technical.
skills:
- name: code_format
content: Always use ```language for all code.
priority: 10
chain:
- condition: deploy OR server OR docker
to: devops
message: Routing to DevOps agent.
Add a new agent = create a new .yaml file in agents/. Done.
๐ API Reference
Memory (v3 API)
mem = sc.memory(user_id)
mem.add_user("hello!")
mem.add_assistant("hi there!")
history = mem.get_for_llm(limit=10) # ready for LLM
# Persistent user facts
mem.remember("name", "Alice")
mem.remember("stack", "Python + FastAPI")
mem.recall("name") # โ "Alice"
# Compress old messages into episodic summary
mem.compress(keep_last=10)
TieredMemory (v4 API)
ctx = sc.context(user_id)
ctx.working.add("debug this error", NodeKind.MESSAGE)
ctx.episodic.add("session summary", NodeKind.SUMMARY)
ctx.semantic.add("user uses Proxmox", NodeKind.FACT, importance=0.8)
ctx.stats() # โ {"working": 5, "episodic": 1, "semantic": 3}
ctx.prune() # remove expired + deleted nodes from DB
Intent โ Retrieval Strategy
| Intent | Working | Episodic | Semantic | Skills |
|---|---|---|---|---|
conversation |
โ | โ | โ | โ |
personal |
โ | โ | โ | โ |
coding |
โ | โ | โ | โ |
knowledge |
โ | โ | โ | โ |
task |
โ | โ | โ | โ |
Debug & Utilities
sc.enable_debug(True) # log retrieval pipeline details
sc.apply_decay(user_id) # apply importance decay (call periodically)
sc.apply_decay() # apply to all users
stats = sc.engine.get_stats(plan)
# โ {"candidates": 37, "active": 28, "selected": 11, "total_chars": 3200}
โ๏ธ Configuration
# config.yaml
storage:
backend: sqlite # sqlite | memory | redis | postgresql
path: ./sc_data.db
memory:
default_limit: 20
ttl_hours:
working: 2 # working nodes expire after 2 hours
episodic: 720 # episodic nodes expire after 30 days
compression:
enabled: false
threshold: 50
keep_last: 10
agents:
folder: ./agents
hot_reload: true
default: general
plugins:
enabled: true
folder: ./plugins
debug:
retrieval: false
๐ Plugin System
from simplecontext.plugins.base import BasePlugin
class MyPlugin(BasePlugin):
name = "my_plugin"
depends_on = [] # declare dependencies
def setup(self):
self.count = self.state.get("count", 0) # persistent state
# Hooks available:
def on_message_saved(self, user_id, role, content, tags, metadata): ...
def on_before_llm(self, user_id, agent_id, messages) -> list: ...
def on_after_llm(self, user_id, agent_id, response) -> str: ...
def on_agent_routed(self, user_id, agent_id, message): ...
def on_prompt_build(self, agent_id, prompt) -> str: ...
def on_export(self, data) -> dict: ...
sc.use(MyPlugin())
# or drop the file in ./plugins/ โ auto-loaded on startup
๐ Project Structure
SimpleContext/
โโโ simplecontext/
โ โโโ core.py โ SimpleContext + ChatContext (entry point)
โ โโโ memory.py โ Memory (v3) + TieredMemory (v4)
โ โโโ skills.py โ Skills: groups, conditions, inheritance
โ โโโ enums.py โ Tier, NodeKind, NodeStatus, Intent
โ โโโ context/
โ โ โโโ node.py โ ContextNode + validator
โ โ โโโ planner.py โ ContextPlanner + RetrievalPlan
โ โ โโโ engine.py โ ContextEngine facade + LRU cache
โ โ โโโ retriever.py โ collect candidates
โ โ โโโ resolver.py โ TTL โ mark expired
โ โ โโโ scorer.py โ scoring formula
โ โ โโโ selector.py โ budget enforcement
โ โ โโโ builder.py โ PromptBuilder
โ โ โโโ processor.py โ MemoryProcessor + decay
โ โ โโโ cache.py โ LRU cache
โ โโโ storage/
โ โ โโโ sqlite.py โ default, zero install
โ โ โโโ redis.py โ pip install redis
โ โ โโโ postgres.py โ pip install psycopg2-binary
โ โโโ agent/
โ โ โโโ schema.py โ parse YAML agent definitions
โ โ โโโ registry.py โ hot-reload agent files
โ โ โโโ router.py โ TF-IDF routing + chaining
โ โโโ plugins/
โ โโโ base.py โ BasePlugin + hooks
โ โโโ loader.py โ dynamic loader + dependency resolver
โ โโโ state.py โ persistent plugin state
โโโ agents/ โ agent YAML definitions
โโโ plugins/ โ drop custom plugins here
โโโ tests/
โ โโโ test_all.py โ 107 unit tests
โ โโโ test_benchmark.py โ 28 accuracy + benchmark tests
โโโ config.yaml.example
๐ Comparison
| SimpleContext | OpenViking | LangChain | AutoGPT | |
|---|---|---|---|---|
| Setup time | < 1 min | 30+ min | ~5 min | ~10 min |
| Dependencies | Zero | Go + VLM | Many | Many |
| Tiered Memory | โ | โ | โ | โ |
| Intent Planning | โ | โ | โ | โ |
| Context Scoring | โ | โ | โ | โ |
| Fact Extraction | โ | โ | โ | โ |
| Conflict Handling | โ | โ | โ | โ |
| Agent YAML + Hot-reload | โ | โ | โ | โ |
| Agent Chaining | โ | โ | โ ๏ธ | โ ๏ธ |
| Plugin System | โ | โ | โ ๏ธ | โ |
| Multi-Storage | โ | VectorDB | VectorDB | VectorDB |
| Semantic Search | โ via plugin | โ vector | โ vector | โ vector |
๐ Ecosystem
SimpleContext adalah core engine dari ekosistem yang terus berkembang. Gunakan bersama repositori lain untuk setup yang lebih lengkap:
| Repositori | Deskripsi |
|---|---|
| SimpleContext | Core engine โ Universal AI Brain (repo ini) |
| SimpleContext-Plugin | Official & community plugin registry โ tambah kemampuan via drop-in plugins |
| SimpleContext-Bot | AI Telegram Bot powered by SimpleContext โ one-command setup, auto-downloads engine + agents |
| SimpleContext-Agents | Ready-to-use agent definitions โ koleksi YAML agent siap pakai |
Contoh setup ekosistem penuh
SimpleContext โ otak / engine
โ
โโโ SimpleContext-Agents โ definisi agent (YAML)
โโโ SimpleContext-Plugin โ plugin tambahan (vector search, dll)
โโโ SimpleContext-Bot โ interface ke user (Telegram)
๐ค Call for Contributors
SimpleContext butuh plugin buatanmu.
Plugin system sudah siap โ kamu tinggal buat satu file Python dan submit ke SimpleContext-Plugin. Tidak perlu fork core, tidak perlu setup rumit.
Plugin apa yang dibutuhkan?
Beberapa ide yang belum ada dan sangat berguna:
| Ide Plugin | Deskripsi |
|---|---|
plugin-auto-tagger |
Tag otomatis setiap pesan berdasarkan keyword rules |
plugin-summarizer |
Auto-compress working memory ke episodic via LLM |
plugin-sentiment |
Deteksi sentimen user, simpan ke metadata |
plugin-rate-limiter |
Batasi frekuensi request per user |
plugin-webhook |
Kirim event ke endpoint eksternal via HTTP |
plugin-translate |
Auto-translate pesan ke bahasa tertentu |
plugin-analytics |
Dashboard statistik penggunaan per user/agent |
Seberapa susah membuat plugin?
# Ini sudah cukup untuk jadi plugin yang valid:
from simplecontext.plugins.base import BasePlugin
class MyPlugin(BasePlugin):
name = "my_plugin"
version = "1.0.0"
def on_before_llm(self, user_id, agent_id, messages):
# lakukan sesuatu sebelum LLM dipanggil
return messages
Satu file. Drop ke plugins/. Selesai.
Cara kontribusi
1. Buka https://github.com/zacxyonly/SimpleContext-Plugin
2. Fork โ buat plugin di community/plugin-namakalian/
3. Ikuti panduan di CONTRIBUTING.md
4. Submit Pull Request
๐ก Punya ide plugin tapi tidak yakin cara implementasinya? Buka issue di SimpleContext-Plugin โ diskusikan dulu, baru build.
๐งช Tests
python -m unittest discover tests -v
# Ran 135 tests in 1.2s โ OK
๐ License
MIT โ free to use, modify, and distribute.
Built with โค๏ธ โ zero dependencies, maximum brain.
โญ Star this repo if you find it useful!
SimpleContext-Plugin ยท SimpleContext-Bot ยท SimpleContext-Agents
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file simplecontext_ai-4.3.0.tar.gz.
File metadata
- Download URL: simplecontext_ai-4.3.0.tar.gz
- Upload date:
- Size: 88.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9d13b1777d13b223ef5e096308a35fd9bc3aa95148c27d2bacd2816e8b579054
|
|
| MD5 |
be4b72f1afdb114e41e2f9a9a184ec06
|
|
| BLAKE2b-256 |
a5d69d46f2b3d9cd5c9ace2a2683700a29c5e55bb46c46d5dc76f7867f3a059b
|
File details
Details for the file simplecontext_ai-4.3.0-py3-none-any.whl.
File metadata
- Download URL: simplecontext_ai-4.3.0-py3-none-any.whl
- Upload date:
- Size: 85.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0bcd19dbe20fc47021dc0d04515db523dc63b16fb2642b1647818bba547ef15d
|
|
| MD5 |
585ffcd5feaa7578ac6463d34ba85ec8
|
|
| BLAKE2b-256 |
9c015e68e01189c7db6248d7bab018ccb7193c18f75597c00fad1e94a5ae224e
|