Development Guide
Development Guide
Section titled “Development Guide”Development workflow, testing, and code quality commands.
Quick Start
Section titled “Quick Start”# Install dependenciesuv sync --dev
# Activate environmentsource .venv/bin/activate
# Run testspytest
# Format and lintruff format . && ruff check --fix .
# Type checkmypy src/Development Workflow
Section titled “Development Workflow”1. Create Feature Branch
Section titled “1. Create Feature Branch”git checkout -b feature/your-feature-name2. Make Changes
Section titled “2. Make Changes”Edit code following project conventions (see Code Style section).
3. Test Changes
Section titled “3. Test Changes”# Run all testspytest
# Run specific test filepytest tests/test_prompts.py
# Run with coveragepytest --cov=consumer_agent --cov-report=htmlopen htmlcov/index.html4. Format and Lint
Section titled “4. Format and Lint”# Auto-format coderuff format .
# Check and fix lint issuesruff check --fix .
# Sort importsruff check --select I --fix .5. Type Check
Section titled “5. Type Check”# Check all source filesmypy src/
# Check specific filemypy src/consumer_agent/agent/agent.py6. Commit Changes
Section titled “6. Commit Changes”git add .git commit -m "Brief description of changes
- Specific change 1- Specific change 2- Specific change 3"Follow conventional commit format: feat:, fix:, docs:, refactor:, test:, chore:
7. Push and Create PR
Section titled “7. Push and Create PR”git push origin feature/your-feature-nameCreate PR on GitHub with description of changes.
Testing
Section titled “Testing”Run Tests
Section titled “Run Tests”# All tests (skips integration by default)pytest
# Include integration testspytest -m integration
# Run with verbose outputpytest -v
# Run specific testpytest tests/test_prompts.py::test_prompt_manager_loads_conversational_v3
# Run with debug outputpytest -v -sTest Coverage
Section titled “Test Coverage”# Generate coverage reportpytest --cov=consumer_agent --cov-report=html
# View in browseropen htmlcov/index.html
# Terminal reportpytest --cov=consumer_agent --cov-report=termWriting Tests
Section titled “Writing Tests”Create test files in tests/ with test_ prefix:
import pytestfrom consumer_agent.agent import Agent
@pytest.mark.asyncioasync def test_agent_streaming(): """Test agent streaming responses.""" model = create_chat_model() agent = Agent(model)
messages = [{"role": "user", "content": "Hello"}] events = []
async for event in agent.stream(messages, "You are helpful."): events.append(event)
assert len(events) > 0Mark integration tests:
@pytest.mark.integrationasync def test_mcp_connection(): """Test MCP server connection (requires server).""" passExpensive Tests (Costs Money)
Section titled “Expensive Tests (Costs Money)”Some tests make real OpenAI API calls and cost money. These are marked with @pytest.mark.requires_openai and are skipped by default.
Run expensive tests explicitly:
# Run all tests that require OpenAI (WARNING: costs money)pytest -m requires_openai
# Run specific expensive testpytest -m requires_openai tests/integration/test_landing_page_evaluation.py
# Run expensive integration tests onlypytest -m "requires_openai and integration"Available test markers:
unit: Unit tests (no external dependencies)integration: Integration tests (may require external services)requires_openai: Tests that make OpenAI API calls (costs money)requires_mcp: Tests that require MCP serverrequires_aws: Tests that require real AWS credentials
Code Quality
Section titled “Code Quality”Ruff (Linting and Formatting)
Section titled “Ruff (Linting and Formatting)”Configuration in pyproject.toml:
[tool.ruff]line-length = 100target-version = "py311"
[tool.ruff.lint]select = ["E", "F", "I", "N", "W", "UP"]ignore = ["E501"]Commands:
# Format coderuff format .
# Check lintingruff check .
# Fix auto-fixable issuesruff check --fix .
# Check specific fileruff check src/consumer_agent/agent/agent.pyMypy (Type Checking)
Section titled “Mypy (Type Checking)”Configuration in pyproject.toml:
[tool.mypy]python_version = "3.11"strict = truewarn_return_any = truewarn_unused_configs = truedisallow_untyped_defs = trueCommands:
# Check all source filesmypy src/
# Check specific filemypy src/consumer_agent/agent/agent.py
# Show error contextmypy --show-error-context src/Pre-commit Hooks
Section titled “Pre-commit Hooks”Install hooks:
pre-commit installRun manually:
# All filespre-commit run --all-files
# Staged files onlypre-commit runHooks run automatically on git commit.
Code Style
Section titled “Code Style”General Rules
Section titled “General Rules”- Line length: 100 characters
- Use type hints for all functions
- Docstrings for public functions (Google style)
- Import order: stdlib, third-party, local
Type Hints
Section titled “Type Hints”# Gooddef create_agent(model: BaseLanguageModel, tools: list[BaseTool] | None = None) -> Agent: """Create agent with tools.""" pass
# Bad - missing type hintsdef create_agent(model, tools=None): passDocstrings
Section titled “Docstrings”Use Google style:
def load_config(config_path: str | None = None) -> dict[str, Any]: """Load agent configuration from YAML file.
Args: config_path: Path to config file. If None, uses default.
Returns: Configuration dictionary
Raises: FileNotFoundError: If config file not found yaml.YAMLError: If config file invalid """ passImport Sorting
Section titled “Import Sorting”Order:
- Standard library
- Third-party packages
- Local imports
# Standard libraryimport osfrom pathlib import Path
# Third-partyimport yamlfrom langchain.agents import create_agent
# Localfrom consumer_agent.config import get_openai_configRunning Locally
Section titled “Running Locally”FastAPI Server
Section titled “FastAPI Server”# Development mode (auto-reload)uvicorn consumer_agent.api.main:app --reload --port 8000
# Production modeuvicorn consumer_agent.api.main:app --host 0.0.0.0 --port 8000Test endpoints:
# Health checkcurl http://localhost:8000/health
# Stream responsecurl -X POST http://localhost:8000/agent/stream \ -H "Content-Type: application/json" \ -d '{ "messages": [{"role": "user", "content": "Hello"}], "agent_id": "conversational", "enabled_components": [] }'TUI Chatbot
Section titled “TUI Chatbot”# Via CLI commandconsumer-agent chat
# Direct Pythonpython src/consumer_agent/cli/chat.pyDebugging
Section titled “Debugging”Enable Debug Logging
Section titled “Enable Debug Logging”Set log level in code:
from loguru import loggerimport sys
logger.remove()logger.add(sys.stderr, level="DEBUG")IPython/Jupyter
Section titled “IPython/Jupyter”# Install ipythonuv add --dev ipython
# Start interactive sessionipython
# In IPython:from consumer_agent.agent import Agentfrom consumer_agent.factory import create_chat_model
model = create_chat_model()agent = Agent(model)Print Debugging
Section titled “Print Debugging”# During streamingasync for event in agent.stream(messages, system_prompt): print(f"[DEBUG] Event: {event.event_type}, Content: {event}")Pytest Debugging
Section titled “Pytest Debugging”# Show print statementspytest -s
# Drop into debugger on failurepytest --pdb
# Drop into debugger at startpytest --traceCommon Tasks
Section titled “Common Tasks”Add New Tool
Section titled “Add New Tool”- Create tool class in
src/consumer_agent/utils/tools.py:
class NewTool(BaseTool): name: str = "new_tool" description: str = "Tool description" args_schema: type[BaseModel] = NewToolInput mcp_client: MCPClient
async def _arun(self, arg1: str, ...) -> str: result = await self.mcp_client.call_tool("new_tool", {"arg1": arg1}) return str(result)- Add to
build_mcp_tools():
def build_mcp_tools(...) -> list[BaseTool]: tools = [ # Existing tools... NewTool(mcp_client), ] return tools- Test:
@pytest.mark.asyncioasync def test_new_tool(): # Test implementation passAdd New Prompt
Section titled “Add New Prompt”- Create file in
prompts/:
touch prompts/specialized-task-v1.txt-
Add content to file
-
Load in code:
from consumer_agent.prompts import PromptManager
prompt = PromptManager.load_prompt("specialized-task-v1")- Add test:
def test_specialized_task_prompt_loads(): prompt = PromptManager.load_prompt("specialized-task-v1") assert len(prompt) > 0Update Dependencies
Section titled “Update Dependencies”# Add new dependencyuv add package-name
# Add dev dependencyuv add --dev package-name
# Update all dependenciesuv sync
# Update specific packageuv add package-name@latestBuild Distribution
Section titled “Build Distribution”# Build wheel and sdistuv build
# Output in dist/ls dist/GitHub Actions
Section titled “GitHub Actions”Tests run automatically on:
- Push to any branch
- Pull request creation
- Pull request updates
Check status:
# View recent workflow runsgh run list
# View specific rungh run view <run-id>Local CI Simulation
Section titled “Local CI Simulation”# Run full test suitepytest --cov=consumer_agent
# Run lintingruff check .
# Run type checkingmypy src/
# Run all checks (like CI)ruff format . && ruff check --fix . && mypy src/ && pytestProject Structure
Section titled “Project Structure”consumer-agent/├── src/consumer_agent/│ ├── agent/ # Agent implementation│ │ ├── agent.py # Main agent class│ │ ├── prompts.py # PromptManager for system prompts│ │ └── streaming.py # Event types│ ├── api/ # FastAPI service│ │ └── main.py # FastAPI application│ ├── cli/ # CLI interface│ │ ├── main.py # Click CLI│ │ └── chat.py # TUI chatbot│ ├── evaluation/ # Opik integration + metrics│ ├── history/ # DynamoDB + S3 persistence│ ├── utils/ # Utilities│ │ ├── mcp_client.py # MCP JSON-RPC client│ │ └── tools.py # MCP tool wrappers│ ├── config.py # Configuration management│ └── factory.py # Model + agent factory├── prompts/ # System prompts│ └── components/ # Feature-flagged YAML instructions├── tests/ # Test suite├── docs/ # Documentation├── .env.example # Environment template├── agent_config.yaml # Agent configuration├── settings.yaml # Infrastructure configuration└── pyproject.toml # Project metadataUseful Commands Reference
Section titled “Useful Commands Reference”# Environmentuv sync # Install depsuv sync --dev # Install with dev depssource .venv/bin/activate # Activate venv
# Testingpytest # Run testspytest -v # Verbosepytest --cov # With coveragepytest -k test_name # Run specific test
# Code Qualityruff format . # Format coderuff check . # Lint coderuff check --fix . # Fix lint issuesmypy src/ # Type check
# Runninguvicorn consumer_agent.api.main:app --reload # FastAPIconsumer-agent chat # TUIpython -m consumer_agent.cli.chat # TUI direct
# Dependenciesuv add package-name # Add dependencyuv add --dev package-name # Add dev dependencyuv remove package-name # Remove dependency
# Gitgit status # Check statusgit add . # Stage changesgit commit -m "message" # Commitgit push # Push to remoteReferences
Section titled “References”- Setup Guide - Installation and environment
- Architecture Guide - System design
- Responses API - Streaming events
- MCP Guide - Tool integration