# ABI-Core 🤖
[![PyPI version](https://badge.fury.io/py/abi-core-ai.svg)](https://pypi.org/project/abi-core-ai/)
[![Python](https://img.shields.io/pypi/pyversions/abi-core-ai.svg)](https://pypi.org/project/abi-core-ai/)
[![License](https://img.shields.io/pypi/l/abi-core-ai.svg)](https://github.com/Joselo-zn/abi-core-ai/blob/main/LICENSE)
[![Documentation](https://readthedocs.org/projects/abi-core/badge/?version=latest)](https://abi-core.readthedocs.io/en/latest/?badge=latest)

**ABI-Core** is the foundation for building **Agent-Based Infrastructure** — a framework where intelligent agents collaborate through semantic context, policy-driven governance, and modular orchestration.

**ABI Swarm** is the runtime: a self-building multi-agent system that plans, orchestrates, and creates agents on demand — governed by policy.

> Beta Release — APIs may change. Feedback welcome.

---

## What Makes ABI Different

Most agent frameworks assume your agents and tools already exist. ABI doesn't.

- The **Planner** decomposes complex requests into tasks and finds (or creates) the right agents
- The **Orchestrator** coordinates execution across multiple agents with A2A protocol
- The **Builder** creates ephemeral agents on demand — Docker containers that live, execute, and die
- The **Guardian** enforces security policies via OPA before any agent communicates
- The **Semantic Layer** connects everything through vector search and MCP tools

If an agent doesn't exist for a task, ABI builds one. If a tool doesn't exist, ABI creates it. All governed by policy.

---

## Quick Start

```bash
pip install abi-core-ai

# Create a project
abi-core create project my-system --with-semantic-layer --with-guardian

# Add the swarm (planner + orchestrator + builder + semantic layer + guardian)
abi-core add abi-swarm

# Run
docker compose up -d
```

---

## Architecture

```
User Request
     │
     ▼
┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│ Orchestrator │────▶│   Planner   │────▶│   Builder   │
│              │     │             │     │             │
│ Coordinates  │     │ Decomposes  │     │ Creates     │
│ workflows    │     │ tasks       │     │ ephemeral   │
│              │     │ Finds agents│     │ agents      │
└──────┬───────┘     └─────────────┘     └──────┬──────┘
       │                                        │
       ▼                                        ▼
┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│   Agents    │     │  Semantic   │     │  Guardian   │
│             │◄───▶│   Layer     │◄───▶│  Security   │
│ Permanent   │     │             │     │             │
│ or Ephemeral│     │ Agent Cards │     │ OPA Policies│
│             │     │ Tool Cards  │     │ A2A Auth    │
│             │     │ MCP Tools   │     │ Audit Log   │
└─────────────┘     └─────────────┘     └─────────────┘
```

---

## Core Concepts

### AbiCore — FastAPI-style Agent Runner

```python
from my_agent import MyAgent
from abi_core.agent import AbiCore

agent = AbiCore()

@agent.task(name="step1")
def step1(raw_input):
    return {"cleaned": raw_input.strip()}

@agent.task(name="step2", depends_on=["step1"], input_map={"data": "$step1.result"})
def step2(data):
    return {"stored": True}

@agent.tool(name="search")
def search(query):
    """Available to the LLM on demand."""
    return {"results": []}

@agent.mcp_tool(name="bigquery_search", input_map={"query": "$input.user_query"})

agent.run(MyAgent())
```

### AbiAgent — Base Class with Heartbeat

```python
from abi_core.agent import AbiAgent
from config import config

class MyAgent(AbiAgent):
    def __init__(self):
        super().__init__(
            agent_name=config.AGENT_NAME,
            description=config.AGENT_DESCRIPTION,
            llm_config=config.LLM_CONFIG,
            tools=[],
            system_prompt="You are a helpful agent.",
        )
    # stream() inherited with SSE heartbeat + checkpointer memory
```

### ToolExecutionGraph — Deterministic DAG

Tasks registered with `@agent.task()` are wired into a LangGraph DAG. The LLM never decides execution order — the graph does. Retry, checkpoint/resume, and `$reference` resolution between nodes are built in.

### ToolCards — Governed Tool Discovery

```json
{
  "tool_name": "query_sales_db",
  "description": "Query the sales database",
  "access_scope": {
    "databases": ["sales_db"],
    "tables": ["sales_db.orders", "sales_db.products"],
    "permissions": ["read"],
    "storage": ["s3://company-data/sales/*"],
    "secrets": ["SALES_DB_CONNECTION_STRING"]
  },
  "checksum": "sha256:...",
  "install_key": "tool://query_sales_db@1.0.0"
}
```

The planner checks `access_scope` against agent permissions before assigning tools. The guardian validates checksums before execution.

### Zombie Container Pattern

Ephemeral agents are cloned from a "zombie" base container. No `docker build` — just `docker run` with env vars. The zombie reads `SYSTEM_PROMPT`, `TOOLS`, `AGENT_PORT` from environment and self-configures as a fully functional A2A agent.

---

## Features

- **AbiCore Runner** — `agent = AbiCore()` with auto-config import
- **Decorator API** — `@agent.task()`, `@agent.tool()`, `@agent.mcp_tool()`
- **ToolExecutionGraph** — LangGraph DAG for deterministic tool execution
- **SSE Heartbeat** — Automatic keepalive for CloudFront/proxy compatibility
- **AgentResponse** — Typed responses: `.success()`, `.error()`, `.status()`, `.input_required()`
- **A2AResponse** — Clean wrapper for A2A protocol parsing
- **Multi-Provider LLM** — Ollama, OpenAI, Anthropic, Bedrock, Azure, Vertex AI, Grok
- **MemorySaver** — Conversation memory across clarification rounds
- **MCP Protocol** — Streamable HTTP transport with auto-reconnection
- **MCPToolkit** — Dynamic tool calling with `await toolkit.my_tool(param="value")`
- **ToolCards** — Tool metadata with access_scope, checksum, and governance
- **Agent Cards** — Structured agent metadata for semantic discovery
- **A2A Validation** — HMAC-signed agent communication via OPA policies
- **Semantic Layer** — Weaviate vector search for agents and tools
- **Guardian** — OPA policy enforcement, audit logging, risk scoring
- **Builder** — Creates ephemeral agents in Docker containers on demand
- **Zombie Pattern** — Fast agent cloning from immutable base image
- **CLI** — `abi-core create project`, `abi-core add abi-swarm`, `abi-core add agent`

---

## CLI Commands

```bash
# Project
abi-core create project <name> [--with-semantic-layer] [--with-guardian]

# Swarm (planner + orchestrator + builder + prerequisites)
abi-core add abi-swarm

# Agents
abi-core add agent <name> --description "..."
abi-core remove agent <name>

# Services
abi-core add semantic-layer
abi-core add service guardian-native

# Cleanup
abi-core remove abi-swarm
```

---

## Project Structure

```
my-project/
├── agents/
│   ├── planner/          # Task decomposition
│   ├── orchestrator/     # Workflow coordination
│   ├── builder/          # Ephemeral agent creation
│   └── my-agent/         # Your custom agents
├── services/
│   ├── web_api/          # FastAPI application
│   ├── semantic_layer/   # MCP server + Weaviate
│   │   ├── agent_cards/
│   │   ├── tool_cards/
│   │   └── embedding_mesh/
│   └── guardian/         # OPA security
├── compose.yaml
└── .abi/runtime.yaml
```

---

## Documentation

[https://abi-core.readthedocs.io](https://abi-core.readthedocs.io)

---

## Contributing

```bash
git clone https://github.com/Joselo-zn/abi-core
cd abi-core-ai
uv sync --dev
uv run pytest
```

---

## License

Apache 2.0 — see [LICENSE](LICENSE)

---

**Built by [José Luis Martínez](https://github.com/Joselo-zn)** — Creator of ABI (Agent-Based Infrastructure)
