Skip to content

Repository files navigation

🧠 SimpleContext

Universal AI Brain for AI Agents
Tiered Memory · Context Scoring · Intent Planning · Zero Dependencies

PythonTestsLicenseDependenciesVersion


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

FeatureDescription
🧠3-Tier Memoryworking (active) · episodic (sessions) · semantic (long-term facts)
🎯Intent PlanningAuto-detect intent → smart retrieval strategy per query type
📊Context Scoringrelevance×0.55 + importance×0.25 + recency×0.10 + path_priority×0.10
🔍Fact ExtractionRule-based: "user uses Proxmox", "user project Mangafork"
♻️Memory EvolutionJaccard dedup · conflict resolution · importance decay
LRU Cache30s TTL cache for repeated queries — reduces DB load
🤖Agent YAMLDefine agents in YAML · hot-reload without restart
🔗Agent ChainingAgent A handoff to Agent B based on user message
💾Multi-StorageSQLite (default, zero install) · Redis · PostgreSQL
🔌Plugin SystemHooks + persistent state + dependency resolver
🔄Backward CompatAll v3 API still works — zero breaking changes
📦Zero DependenciesOnly 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.

fromsimplecontextimportSimpleContextsc=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

# Geminiimportlitellmreply=litellm.completion(model="gemini/gemini-2.0-flash",
messages=ctx.messages).choices[0].message.content# OpenAIfromopenaiimportOpenAIreply=OpenAI().chat.completions.create(
model="gpt-4o", messages=ctx.messages).choices[0].message.content# Ollama (local)importollamareply=ollama.chat(model="llama3", messages=ctx.messages)["message"]["content"]
# Anthropic Claudeimportanthropicsys_msg=next(m["content"] forminctx.messagesifm["role"] =="system")
history= [mforminctx.messagesifm["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.yamlname: codingdescription: Expert programmer for all languagestriggers:
keywords: [code, bug, error, python, javascript, debug, fix]priority: 10personality:
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_formatcontent: Always use ```language for all code.priority: 10chain:
- condition: deploy OR server OR dockerto: devopsmessage: 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 factsmem.remember("name", "Alice")
mem.remember("stack", "Python + FastAPI")
mem.recall("name") # → "Alice"# Compress old messages into episodic summarymem.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

IntentWorkingEpisodicSemanticSkills
conversation
personal
coding
knowledge
task

Debug & Utilities

sc.enable_debug(True) # log retrieval pipeline detailssc.apply_decay(user_id) # apply importance decay (call periodically)sc.apply_decay() # apply to all usersstats=sc.engine.get_stats(plan)
# → {"candidates": 37, "active": 28, "selected": 11, "total_chars": 3200}

⚙️ Configuration

# config.yamlstorage:
backend: sqlite # sqlite | memory | redis | postgresqlpath: ./sc_data.dbmemory:
default_limit: 20ttl_hours:
working: 2# working nodes expire after 2 hoursepisodic: 720# episodic nodes expire after 30 dayscompression:
enabled: falsethreshold: 50keep_last: 10agents:
folder: ./agentshot_reload: truedefault: generalplugins:
enabled: truefolder: ./pluginsdebug:
retrieval: false

🔌 Plugin System

fromsimplecontext.plugins.baseimportBasePluginclassMyPlugin(BasePlugin):
name="my_plugin"depends_on= [] # declare dependenciesdefsetup(self):
self.count=self.state.get("count", 0) # persistent state# Hooks available:defon_message_saved(self, user_id, role, content, tags, metadata): ...
defon_before_llm(self, user_id, agent_id, messages) ->list: ...
defon_after_llm(self, user_id, agent_id, response) ->str: ...
defon_agent_routed(self, user_id, agent_id, message): ...
defon_prompt_build(self, agent_id, prompt) ->str: ...
defon_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

SimpleContextOpenVikingLangChainAutoGPT
Setup time< 1 min30+ min~5 min~10 min
DependenciesZeroGo + VLMManyMany
Tiered Memory
Intent Planning
Context Scoring
Fact Extraction
Conflict Handling
Agent YAML + Hot-reload
Agent Chaining⚠️⚠️
Plugin System⚠️
Multi-StorageVectorDBVectorDBVectorDB
Semantic Searchvia plugin✅ vector✅ vector✅ vector

🌐 Ecosystem

SimpleContext adalah core engine dari ekosistem yang terus berkembang. Gunakan bersama repositori lain untuk setup yang lebih lengkap:

RepositoriDeskripsi
SimpleContextCore engine — Universal AI Brain (repo ini)
SimpleContext-PluginOfficial & community plugin registry — tambah kemampuan via drop-in plugins
SimpleContext-BotAI Telegram Bot powered by SimpleContext — one-command setup, auto-downloads engine + agents
SimpleContext-AgentsReady-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 PluginDeskripsi
plugin-auto-taggerTag otomatis setiap pesan berdasarkan keyword rules
plugin-summarizerAuto-compress working memory ke episodic via LLM
plugin-sentimentDeteksi sentimen user, simpan ke metadata
plugin-rate-limiterBatasi frekuensi request per user
plugin-webhookKirim event ke endpoint eksternal via HTTP
plugin-translateAuto-translate pesan ke bahasa tertentu
plugin-analyticsDashboard statistik penggunaan per user/agent

Seberapa susah membuat plugin?

# Ini sudah cukup untuk jadi plugin yang valid:fromsimplecontext.plugins.baseimportBasePluginclassMyPlugin(BasePlugin):
name="my_plugin"version="1.0.0"defon_before_llm(self, user_id, agent_id, messages):
# lakukan sesuatu sebelum LLM dipanggilreturnmessages

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

About

🧠 Universal AI Brain — Tiered memory, context scoring, intent planning. Zero dependencies.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages