SDK Documentation

Python SDK

Pythonic SDK with async support, type hints, smart analysis, and seamless integration

pip
Package Manager
3.7+
Python Version
Async
Native Support

Installation

Install with pip

pip install autonoma

Install with Poetry

poetry add autonoma

Install with Conda

conda install -c autonoma autonoma

Requirements File

# requirements.txt
autonoma>=2.0.0
# Optional dependencies
autonoma[async]  # For async support
autonoma[dev]    # Development tools

Quick Start

Basic Usage

from autonoma import Autonoma

# Initialize the client
autonoma = Autonoma(
    api_key="your-api-key",
    environment="production"
)

# Start monitoring
autonoma.start()

# Analyze code
with open("app.py", "r") as f:
    analysis = autonoma.analyze(
        file="app.py",
        content=f.read()
    )

# Get predictions
predictions = autonoma.get_predictions()

# Apply auto-fix
if predictions and predictions[0].auto_fix_available:
    result = autonoma.apply_fix(predictions[0].id)
    print(f"Fix applied: {result.success}")

Async Support

import asyncio
from autonoma import AsyncAutonoma

async def main():
    # Initialize async client
    autonoma = AsyncAutonoma(
        api_key="your-api-key",
        environment="production"
    )
    
    # Analyze multiple files concurrently
    files = ["app.py", "models.py", "views.py"]
    
    tasks = []
    for file_path in files:
        with open(file_path, "r") as f:
            task = autonoma.analyze(
                file=file_path,
                content=f.read()
            )
            tasks.append(task)
    
    # Wait for all analyses to complete
    results = await asyncio.gather(*tasks)
    
    # Process results
    for result in results:
        print(f"{result.file}: {len(result.predictions)} issues found")
    
    # Clean up
    await autonoma.close()

# Run async function
asyncio.run(main())

Django Integration

# settings.py
INSTALLED_APPS = [
    # ...
    'autonoma.contrib.django',
]

AUTONOMA = {
    'API_KEY': os.environ.get('AUTONOMA_API_KEY'),
    'ENVIRONMENT': 'production',
    'AUTO_FIX': {
        'ENABLED': True,
        'CONFIDENCE': 0.95,
    },
    'MIDDLEWARE': {
        'ENABLED': True,
        'SAMPLE_RATE': 1.0,
    }
}

# views.py
from autonoma.contrib.django import monitor_view

@monitor_view
def user_profile(request, user_id):
    # Autonoma automatically monitors this view
    user = User.objects.get(id=user_id)
    return render(request, 'profile.html', {'user': user})

# management command
python manage.py autonoma analyze
python manage.py autonoma fix --auto-approve

Flask Integration

from flask import Flask
from autonoma.contrib.flask import Autonoma

app = Flask(__name__)

# Initialize Autonoma
autonoma = Autonoma(app, api_key="your-api-key")

# Or with app factory
autonoma = Autonoma()

def create_app():
    app = Flask(__name__)
    autonoma.init_app(app, api_key="your-api-key")
    return app

# Automatic error tracking
@app.errorhandler(Exception)
def handle_error(error):
    autonoma.capture_exception(error)
    return "Internal Server Error", 500

# Monitor specific routes
@app.route('/api/users/<user_id>')
@autonoma.monitor
def get_user(user_id):
    # Route is automatically monitored
    return User.query.get_or_404(user_id).to_dict()

Configuration Options

from autonoma import Autonoma
from autonoma.config import Config

