Guides

AI Agent Integration

Learn how to integrate CommitKey with AI agents and automated workflows

This guide shows you how to integrate CommitKey with AI agents and automated development workflows.

Overview

CommitKey is designed specifically for AI agent workflows, providing:

  • Programmatic Access: Complete Git operations via API
  • Automated Workflows: Seamless integration with AI development pipelines
  • Secure Environments: Isolated repositories for AI agents
  • Scalable Infrastructure: Handle multiple concurrent AI agents

Basic Integration

Setting Up Your AI Agent

import requests
import os

class CommitKeyAgent:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.commitkey.dev/v1"
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
    
    def create_repository(self, name, description=""):
        """Create a new repository for the AI agent"""
        response = requests.post(
            f"{self.base_url}/repositories",
            headers=self.headers,
            json={
                "name": name,
                "description": description,
                "private": True
            }
        )
        return response.json()
    
    def add_file(self, repo_name, path, content, message):
        """Add or update a file in the repository"""
        response = requests.post(
            f"{self.base_url}/repositories/{repo_name}/files",
            headers=self.headers,
            json={
                "path": path,
                "content": content,
                "message": message,
                "author": {
                    "name": "AI Agent",
                    "email": "agent@commitkey.dev"
                }
            }
        )
        return response.json()

JavaScript/TypeScript Integration

class CommitKeyAgent {
  private apiKey: string;
  private baseUrl: string = "https://api.commitkey.dev/v1";

  constructor(apiKey: string) {
    this.apiKey = apiKey;
  }

  private async request(endpoint: string, options: RequestInit = {}) {
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      ...options,
      headers: {
        "Authorization": `Bearer ${this.apiKey}`,
        "Content-Type": "application/json",
        ...options.headers,
      },
    });

    if (!response.ok) {
      throw new Error(`API request failed: ${response.statusText}`);
    }

    return response.json();
  }

  async createRepository(name: string, description: string = "") {
    return this.request("/repositories", {
      method: "POST",
      body: JSON.stringify({
        name,
        description,
        private: true,
      }),
    });
  }

  async addFile(repoName: string, path: string, content: string, message: string) {
    return this.request(`/repositories/${repoName}/files`, {
      method: "POST",
      body: JSON.stringify({
        path,
        content,
        message,
        author: {
          name: "AI Agent",
          email: "agent@commitkey.dev",
        },
      }),
    });
  }
}

Workflow Patterns

Code Generation Workflow

def generate_code_workflow(agent, project_name, requirements):
    """Complete workflow for AI code generation"""
    
    # 1. Create repository
    repo = agent.create_repository(
        name=project_name,
        description=f"AI-generated project: {requirements}"
    )
    
    # 2. Generate project structure
    files = generate_project_structure(requirements)
    
    # 3. Commit all files
    for file_path, content in files.items():
        agent.add_file(
            repo_name=project_name,
            path=file_path,
            content=content,
            message=f"Add {file_path}"
        )
    
    return repo

Iterative Development

def iterative_development(agent, repo_name, iterations):
    """Iterative development with multiple commits"""
    
    for i, iteration in enumerate(iterations):
        # Generate code for this iteration
        code = generate_code(iteration)
        
        # Commit the changes
        agent.add_file(
            repo_name=repo_name,
            path=f"src/iteration_{i}.py",
            content=code,
            message=f"Implement iteration {i}: {iteration.description}"
        )
        
        # Optional: Create a branch for major changes
        if iteration.major_change:
            agent.create_branch(
                repo_name=repo_name,
                branch_name=f"feature/iteration-{i}",
                base="main"
            )

Advanced Features

Branch Management for AI Agents

def create_feature_branch(agent, repo_name, feature_name):
    """Create a feature branch for AI development"""
    return agent.request(
        "POST",
        f"/repositories/{repo_name}/branches",
        json={
            "name": f"ai-feature/{feature_name}",
            "base": "main"
        }
    )

def merge_branch(agent, repo_name, branch_name):
    """Merge a feature branch back to main"""
    return agent.request(
        "POST",
        f"/repositories/{repo_name}/merge",
        json={
            "source": branch_name,
            "target": "main",
            "message": f"Merge AI-generated feature: {branch_name}"
        }
    )

Webhook Integration

def setup_webhooks(agent, repo_name, webhook_url):
    """Set up webhooks for real-time notifications"""
    return agent.request(
        "POST",
        f"/repositories/{repo_name}/webhooks",
        json={
            "url": webhook_url,
            "events": ["push", "pull_request", "commit"]
        }
    )

Error Handling and Retry Logic

import time
import random

def robust_api_call(agent, operation, max_retries=3):
    """Robust API call with exponential backoff"""
    for attempt in range(max_retries):
        try:
            return operation()
        except requests.exceptions.RequestException as e:
            if attempt == max_retries - 1:
                raise e
            
            # Exponential backoff with jitter
            delay = (2 ** attempt) + random.uniform(0, 1)
            time.sleep(delay)
    
    return None

Security Best Practices

API Key Management

import os
from cryptography.fernet import Fernet

class SecureCommitKeyAgent(CommitKeyAgent):
    def __init__(self, encrypted_api_key, encryption_key):
        # Decrypt API key
        f = Fernet(encryption_key)
        api_key = f.decrypt(encrypted_api_key.encode()).decode()
        super().__init__(api_key)
    
    @classmethod
    def from_env(cls):
        """Create agent from environment variables"""
        api_key = os.getenv("COMMITKEY_API_KEY")
        if not api_key:
            raise ValueError("COMMITKEY_API_KEY environment variable not set")
        return cls(api_key)

Repository Isolation

def create_isolated_repo(agent, agent_id, project_name):
    """Create an isolated repository for a specific AI agent"""
    repo_name = f"agent-{agent_id}-{project_name}"
    
    return agent.create_repository(
        name=repo_name,
        description=f"Isolated repository for agent {agent_id}",
        private=True
    )

Monitoring and Logging

import logging

class MonitoredCommitKeyAgent(CommitKeyAgent):
    def __init__(self, api_key, agent_id):
        super().__init__(api_key)
        self.agent_id = agent_id
        self.logger = logging.getLogger(f"commitkey-agent-{agent_id}")
    
    def add_file(self, repo_name, path, content, message):
        self.logger.info(f"Adding file {path} to {repo_name}")
        
        try:
            result = super().add_file(repo_name, path, content, message)
            self.logger.info(f"Successfully added file {path}")
            return result
        except Exception as e:
            self.logger.error(f"Failed to add file {path}: {e}")
            raise

Example: Complete AI Development Workflow

def complete_ai_workflow():
    """Complete example of AI agent using CommitKey"""
    
    # Initialize agent
    agent = CommitKeyAgent.from_env()
    
    # Create project
    project_name = "ai-generated-web-app"
    repo = agent.create_repository(
        name=project_name,
        description="A web application generated by AI"
    )
    
    # Generate and commit files
    files = {
        "package.json": generate_package_json(),
        "src/index.js": generate_main_js(),
        "src/styles.css": generate_css(),
        "README.md": generate_readme()
    }
    
    for path, content in files.items():
        agent.add_file(
            repo_name=project_name,
            path=path,
            content=content,
            message=f"Add {path}"
        )
    
    # Create a feature branch for enhancements
    agent.create_branch(
        repo_name=project_name,
        branch_name="feature/enhancements",
        base="main"
    )
    
    # Add enhancements
    enhancements = generate_enhancements()
    for enhancement in enhancements:
        agent.add_file(
            repo_name=project_name,
            path=enhancement.path,
            content=enhancement.content,
            message=enhancement.message
        )
    
    return repo

Next Steps

Search Documentation

Search through pages and sections