Developer Guide

Complete setup, API reference, custom agents, and production deployment

Getting API Keys

Required: AVIP needs API keys for full functionality. Without them, features are limited.

G

Google Gemini (Recommended)

Free tier: 15 req/min, 1500 req/day

  1. Go to Google AI Studio
  2. Click "Create API Key"
  3. Copy the key
GEMINI_API_KEY=your-key-here

NVD API Key (Optional)

Increases rate limit from 5 to 50 req/30s

  1. Visit NVD API Key Request
  2. Enter work email (.gov/.edu preferred)
  3. Check email and activate key
NVD_API_KEY=your-key-here
O

OpenAI (Alternative)

GPT-4o or GPT-4o-mini for LLM features

  1. Go to OpenAI Platform
  2. Click "Create new secret key"
  3. Set permissions and copy
OPENAI_API_KEY=sk-...
A

Anthropic Claude (Alternative)

Sonnet or Opus for reasoning tasks

  1. Visit Anthropic Console
  2. Create an API key
  3. Copy and save securely
ANTHROPIC_API_KEY=sk-ant-...

Quick Setup

Windows (One-Click)

1
Clone repogit clone or download ZIP
2
Create .envCopy .env.example and add API keys
3
Double-click run.batEverything starts automatically
4
Open browserNavigate to http://localhost:5173

Linux / Mac / Git Bash

Terminal
git clone https://github.com/Purushothaman-natarajan/Exploit2Patch.git
cd Exploit2Patch

# Create .env with your API keys
echo "GEMINI_API_KEY=your-key" > .env

# Run the launcher
chmod +x run.sh
./run.sh

Environment Configuration

Create a .env file in the project root:

.env
# Required for LLM features
GEMINI_API_KEY=AIza...Get from: https://aistudio.google.com/apikey

# Optional: Increases NVD rate limit from 5 to 50 req/30s
NVD_API_KEY=your-nvd-key-here

# Alternative LLM providers (optional)
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...

# Security (optional)
JWT_SECRET=your-secret-key
CORS_ORIGINS=https://your-domain.com

Note: Without GEMINI_API_KEY, the pipeline runs but LLM features (Playbook generation) are disabled. NVD queries are rate-limited to 5 per 30 seconds.

API Reference

Endpoints

EndpointMethodDescription
/healthGETHealth check, config, agent status
/wsWebSocketLive event streaming
/runsGETList all pipeline runs
/runs/{id}GETGet run details and files
/runs/{id}/fileGETRead file content (query: path=)
/agent/researchPOSTRun research agent only
/agent/ingest/{id}POSTGenerate ingestion scripts
/agent/remediate/{id}POSTCreate remediation plans
/agent/playbook/{id}POSTGenerate final playbook
/pipeline/runPOSTRun full 4-agent pipeline
/pipeline/batchPOSTProcess multiple CVEs

Request Examples

bash
# Health check
curl http://localhost:8000/health

# Research a CVE
curl -X POST http://localhost:8000/agent/research \
  -H "Content-Type: application/json" \
  -d '{"cve_id": "CVE-2024-4577"}'

# Full pipeline (Windows x64)
curl -X POST http://localhost:8000/pipeline/run \
  -H "Content-Type: application/json" \
  -d '{
    "cve_id": "CVE-2024-4577",
    "os_type": "windows",
    "architecture": "x64"
  }'

# By product (auto-searches NVD)
curl -X POST http://localhost:8000/pipeline/run \
  -H "Content-Type: application/json" \
  -d '{
    "product": "Notepad++",
    "os_type": "windows"
  }'

# Batch process multiple CVEs
curl -X POST http://localhost:8000/pipeline/batch \
  -H "Content-Type: application/json" \
  -d '{
    "cve_ids": ["CVE-2024-4577", "CVE-2024-3001"],
    "os_type": "windows"
  }'

# Read a generated file
curl "http://localhost:8000/runs/20260326_120000_abc123/file?path=research/research.json"

WebSocket Event Streaming

Connect to ws://localhost:8000/ws for real-time pipeline events:

Event Types

EventSourceData
pipeline_startpipelinerun_id, cve
pipeline_endpipelinerun_id, tokens_used
agent_start*_agentrun_id, cve, os, product
agent_end*_agentrun_id, cves, scripts, plans
tool_call*_agenttool, action, search, cve
tool_result*_agenttool, count, validated, cves_found
token_usagesystemprovider, tokens, total

JavaScript Client Example

javascript
const ws = new WebSocket('ws://localhost:8000/ws');

ws.onopen = () => console.log('Connected to event stream');
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  if (data.type === 'backlog') {
    console.log('History:', data.events.length, 'events');
    data.events.forEach(handleEvent);
  } else {
    handleEvent(data);
  }
};

