Skip to content

zacxyonly/SimpleContext

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🧠 SimpleContext

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

Python Tests License Dependencies Version


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

About

🧠 Universal AI Brain β€” Tiered memory, context scoring, intent planning. Zero dependencies.

Topics

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages