Metadata-Version: 2.4
Name: symfonic-core
Version: 4.9.0
Summary: Agent Graph Framework — core graph primitives for symfonic
Author: AmSiDev
License-Expression: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: langchain-core<1.0,>=0.3
Requires-Dist: langgraph<1.0,>=0.2
Requires-Dist: pydantic<3.0,>=2.0
Provides-Extra: agent-api
Requires-Dist: fastapi>=0.115; extra == 'agent-api'
Requires-Dist: jinja2>=3.1; extra == 'agent-api'
Requires-Dist: sse-starlette>=2.0; extra == 'agent-api'
Provides-Extra: agent-dev
Requires-Dist: fastapi>=0.115; extra == 'agent-dev'
Requires-Dist: jinja2>=3.1; extra == 'agent-dev'
Requires-Dist: mypy>=1.13; extra == 'agent-dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'agent-dev'
Requires-Dist: pytest-cov>=5.0; extra == 'agent-dev'
Requires-Dist: pytest>=8.0; extra == 'agent-dev'
Requires-Dist: ruff>=0.8; extra == 'agent-dev'
Requires-Dist: sse-starlette>=2.0; extra == 'agent-dev'
Provides-Extra: anthropic
Requires-Dist: langchain-anthropic<1.0,>=0.3; extra == 'anthropic'
Requires-Dist: python-dotenv>=1.0; extra == 'anthropic'
Provides-Extra: chroma
Requires-Dist: langchain-chroma>=0.2.0; extra == 'chroma'
Provides-Extra: cli
Requires-Dist: typer>=0.12; extra == 'cli'
Provides-Extra: demo
Requires-Dist: aiosqlite>=0.19; extra == 'demo'
Requires-Dist: asyncpg>=0.29; extra == 'demo'
Requires-Dist: celery[redis]>=5.3; extra == 'demo'
Requires-Dist: chromadb>=0.4; extra == 'demo'
Requires-Dist: fastapi>=0.115; extra == 'demo'
Requires-Dist: httpx>=0.27; extra == 'demo'
Requires-Dist: jinja2>=3.1; extra == 'demo'
Requires-Dist: motor>=3.3; extra == 'demo'
Requires-Dist: pgvector>=0.3; extra == 'demo'
Requires-Dist: sqlalchemy[asyncio]>=2.0; extra == 'demo'
Requires-Dist: sse-starlette>=2.0; extra == 'demo'
Provides-Extra: dev
Requires-Dist: build>=1.0; extra == 'dev'
Requires-Dist: langchain-anthropic<1.0,>=0.3; extra == 'dev'
Requires-Dist: mypy>=1.13; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: python-dotenv>=1.0; extra == 'dev'
Requires-Dist: ruff>=0.8; extra == 'dev'
Provides-Extra: knowledge
Requires-Dist: chromadb>=0.4; extra == 'knowledge'
Provides-Extra: mcp
Requires-Dist: httpx>=0.27; extra == 'mcp'
Provides-Extra: mongodb
Requires-Dist: motor>=3.3; extra == 'mongodb'
Provides-Extra: openai
Requires-Dist: langchain-openai<1.0,>=0.3; extra == 'openai'
Provides-Extra: postgres
Requires-Dist: asyncpg>=0.29; extra == 'postgres'
Requires-Dist: pgvector>=0.3; extra == 'postgres'
Provides-Extra: prompts
Requires-Dist: jinja2>=3.1; extra == 'prompts'
Provides-Extra: testing
Requires-Dist: pytest-asyncio>=0.24; extra == 'testing'
Requires-Dist: pytest-cov>=5.0; extra == 'testing'
Requires-Dist: pytest>=8.0; extra == 'testing'
Description-Content-Type: text/markdown

# symfonic-core

Hierarchical Memory System for AI Agents

## Overview

`symfonic-core` is a Python framework for building AI agents with persistent,
structured memory. It implements a five-layer Hierarchical Memory System (HMS)
inspired by cognitive science: Semantic, Episodic, Working, Prospective, and
Procedural memory -- all backed by Postgres for durable persistence.