function handleEvent(ev) {
  console.log(`${ev.event_type} from ${ev.source}:`, ev.data);
  
  if (ev.event_type === 'agent_start') {
    updateUI('Agent started:', ev.data.cve);
  }
  if (ev.event_type === 'tool_result') {
    updateProgress(ev.data);
  }
  if (ev.event_type === 'pipeline_end') {
    showResults(ev.data);
  }
}

Building Custom Agents

Extend AVIP with your own agents. Here's a complete example:

1. Create Agent File

backend/src/agents/my_agent.py
from __future__ import annotations
from typing import Dict, Any
from src.events.bus import EventType, Event

class MyCustomAgent:
    def __init__(self):
        self.name = "my_custom_agent"

    async def analyze(self, data: Dict[str, Any], emit_fn) -> Dict[str, Any]:
        # Emit start event
        await emit_fn(self.name, EventType.AGENT_START, {
            "task": data.get("task"),
            "run_id": data.get("run_id")
        })
        
        # Do work...
        await emit_fn(self.name, EventType.TOOL_CALL, {
            "tool": "my_tool",
            "action": "analyze"
        })
        
        # Emit result
        result = {"analysis": "completed", "items": 42}
        await emit_fn(self.name, EventType.TOOL_RESULT, result)
        
        # Emit end
        await emit_fn(self.name, EventType.AGENT_END, {
            "run_id": data.get("run_id"),
            "status": "success"
        })
        
        return result

2. Register Endpoint

backend/src/api/main.py
# Import your agent
from src.agents.my_agent import MyCustomAgent

# Initialize agent
_my_agent = MyCustomAgent()

# Add endpoint
@app.post("/agent/custom")
async def custom_analysis(data: CustomInput):
    async def _emit(source, etype, payload):
        await event_bus.emit(Event(
            event_type=etype,
            source=source,
            data=payload
        ))
    
    result = await _my_agent.analyze(
        data={"task": data.task, "run_id": _make_run_id()},
        emit_fn=_emit
    )
    return {"status": "ok", "result": result}

Configuration Reference

Settings in backend/src/config.py:

SettingDefaultDescription
llm.providergeminiLLM: gemini, openai, anthropic, ollama
llm.modelgemini-1.5-flashModel name
llm.temperature0.3Response creativity (0-1)
llm.max_tokens2048Max response length
url_trust.min_score30Minimum trust score threshold
url_trust.blockedblogs, forumsBlocked domain patterns
nvd.max_results20Max CVEs from NVD search
nvd.rate_limit5Requests per 30 seconds
execution.default_oswindowsDefault OS type
execution.default_archx64Default architecture

Production Deployment

Docker

Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY backend/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY backend/ .
ENV PYTHONPATH=/app
EXPOSE 8000
CMD ["uvicorn", "src.api.main:app", "--host", "0.0.0.0"]

Environment Variables for Production

.env
# Production keys (use secrets management!)
GEMINI_API_KEY=production-key
NVD_API_KEY=production-nvd-key

# Security
JWT_SECRET=secure-random-secret
ALLOWED_ORIGINS=https://app.your-domain.com

# Performance
UVICORN_WORKERS=4
MAX_CONCURRENT_PIPELINES=10

# Storage
RUNS_DIR=/data/avip/runs

Kubernetes

deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: avip-backend
spec:
  replicas: 3
  selector:
    matchLabels:
      app: avip-backend
  template:
    spec:
      containers:
      - name: backend
        image: your-registry/avip:latest
        ports:
        - containerPort: 8000
        env:
        - name: GEMINI_API_KEY
          valueFrom:
            secretKeyRef:
              name: avip-secrets
              key: gemini-api-key
        resources:
          requests:
            memory: "512Mi"
            cpu: "250m"
          limits:
            memory: "1Gi"
            cpu: "1000m"

Troubleshooting

Backend won't start

  • Check port 8000 is not in use
  • Verify Python 3.11+ installed
  • Run: pip install -r requirements.txt
  • Check .env file exists

Pipeline fails / No results

  • Verify GEMINI_API_KEY is set
  • Check API key is valid and has quota
  • NVD may be rate-limited - wait 30s
  • Check logs for specific errors

WebSocket not connecting

  • Ensure backend is running
  • Check browser console for errors
  • Verify no firewall blocking WebSocket
  • CORS may need configuration

PDF not generating

  • Install reportlab: pip install reportlab
  • Check write permissions for runs/ folder
  • Verify research data is valid JSON

Quick Reference

Start Backend:   cd backend && python -m uvicorn src.api.main:app --port 8000
Start Frontend:  cd frontend && python -m http.server 5173
Run Tests:       cd backend && python -m pytest tests/
View Logs:       Check terminal output or browser console
Stop:            Ctrl+C or taskkill /F /IM python.exe
Reset:           Delete runs/ folder to clear history