Skip to main content

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

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

simplecontext_ai-4.3.0.tar.gz (88.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

simplecontext_ai-4.3.0-py3-none-any.whl (85.8 kB view details)

Uploaded Python 3

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

Hashes for simplecontext_ai-4.3.0.tar.gz
Algorithm Hash digest
SHA256 9d13b1777d13b223ef5e096308a35fd9bc3aa95148c27d2bacd2816e8b579054
MD5 be4b72f1afdb114e41e2f9a9a184ec06
BLAKE2b-256 a5d69d46f2b3d9cd5c9ace2a2683700a29c5e55bb46c46d5dc76f7867f3a059b

See more details on using hashes here.

File details

Details for the file simplecontext_ai-4.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for simplecontext_ai-4.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0bcd19dbe20fc47021dc0d04515db523dc63b16fb2642b1647818bba547ef15d
MD5 585ffcd5feaa7578ac6463d34ba85ec8
BLAKE2b-256 9c015e68e01189c7db6248d7bab018ccb7193c18f75597c00fad1e94a5ae224e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page