The framework goes beyond simple retrieval-augmented generation. On every
query, it hydrates context from multiple memory layers, runs spreading
activation across the knowledge graph to surface related facts, executes the
LLM, extracts structured memory operations from the response, and consolidates
them back into the appropriate layers. A Deep Sleep consolidation engine
strengthens recurring knowledge, prunes stale nodes, and generates meta-nodes
from clusters -- running as a nightly task or on manual trigger.

`symfonic-core` ships three cooperating subpackages in a single distribution:

| Subpackage | Role |
|-----------|------|
| `symfonic.core` | Graph execution engine: nodes, edges, DI container, tools, streaming |
| `symfonic.memory` | 5-layer HMS: episodic, semantic, procedural, prospective, working |
| `symfonic.agent` | Orchestration: wires core + memory, exposes `SymfonicAgent`, FastAPI bridge |

## Quick Start

### Installation

```bash
pip install symfonic-core \
  --index-url https://gitea-teotl.amsiops.io/api/packages/AmSiDev/pypi/simple
```

With Anthropic provider and FastAPI support:

```bash
pip install "symfonic-core[anthropic,agent-api]" \
  --index-url https://gitea-teotl.amsiops.io/api/packages/AmSiDev/pypi/simple
```

### Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `ANTHROPIC_API_KEY` | For real LLM | Anthropic API key |
| `POSTGRES_DSN` | For persistence | PostgreSQL connection string |
| `MONGODB_URI` | Optional | MongoDB URI for graph visualization secondary |

### Minimal Code Example

```python
import asyncio
from symfonic.agent import SymfonicAgent, FrameworkTenantScope
from symfonic.core.testing import MockModelProvider

async def main() -> None:
    agent = SymfonicAgent(model_provider=MockModelProvider(response="Hello!"))
    scope = FrameworkTenantScope(tenant_id="acme")
    response = await agent.run("What do you know about us?", scope=scope)
    print(response.final_response)
    print(f"Memory entries used: {response.memory_entries_used}")
    print(f"Duration: {response.duration_ms:.0f}ms")

asyncio.run(main())
```

## The Pentad -- 5 Memory Layers

| Layer | Purpose | Backend | Persistence |
|-------|---------|---------|-------------|
| Semantic | Stable knowledge graph -- facts, entities, relationships | Postgres Graph (+ optional MongoDB secondary) | Persistent |
| Episodic | Timestamped interaction history and events | Postgres Vector | Persistent |
| Working | Active reasoning context with 24h TTL thinking nodes | Postgres Graph (short-TTL) | Persistent |
| Prospective | Future plans, reminders, scheduled triggers | Postgres Graph | Persistent |
| Procedural | Learned skills, workflows, tool routing | Postgres Graph + SkillRegistry | Persistent |

All five layers share the `BaseMemoryStore` protocol with a uniform
`write / retrieve / delete` interface and strict per-tenant isolation via
`TenantScope`.

## Key Features

- **Deep Sleep Consolidation** -- Offline engine with 7 phases: strengthen
  recurring nodes, create co-occurrence edges, tag risk nodes, consolidate
  pending inferred edges, prune stale orphans, generate meta-nodes from
  clusters, and apply SOUL schema corrections.
- **Spreading Activation** -- On every query, expands semantic hits with
  first-degree graph neighbors. Returns `activation_log` metadata with
  `activated_nodes`, `inference_paths`, and `pending_connections`.
- **EventTranspiler Streaming** -- Converts LangGraph events into typed
  `TimestampedEvent` objects with millisecond precision. Supports Anthropic
  extended thinking blocks (`ThinkingDeltaEvent` / `TextDeltaEvent`).
- **Multi-Tenant Isolation** -- `FrameworkTenantScope` bridges core and memory
  scopes. No data crosses tenant boundaries.
- **Domain Plugins** -- `DomainTemplate` injects business-specific labels,
  onboarding checklists, SOUL schemas, and monitoring blueprints without
  modifying the framework.
- **Dual-Write Observer** -- Postgres as primary, MongoDB as optional
  secondary for graph visualization (vis.js).