# Configuration object
config = Config(
    # Required
    api_key="your-api-key",
    
    # Environment
    environment="production",  # or "development", "staging"
    
    # API Configuration
    base_url="https://api.autonoma.dev",
    timeout=30,
    max_retries=3,
    retry_backoff=True,
    
    # Features
    auto_fix=AutoFixConfig(
        enabled=True,
        confidence_threshold=0.95,
        require_approval=False,
        exclude_patterns=["*_test.py", "test_*.py"],
        max_fixes_per_run=10
    ),
    
    # Monitoring
    monitoring=MonitoringConfig(
        errors=True,
        performance=True,
        custom_metrics=True,
        sampling_rate=1.0,  # 100% sampling
        capture_locals=True,
        sanitize_data=True
    ),
    
    # Security
    encryption=True,
    anonymize=AnonymizeConfig(
        enabled=True,
        patterns=[
            r"password\s*=\s*['"].*?['"]",
            r"api_key\s*=\s*['"].*?['"]",
            r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"  # emails
        ]
    ),
    
    # Performance
    batch_size=100,
    flush_interval=5.0,
    async_mode=True,
    thread_pool_size=4,
    
    # Logging
    log_level="INFO",
    log_format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    
    # Callbacks
    on_prediction=lambda pred: print(f"New prediction: {pred}"),
    on_fix=lambda fix: print(f"Fix applied: {fix}"),
    on_error=lambda err: logger.error(f"Autonoma error: {err}")
)

# Initialize with config
autonoma = Autonoma(config)

# Or use environment variables
# AUTONOMA_API_KEY
# AUTONOMA_ENVIRONMENT
# AUTONOMA_BASE_URL
# AUTONOMA_LOG_LEVEL
autonoma = Autonoma.from_env()

Configuration File

Load configuration from YAML or JSON:

# autonoma.yaml
api_key: ${AUTONOMA_API_KEY}
environment: production
auto_fix:
  enabled: true
  confidence_threshold: 0.95

Type Hints

Full type hint support for better IDE experience:

from autonoma import Autonoma, Prediction, Fix
from typing import List

def process_predictions(predictions: List[Prediction]) -> None:
    for pred in predictions:
        print(f"{pred.severity}: {pred.message}")

Core Methods

analyze(file, content, **kwargs)

Analyze code for potential issues, performance problems, and security vulnerabilities.

# Analyze a single file
result = autonoma.analyze(
    file="src/models/user.py",
    content=file_content,
    context={
        "framework": "django",
        "python_version": "3.9"
    }
)

# Analyze with specific rules
result = autonoma.analyze(
    file="api.py",
    content=file_content,
    rules=["security", "performance"],
    severity_threshold="medium"
)

# Batch analysis
files = [
    {"file": "app.py", "content": app_content},
    {"file": "models.py", "content": models_content}
]
results = autonoma.analyze_batch(files)

# Response structure
{
    "predictions": [
        {
            "id": "pred_123",
            "type": "security",
            "severity": "high",
            "message": "SQL injection vulnerability detected",
            "line": 45,
            "column": 12,
            "auto_fix_available": True
        }
    ],
    "metrics": {
        "total_issues": 3,
        "by_severity": {"high": 1, "medium": 2},
        "execution_time": 0.234
    }
}

get_predictions(**filters)

Retrieve predictions for your codebase with optional filtering.

# Get all predictions
predictions = autonoma.get_predictions()

# Filter by severity and type
critical_security = autonoma.get_predictions(
    severity=["critical", "high"],
    type="security",
    status="open"
)

# Filter by date and confidence
recent_high_confidence = autonoma.get_predictions(
    created_after=datetime.now() - timedelta(days=7),
    confidence_min=0.9
)

# Pagination
page = autonoma.get_predictions(
    page=1,
    per_page=50,
    order_by="severity",
    order="desc"
)

# Access results
for prediction in predictions:
    print(f"{prediction.file}:{prediction.line} - {prediction.message}")
    if prediction.auto_fix_available:
        print(f"  Auto-fix available with {prediction.fix_confidence:.0%} confidence")

apply_fix(prediction_id, **options)

Apply an auto-fix for a specific prediction with validation and rollback support.

# Apply fix with default settings
fix_result = autonoma.apply_fix("pred_123abc")

# Apply with options
fix_result = autonoma.apply_fix(
    "pred_123abc",
    dry_run=True,           # Preview without applying
    create_backup=True,     # Backup file before changes
    run_tests=True,         # Run test suite after fix
    test_command="pytest",  # Custom test command
    auto_commit=False,      # Don't auto-commit to git
    commit_message="fix: resolve SQL injection vulnerability"
)

# Handle result
if fix_result.success:
    print(f"Fix applied successfully!")
    print(f"Files changed: {fix_result.files_changed}")
    print(f"Lines modified: {fix_result.lines_modified}")
    
    # Review changes
    for change in fix_result.changes:
        print(f"  {change.file}: {change.description}")
else:
    print(f"Fix failed: {fix_result.error}")
    
    # Rollback if needed
    if fix_result.rollback_available:
        autonoma.rollback(fix_result.rollback_id)

# Batch fixes
fixes = autonoma.apply_fixes(
    prediction_ids=["pred_123", "pred_456"],
    stop_on_error=True
)

monitor(**options) / @monitor decorator

Monitor application performance and errors in real-time.

# Start monitoring
autonoma.monitor(
    capture_errors=True,
    capture_performance=True,
    capture_custom_metrics=True
)

# Using decorators
from autonoma.decorators import monitor, measure_time

@monitor
def process_payment(amount, user_id):
    # Function is automatically monitored
    # Errors are captured and reported
    return payment_gateway.charge(amount, user_id)

@measure_time
def expensive_operation():
    # Execution time is automatically tracked
    return complex_calculation()

# Custom metrics
autonoma.metric("api.requests", 1, tags={"endpoint": "/users"})
autonoma.gauge("queue.size", queue.qsize())
autonoma.histogram("response.size", len(response.content))

# Context manager for monitoring
with autonoma.monitor_context("batch_job"):
    for item in items:
        process_item(item)

# Stop monitoring
autonoma.stop_monitoring()

Smart Analysis & Intent Recognition

Smart Project Analysis

Comprehensive ML-powered project scanning with intelligent insights.

# Analyze entire project with ML insights
analysis = await autonoma.analyze_project("/path/to/project")

print(f"Project Score: {analysis['overall_score']}/100")
print(f"Tech Stack: {analysis['detected_stack']}")
print(f"Architecture: {analysis['architecture_pattern']}")
print(f"Issues Found: {len(analysis['issues'])}")
print(f"Opportunities: {analysis['improvement_opportunities']}")

# Deep scan for comprehensive analysis
deep_analysis = await autonoma.analyze_project(
    "/path/to/project",
    deep_scan=True
)

Natural Language Intent Recognition

Understand user requests and automatically map them to actions.

# Recognize intent from natural language
intent = await autonoma.recognize_intent(
    "I need to add authentication to my API with rate limiting"
)

print(f"Intent: {intent['primary_intent']}")  # 'ADD_FEATURE'
print(f"Features: {intent['requested_features']}")  # ['authentication', 'rate_limiting']
print(f"Confidence: {intent['confidence']}")  # 0.95

# With project context
intent = await autonoma.recognize_intent(
    "Optimize database queries",
    project_context={"framework": "django", "db": "postgresql"}
)

Production Readiness Verification

Comprehensive 17-category production readiness assessment.

# Verify production readiness
readiness = await autonoma.verify_production_readiness("/path/to/project")

print(f"Production Ready: {'Yes' if readiness['score'] > 80 else 'No'}")
print(f"Overall Score: {readiness['score']}/100")

# Category breakdown
for category, score in readiness['category_scores'].items():
    print(f"  {category}: {score}/100")
    
# Categories include:
# - Security, Performance, Reliability
# - Monitoring, Documentation, Testing
# - Deployment, Disaster Recovery, Compliance
# - Scalability, Dependencies, Configuration
# - Error Handling, Logging, API Design
# - Data Management, Cost Management

Anti-Pattern Detection & Auto-Fix

Detect and automatically fix 15+ common code anti-patterns.

# Detect anti-patterns
antipatterns = await autonoma.detect_antipatterns(
    "/path/to/project",
    auto_fix=True  # Automatically fix detected issues
)

print(f"Anti-patterns found: {len(antipatterns['detected'])}")
print(f"Auto-fixed: {len(antipatterns['fixed'])}")
print(f"Manual review needed: {len(antipatterns['manual_review'])}")

# Anti-patterns detected:
# - Hardcoded secrets, Missing error handling
# - Synchronous blocking, Memory leaks
# - SQL injection risks, Race conditions
# - Circular dependencies, God objects
# - Copy-paste code, Mock in production
# - Missing validation, Poor naming
# - Excessive complexity, Missing tests
# - Outdated dependencies

Intelligent Dialogue System

Adaptive questioning based on user expertise and project context.

# Start intelligent dialogue
dialogue = await autonoma.start_intelligent_dialogue(
    intent_type="build_new",
    initial_context={"project_type": "microservice"}
)

print(f"Question: {dialogue['current_question']}")
# "What are your primary business requirements for this microservice?"

# Process user response
dialogue = await autonoma.process_dialogue_response(
    session_id=dialogue['session_id'],
    user_response="High availability with 99.99% uptime"
)

# Dialogue adapts to:
# - User expertise level (beginner to expert)
# - Project complexity
# - Business requirements
# - Technical constraints

Advanced Features

Custom Rules

from autonoma.rules import Rule, RuleSet

# Define custom rule
@autonoma.rule
def no_print_statements(node, context):
    """Detect print statements in production code"""
    if isinstance(node, ast.Call):
        if getattr(node.func, 'id', None) == 'print':
            return {
                "severity": "warning",
                "message": "Remove print statement",
                "fix": lambda: ast.Pass()
            }

# Rule set
security_rules = RuleSet(
    name="security",
    rules=[
        Rule(
            id="sql-injection",
            pattern=r"query\(.*?%s.*?\)",
            message="Potential SQL injection",
            severity="critical"
        ),
        Rule(
            id="hardcoded-secret",
            pattern=r"(password|api_key)\s*=\s*['"]\w+['"]",
            message="Hardcoded secret detected",
            severity="high"
        )
    ]
)

autonoma.add_ruleset(security_rules)

Git Integration

# Pre-commit hook
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/autonoma/pre-commit
    rev: v2.0.0
    hooks:
      - id: autonoma
        args: ['--fix', '--fail-on-critical']

# Git hooks
from autonoma.git import GitIntegration

git = GitIntegration(autonoma)

# Analyze changes before commit
@git.pre_commit
def analyze_staged_files(files):
    results = autonoma.analyze_files(files)
    if results.has_critical_issues():
        return False, "Critical issues found"
    return True, None

# Auto-fix on push
@git.pre_push
def auto_fix_before_push():
    predictions = autonoma.get_predictions(
        status="open",
        auto_fix_available=True
    )
    autonoma.apply_fixes([p.id for p in predictions])

CI/CD Integration

# GitHub Actions
# .github/workflows/autonoma.yml
name: Autonoma Analysis
on: [push, pull_request]

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: '3.9'
      - run: pip install autonoma
      - run: |
          python -c "
          from autonoma import Autonoma
          from autonoma.ci import CI
          
          autonoma = Autonoma.from_env()
          ci = CI(autonoma)
          
          results = ci.analyze_changes()
          ci.comment_on_pr(results)
          
          if results.has_critical_issues():
              exit(1)
          "
        env:
          AUTONOMA_API_KEY: ${{ secrets.AUTONOMA_API_KEY }}

# Jenkins Pipeline
pipeline {
    agent any
    stages {
        stage('Autonoma Analysis') {
            steps {
                sh '''
                    pip install autonoma
                    autonoma analyze --output=json > results.json
                    autonoma fix --auto-approve --confidence=0.95
                '''
            }
        }
    }
}

Testing Integration

import pytest
from autonoma.testing import AutonomaTestCase

class TestUserAPI(AutonomaTestCase):
    """Tests with automatic Autonoma analysis"""
    
    def test_user_creation(self):
        # Test runs normally
        response = self.client.post("/users", {...})
        assert response.status_code == 201
        
        # Autonoma analyzes test code automatically
        # and reports any issues found
    
    def test_performance(self):
        with self.assert_performance(max_time=0.1):
            # This block must complete within 100ms
            expensive_operation()

