# CLAUDE.md - Broadie AI Agent Framework

## Project Overview

**Broadie** is an opinionated AI agent framework built on LangGraph and LangServe, designed to reduce hallucination through structured contracts between agents, LLMs, and tools using Pydantic models. This is a production-ready framework for building and deploying AI agents with enterprise-grade reliability.

- **Version**: 2.0.6
- **Language**: Python 3.10+
- **License**: MIT AND (Apache-2.0 OR BSD-2-Clause)
- **Author**: Broad Institute

## Key Features

- **Structured Outputs**: Uses strict Pydantic schemas to enforce structured outputs and reduce hallucination
- **Clear Contracts**: Defines clear contracts between agents, LLMs, and tools
- **Built-in Memory**: Leverages built-in memory and persistence for stateful conversations
- **A2A Communication**: Supports agent-to-agent (a2a) communication through a central registry
- **Easy Deployment**: Provides easy deployment with minimal configuration
- **Channel Integration**: Built-in Slack and email notification support
- **Observability**: LangSmith integration for tracing and monitoring

## Project Structure

```
broadie/
├── src/broadie/           # Main package source
│   ├── agents.py         # Core agent classes (Agent, BaseAgent, SubAgent)
│   ├── factory.py        # Factory functions (create_agent, create_sub_agent)
│   ├── config.py         # Configuration settings
│   ├── schemas.py        # Pydantic schemas (AgentSchema, ModelSchema, etc.)
│   ├── cli.py            # CLI commands (serve, chat, version)
│   ├── utils.py          # Utility functions (slugify)
│   ├── mixins.py         # Agent mixins
│   ├── server/           # FastAPI server components
│   ├── tools/            # Built-in tools (channels, memory, tasks)
│   └── a2a/              # Agent-to-agent communication
├── tests/                # Test suite with pytest
├── examples/             # Example agents (simple.py, standard.py, advanced.py)
├── docs/                 # Documentation (README.md)
├── .env                  # Environment configuration
├── pyproject.toml        # Project configuration and dependencies
└── mise.toml             # Development tooling configuration
```

## Development Setup

### Prerequisites

- Python 3.10+
- Google Cloud account with Vertex AI access
- Virtual environment (automatically managed in `.venv`)

### Installation

```bash
# Install development dependencies
pip install -e .[dev]

# Or install base dependencies only
pip install -e .
```

### Environment Configuration

The project requires several environment variables (stored in `.env`):

```bash
# Core configuration
API_KEY=<generated-api-key>
DEBUG=True
PORT=2024
HOST=localhost

# Google Cloud (required for Vertex AI)
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json
GOOGLE_CLOUD_PROJECT=your-gcp-project-id
GOOGLE_CLOUD_LOCATION=us-central1

# Database
DATABASE_URL=sqlite+aiosqlite:///./data/sqlite_dev.sqlite3

# LangSmith Tracing
LANGCHAIN_TRACING_V2=true
LANGCHAIN_API_KEY=<langsmith-api-key>
LANGCHAIN_PROJECT=<project-name>

# A2A (Agent-to-Agent)
A2A_ENABLED=true
A2A_REGISTRY_URL=http://localhost:2024/registry

# Channel integrations
SLACK_BOT_TOKEN=<slack-bot-token>
SLACK_SIGNING_SECRET=<slack-signing-secret>
SMTP_HOST=<smtp-server>
EMAIL_FROM=<sender-email>
```

## Development Workflow

### Running Tests

```bash
# Run all tests
pytest -v

# Run specific test file
python -m pytest tests/broadie/test_agents.py -v

# Run with coverage
pytest -v --cov=src/broadie
```

### Code Quality

```bash
# Lint and format check
ruff format --check . && ruff check .

# Auto-fix lint and formatting issues
ruff format . && ruff check --fix .

# Using mise tasks
mise run lint      # Check formatting and linting
mise run lint:fix  # Auto-fix issues
```

### Running the Application

```bash
# Serve an agent (with playground)
broadie serve examples/simple.py:simple_agent --port 8000

# Chat with an agent in CLI
broadie chat examples/simple.py:simple_agent

# Using mise tasks
mise run serve  # Serves simple agent on port 2024
```

