Metadata-Version: 2.4
Name: agentguardinc
Version: 0.1.0
Summary: Compliance infrastructure for AI agents — runtime monitoring, audit trails, guardrails.
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.1.0; extra == 'langchain'
Provides-Extra: yaml
Requires-Dist: pyyaml>=6.0; extra == 'yaml'
Description-Content-Type: text/markdown

<p align="center">
  <strong>AgentGuard</strong><br>
  Compliance infrastructure for AI agents
</p>

<p align="center">
  <a href="https://pypi.org/project/agentguard/"><img src="https://img.shields.io/pypi/v/agentguard?color=blue" alt="PyPI"></a>
  <a href="https://pypi.org/project/agentguard/"><img src="https://img.shields.io/pypi/pyversions/agentguard" alt="Python"></a>
  <a href="https://github.com/agentguardinc/agentguard-python/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-blue" alt="License"></a>
</p>

---

Runtime monitoring, audit trails, guardrails, and auto-generated compliance documentation for autonomous AI agents. Three lines of code to make your agent compliant with the EU AI Act, Colorado AI Act, and Texas TRAIGA.

**Zero external dependencies.** Runs anywhere Python runs.

```python
from agentguard import monitor, ctx

@monitor(regulation="eu-ai-act", audit="sqlite")
def my_agent(task):
    ctx.log_tool("web_search", query=task)
    ctx.log_reasoning("Searching for relevant information")
    return execute(task)
```

That's it. Every call is now monitored, audited, and checked against guardrails.

## Why AgentGuard

AI agents are making autonomous decisions in production — hiring candidates, approving loans, triaging patients. Regulations are catching up:

| Regulation | Enforcement | Scope |
|---|---|---|
| **EU AI Act** (high-risk) | August 2, 2026 | Any AI system sold/used in EU |
| **Colorado AI Act** | February 1, 2026 | High-risk automated decisions |
| **Texas TRAIGA** | September 1, 2025 | AI systems deployed in Texas |

AgentGuard gives you compliance-by-default: every agent decision gets a complete audit trail, risk classification, and guardrail enforcement — with ~32 microseconds of overhead per call.

## Install

```bash
pip install agentguard
```

Optional extras:

```bash
pip install agentguard[yaml]       # YAML config file support
pip install agentguard[langchain]  # LangChain callback handler
pip install agentguard[dev]        # pytest, coverage
```

## Quick Start

### Basic monitoring

```python
from agentguard import monitor, ctx

@monitor
def research_agent(topic):
    ctx.log_tool("search", query=topic)
    ctx.log_model("gpt-4", tokens=150)
    ctx.log_reasoning("Found 3 relevant sources, synthesizing")
    return {"summary": "...", "sources": [...]}

result = research_agent("quantum computing trends")
```

### With guardrails

```python
@monitor(
    guardrails=["pii", "scope"],
    pii_action="block",                    # block | warn | redact
    allowed_scopes=["research_agent"],     # restrict to allowed functions
    audit="sqlite",                        # stdout | jsonfile | sqlite
    audit_path="audit.db",
)
def research_agent(query):
    ctx.log_tool("search", query=query)
    return search(query)

# This will raise GuardrailViolation:
research_agent("Find info on john@example.com")
```

### Async support

```python
@monitor(audit="jsonfile", audit_path="events.jsonl")
async def async_agent(task):
    ctx.log_tool("api_call", endpoint="/data")
    result = await fetch_data(task)
    return result
```

### Nested agents

Parent-child relationships are tracked automatically:

```python
@monitor(agent_name="orchestrator")
def orchestrator(task):
    ctx.log_reasoning("Delegating to specialist")
    return specialist(task)

@monitor(agent_name="specialist")
def specialist(task):
    ctx.log_tool("process", task=task)
    return f"Processed: {task}"
```

## Decorator Forms

```python
@monitor                                        # zero-config
@monitor()                                      # explicit empty
@monitor(regulation="eu-ai-act", audit="sqlite") # fully configured
```

## Context API

Inside any `@monitor`-decorated function, use `ctx` to capture structured data:

```python
from agentguard import ctx

ctx.log_tool("tool_name", key="value")     # log tool/action usage
ctx.log_reasoning("explanation")            # log decision reasoning
ctx.log_model("gpt-4", tokens=250)         # log model and token usage
ctx.set("custom_key", "custom_value")       # arbitrary metadata
ctx.get("custom_key")                       # retrieve metadata
ctx.active                                  # True inside @monitor
```

All `ctx` methods are **no-ops outside `@monitor`** — your code never crashes.

## Guardrails

### PII Detection

Regex-based detection of emails, phone numbers, SSNs, credit cards, and IP addresses:

```python
@monitor(guardrails=["pii"], pii_action="block")
def agent(data):
    ...  # raises GuardrailViolation if PII found in input

@monitor(guardrails=["pii"], pii_action="warn")
def agent(data):
    ...  # logs warning but continues

@monitor(guardrails=["pii"], pii_action="redact")
def agent(data):
    ...  # replaces PII with [REDACTED] in output
```