# Pytest plugin
# conftest.py
pytest_plugins = ["autonoma.pytest"]

# Run with analysis
# pytest --autonoma-analyze --autonoma-fix

# Custom markers
@pytest.mark.autonoma(
    analyze=True,
    fix=True,
    rules=["security", "performance"]
)
def test_critical_function():
    # This test gets extra analysis
    pass

Command Line Interface

# Installation includes CLI tool
$ autonoma --help

# Initialize project
$ autonoma init
✓ Created autonoma.yaml configuration file
✓ Added .autonoma to .gitignore

# Analyze current directory
$ autonoma analyze
Analyzing 45 Python files...
Found 12 issues (2 critical, 5 high, 5 medium)

# Analyze specific files
$ autonoma analyze src/ tests/ --severity=high

# View predictions
$ autonoma predictions
┌─────────────┬──────────┬──────────┬─────────────────────────┐
│ ID          │ Severity │ Type     │ Message                 │
├─────────────┼──────────┼──────────┼─────────────────────────┤
│ pred_abc123 │ Critical │ Security │ SQL injection risk      │
│ pred_def456 │ High     │ Perf     │ N+1 query detected      │
└─────────────┴──────────┴──────────┴─────────────────────────┘

# Apply fixes
$ autonoma fix pred_abc123
✓ Fix applied successfully
  Changed: models.py (1 line modified)

# Auto-fix all high confidence issues
$ autonoma fix --auto --confidence=0.95
✓ Applied 8 fixes automatically

# Monitor in real-time
$ autonoma monitor
Monitoring application...
[2024-01-15 10:30:45] Error detected: ZeroDivisionError in calc.py:45
[2024-01-15 10:30:46] Performance issue: Slow query (523ms) in db.py:122

# Generate report
$ autonoma report --format=html --output=report.html
✓ Report generated: report.html

Pro tip: Add autonoma analyze to your pre-commit hooks for immediate feedback on code quality issues.

Error Handling

from autonoma import Autonoma
from autonoma.exceptions import (
    AutonomaError,
    APIError,
    ConfigurationError,
    RateLimitError,
    ValidationError
)

try:
    result = autonoma.analyze(file="app.py", content=content)
except RateLimitError as e:
    print(f"Rate limit exceeded. Retry after {e.retry_after} seconds")
    time.sleep(e.retry_after)
    result = autonoma.analyze(file="app.py", content=content)
except APIError as e:
    if e.status_code == 401:
        print("Invalid API key")
    elif e.status_code == 403:
        print("Access forbidden")
    else:
        print(f"API error: {e.message}")
except ValidationError as e:
    print(f"Invalid input: {e.field} - {e.message}")
    for error in e.errors:
        print(f"  - {error['field']}: {error['message']}")
except AutonomaError as e:
    # Generic Autonoma error
    print(f"Autonoma error: {e}")
    
# Using context manager for automatic cleanup
with Autonoma(api_key="key") as autonoma:
    autonoma.analyze(file="app.py", content=content)
    # Connection automatically closed on exit

# Error callbacks
def handle_error(error):
    logger.error(f"Autonoma error: {error}")
    # Send to error tracking service
    sentry.capture_exception(error)

autonoma = Autonoma(
    api_key="key",
    on_error=handle_error
)

Best Practices

Security

  • • Store API keys in environment variables
  • • Use python-dotenv for local development
  • • Enable data anonymization for sensitive code
  • • Regularly rotate API keys

Performance

  • • Use async client for concurrent operations
  • • Batch analyze multiple files together
  • • Enable caching for repeated analyses
  • • Use sampling in development (0.1 rate)

Workflow

  • • Add to pre-commit hooks
  • • Run in CI/CD pipelines
  • • Enable auto-fix for high confidence issues
  • • Review fixes before production deployment

Configuration

  • • Use configuration files for consistency
  • • Set appropriate confidence thresholds
  • • Customize rules for your coding standards
  • • Enable debug logging during development

Ready to Get Started?

Install the SDK and start improving your Python code quality