### Building and Distribution

```bash
# Build package
python -m build

# Install locally for testing
pip install -e .
```

## Core Components

### Agents (`src/broadie/agents.py`)

- **BaseAgent**: Abstract base class with core functionality
- **Agent**: Main agent implementation with tools, subagents, and channels
- **SubAgent**: Specialized agent for specific tasks

### Factory Functions (`src/broadie/factory.py`)

- `create_agent()`: Creates main agents with tools, subagents, channels
- `create_sub_agent()`: Creates specialized sub-agents

### Tools (`src/broadie/tools/`)

- **ToolResponse**: Structured response pattern for tools
- **Channels**: Slack, email, and API notification tools
- **Memory**: User fact storage and retrieval
- **Tasks**: Task management capabilities

### Configuration (`src/broadie/config.py`)

- Pydantic Settings-based configuration
- Environment variable management
- Default values and validation

## Testing

The test suite uses pytest with comprehensive mocking:

- **Fixtures**: Mock agents, settings, and external dependencies (`tests/conftest.py`)
- **Auto-mocking**: Automatic mocking of network calls (Slack, SMTP, HTTP)
- **Async Support**: Full async/await testing support
- **Test Coverage**: Tests for agents, tools, configuration, CLI, and more

### Key Test Files

- `tests/broadie/test_agents.py`: Agent functionality tests
- `tests/broadie/test_tools.py`: Tool and channel tests
- `tests/broadie/test_config.py`: Configuration tests
- `tests/broadie/test_cli.py`: CLI command tests

## Examples

### Simple Agent (`examples/simple.py`)

Basic agent with minimal configuration for getting started.

### Standard Agent (`examples/standard.py`)

Feature-complete example with tools, structured output, and channels.

### Advanced Agent (`examples/advanced.py`)

Complex multi-agent setup with subagents, A2A communication, and full observability.

## Common Commands

```bash
# Development
mise run install:dev    # Install dev dependencies
mise run test          # Run tests
mise run lint          # Check code quality
mise run lint:fix      # Fix code issues
mise run serve         # Serve example agent

# CLI Usage
broadie version                              # Show version
broadie serve examples/simple.py:agent     # Serve agent
broadie chat examples/simple.py:agent      # Chat with agent

# Testing
pytest -v                                   # Run all tests
python -m pytest tests/broadie/test_agents.py -v  # Specific tests
```

## Key Dependencies

### Core Framework
- **langchain** (>=0.3.27): Core LangChain functionality
- **langgraph** (>=0.6.6): Agent workflow graphs
- **langchain-google-vertexai** (>=2.0.28): Google AI integration
- **fastapi** (>=0.116.1): Web server and API
- **pydantic-settings** (>=2.10.1): Configuration management

### Database & Storage
- **langgraph-checkpoint-postgres** (>=2.0.23): PostgreSQL checkpointing
- **langgraph-checkpoint-sqlite** (>=2.0.11): SQLite checkpointing
- **asyncpg** (>=0.30.0): Async PostgreSQL driver

### Development Tools
- **pytest** (8.4.1): Testing framework
- **pytest-asyncio** (1.1.0): Async testing support
- **ruff** (0.12.11): Linting and formatting

## Architecture Notes

### Contract System
Broadie enforces contracts between agents, LLMs, and tools:
- **Agent Contract**: Defines capabilities, tools, and expected outputs
- **LLM Contract**: Structured via Pydantic schemas to prevent hallucination
- **Tool Contract**: Type-safe tool definitions with clear input/output schemas

### Memory & Persistence
- Automatic persistent memory for conversations
- Thread-based conversation tracking
- User fact storage and retrieval
- SQLite/PostgreSQL checkpoint storage

### Channels
Built-in notification system supporting:
- **Slack**: Block-based messaging
- **Email**: SMTP-based notifications
- **API**: Webhook notifications

## Security Considerations

- API keys are auto-generated and stored in `.env`
- Google Cloud authentication via service account
- Environment-based configuration
- No hardcoded secrets in codebase

## Deployment

The framework supports various deployment options:
- Local development server
- Docker containers (configuration in progress)
- Cloud deployment (GCP/AWS)
- Kubernetes (future feature)