- **Memory Extraction Pipeline** -- 4-strategy parser extracts structured
  `MEMORY_EXTRACT` / `GRAPH_OPERATIONS` blocks from LLM responses.
- **SemanticMerge Janitor** -- Deduplicates similar nodes by textual
  similarity.
- **AnomalyDetection** -- Sub-agent monitoring with configurable thresholds
  and finding records.
- **SkillRegistry** -- Procedural layer stores learned skills and routes tools
  via `CapabilityRouter`.

## API Endpoints

The FastAPI router (`create_agent_router`) mounts these endpoints:

| Method | Path | Description |
|--------|------|-------------|
| POST | `/chat` | Synchronous agent execution, returns `AgentResponse` |
| POST | `/stream` | SSE streaming, yields `StreamChunk` events |
| GET | `/chats` | List chat sessions for tenant |
| GET | `/memories/status` | Memory block status per label |
| GET | `/memories` | List all semantic memory nodes |
| PATCH | `/memories/{node_id}` | Update a memory node |
| DELETE | `/memories/{node_id}` | Delete a memory node |
| GET | `/procedures` | List procedural skill nodes |
| PATCH | `/procedures/{node_id}` | Update a procedure |
| POST | `/procedures/{node_id}/toggle` | Toggle procedure active flag |
| POST | `/procedures/deduplicate` | SemanticMerge deduplication |
| POST | `/memory/consolidate` | Trigger Deep Sleep consolidation |

The full demo (`examples/full_demo/`) adds additional endpoints for metrics,
traces, analytics, graph visualization, billing, sub-agent findings, and
scheduled tasks.

## Architecture

```
Query --> SymfonicAgent.run() / stream()
           |
           +--> _hydrate()
           |      |-- Retrieve from Semantic, Episodic, Procedural, Prospective layers
           |      |-- SpreadingActivation.expand() (1st-degree graph neighbors)
           |      '-- Format context string with activation_log metadata
           |
           +--> AgentRuntime (LangGraph execution)
           |      |-- HMS system prompt (9 sections)
           |      |-- EventTranspiler (stream mode: thinking/text_delta/tool events)
           |      '-- LLM generates response + MEMORY_EXTRACT block
           |
           +--> _consolidate() (background)
                  |-- Parse extraction ops (4-strategy parser)
                  |-- Write to appropriate memory layers
                  |-- Mirror to MongoDB (dual-write, optional)
                  |-- Write thinking nodes to Working memory (24h TTL)
                  '-- Write episodic turn summary
```

## Demo

Run the full interactive demo with Postgres, MongoDB, and web UI:

```bash
cd examples/full_demo
# Start infrastructure
docker compose up -d  # Postgres + MongoDB
# Install dependencies
pip install -e ".[agent-api,anthropic,mongodb]"
# Run server (mock mode or with ANTHROPIC_API_KEY)
python -m examples.full_demo.server
```

Open http://localhost:8000 for the web UI with chat, Memory Vault, graph
visualization, workflows, analytics, and observability panels.

See [examples/full_demo/README.md](examples/full_demo/README.md) for details.

## Documentation

| Guide | Description |
|-------|-------------|
| [Architecture](docs/concepts/architecture.md) | Component diagram, data flow, multi-tenant isolation |
| [Memory (HMS)](docs/concepts/memory.md) | 5 layers, hydration, spreading activation, Deep Sleep consolidation |
| [Agent Layer](docs/concepts/agent.md) | SymfonicAgent, AgentResponse, streaming events, domain plugins |
| [Capabilities & DI](docs/concepts/capabilities.md) | Protocol-based dependency injection |
| [Examples](docs/concepts/examples.md) | Walk-through of curated examples |

## Testing

```bash
pytest tests/ -q
# With coverage
pytest --cov=symfonic.core --cov=symfonic.memory --cov=symfonic.agent --cov-report=term-missing
```

1995 tests covering unit, integration, and contract layers.

## Development

```bash
git clone <repo-url> && cd symfonic-core
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"

# Type checking
mypy src/

# Linting
ruff check src/ tests/
```

## License

MIT