**Pre-execution** guardrails can block. **Post-execution** guardrails only warn or redact — because side effects already happened.

### Scope Enforcement

Restrict which functions can run:

```python
@monitor(guardrails=["scope"], allowed_scopes=["read_data", "search"])
def unauthorized_action():
    ...  # raises GuardrailViolation
```

## Audit Trail

Three built-in backends:

| Backend | Use case | Config |
|---|---|---|
| `stdout` | Development/debugging | `audit="stdout"` |
| `jsonfile` | Simple production logging | `audit="jsonfile", audit_path="events.jsonl"` |
| `sqlite` | Queryable audit trail | `audit="sqlite", audit_path="audit.db"` |

The audit trail runs on a **background daemon thread** with a bounded queue (10K events). It never blocks your agent and never crashes — even if the backend fails.

```python
# Query the audit trail programmatically
from agentguard.audit.backends import SQLiteBackend

backend = SQLiteBackend(path="audit.db")
events = backend.query(limit=50, agent_name="my_agent")
```

## Configuration

### Resolution order

`kwargs` > `env vars` > `config file` > `defaults`

### Config file

Place `agentguard.json` (or `.yaml`/`.yml`) in your project root — AgentGuard walks up from cwd to find it:

```json
{
  "audit_backend": "sqlite",
  "audit_path": "audit.db",
  "guardrails": ["pii", "scope"],
  "pii_action": "warn",
  "allowed_scopes": ["research", "summarize"],
  "regulation": "eu-ai-act"
}
```

### Environment variables

```bash
AGENTGUARD_AUDIT_BACKEND=sqlite
AGENTGUARD_AUDIT_PATH=audit.db
AGENTGUARD_PII_ACTION=block
AGENTGUARD_REGULATION=eu-ai-act
AGENTGUARD_ALLOWED_SCOPES=read,write,search
AGENTGUARD_GUARDRAILS=pii,scope
```

## CLI

```bash
# Classify risk level of a Python file
agentguard classify agent.py
agentguard classify agent.py --json

# Check compliance against a regulation
agentguard check agent.py --regulation eu-ai-act

# Query the audit trail
agentguard trail --backend jsonfile --path events.jsonl --limit 20
agentguard trail --backend sqlite --path audit.db --agent my_agent

# Generate Annex IV documentation
agentguard docs --name "My AI System" --output compliance.md
agentguard docs --name "My AI System" --trail-path audit.db
```

## EU AI Act Compliance

AgentGuard maps your agent against **Annex III** high-risk categories (biometric, employment, education, law enforcement, etc.) and generates **Annex IV** technical documentation:

```python
from agentguard.regulations.eu_ai_act import EUAIActRegulation

reg = EUAIActRegulation()

# Classify risk
risk = reg.classify_risk({
    "purpose": "candidate screening",
    "domain": "recruitment",
})
# Returns: "high"

# Full compliance check
result = reg.check_compliance({
    "purpose": "candidate screening",
    "domain": "recruitment",
    "documentation": True,
    "human_oversight": True,
    "audit_trail": True,
    "risk_management": True,
})
print(result.compliant)        # True
print(result.recommendations)  # []
```

## LangChain Integration

```python
from agentguard import monitor, ctx
from agentguard.integrations.langchain import AgentGuardCallbackHandler

@monitor(regulation="eu-ai-act", audit="sqlite", audit_path="audit.db")
def langchain_agent(query):
    chain = LLMChain(llm=llm, prompt=prompt)
    return chain.invoke(
        {"query": query},
        config={"callbacks": [AgentGuardCallbackHandler()]}
    )
```

The callback handler automatically captures model name, token usage, and tool calls into the AgentGuard context.

## Design Principles

- **Never crash.** AgentGuard is fail-open: if monitoring fails, your agent runs unmonitored. Audit never blocks. Context methods are no-ops outside `@monitor`.
- **Zero dependencies.** Core SDK uses only the Python standard library. No supply chain risk.
- **Microsecond overhead.** ~32 microseconds per decorated call. Background audit thread. No I/O on the hot path.
- **Thread-safe and async-safe.** Uses `contextvars` for proper isolation across threads and async tasks.

## Architecture

```
@monitor decorator
    |
    +-- Pre-guardrails (may block)
    |       +-- PII check
    |       +-- Scope check
    |
    +-- Function execution (with DecisionContext active)
    |       +-- ctx.log_tool()
    |       +-- ctx.log_reasoning()
    |       +-- ctx.log_model()
    |
    +-- Post-guardrails (warn/redact only)
    |
    +-- AuditTrail.emit() (non-blocking, background thread)
            +-- StdoutBackend / JSONFileBackend / SQLiteBackend
```

## Development

```bash
git clone https://github.com/agentguardinc/agentguard-python.git
cd agentguard-python
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest --cov=agentguard --cov-report=term-missing
```

## License

Apache 2.0 — see [LICENSE](LICENSE).
