Skip to content

Latest commit

 

History

History
311 lines (232 loc) · 5.51 KB

File metadata and controls

311 lines (232 loc) · 5.51 KB

API Guide

REST API documentation for Perpendicularity web service.


🌐 Overview

The Perpendicularity API is a FastAPI application providing:

  • REST endpoints for chat, configuration, health checks
  • Server-Sent Events (SSE) for real-time streaming
  • CORS support for web development
  • Auto-generated docs at /docs

Base URL: http://localhost:8000


🚀 Quick Start

Start Server

perpendicularity api
# Access: http://localhost:8000
# Docs: http://localhost:8000/docs

Test API

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

# Get configuration
curl http://localhost:8000/api/config

# Chat (non-streaming)
curl -X POST http://localhost:8000/api/chat \
  -H "Content-Type: application/json" \
  -d '{
    "question": "What is aspirin?",
    "agent_type": "langgraph",
    "model": "gemini",
    "stream": false
  }'

📡 Endpoints

GET /

Frontend homepage (serves React app).

Response: HTML


GET /api/health

Health check endpoint.

Response:

{
  "status": "healthy",
  "service": "perpendicularity-api"
}

GET /api/config

Get available models, agents, and prompts.

Response:

{
  "available_models": ["gemini", "claude", "ollama_qwen14b", ...],
  "default_model": "ollama_qwen14b",
  "agent_types": ["langgraph", "react"],
  "mcp_servers": ["genomic_ops", "txgemma"],
  "available_prompts": ["default", "conservative", "exploratory", "genomics"]
}

POST /api/chat

Submit a question to the agent.

Request Body:

{
  "question": "What is aspirin?",
  "agent_type": "langgraph",  // Optional, default: "langgraph"
  "model_name": "gemini",      // Optional, default: from config
  "max_steps": 5,              // Optional, default: 5
  "stream": true               // Optional, default: true
}

Response (stream=false):

{
  "answer": "Aspirin is acetylsalicylic acid...",
  "agent_type": "langgraph",
  "model_name": "gemini"
}

Response (stream=true): Server-Sent Events (see Streaming section)


🌊 Streaming API

When stream: true, the API returns Server-Sent Events (SSE).

Event Types

Status Event:

data: {"type":"status","message":"Connecting to agent..."}

Step Event (ReAct):

data: {
  "type":"step",
  "step_num":1,
  "max_steps":5,
  "thought":"I need to...",
  "action":"tool_call(...)",
  "observation":"Result..."
}

Recursion Event (LangGraph):

data: {
  "type":"recursion",
  "recursion_num":1,
  "thought":"I need to...",
  "action":"tool_call(...)",
  "observation":"Result..."
}

Answer Event:

data: {"type":"answer","content":"Aspirin is..."}

Done Event:

data: {"type":"done"}

Error Event:

data: {"type":"error","message":"Error description"}

JavaScript Client Example

const eventSource = new EventSource('/api/chat?' + new URLSearchParams({
  question: "What is aspirin?",
  stream: "true"
}));

eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  switch(data.type) {
    case 'status':
      console.log('Status:', data.message);
      break;
    case 'step':
    case 'recursion':
      console.log('Step:', data.thought);
      break;
    case 'answer':
      console.log('Answer:', data.content);
      eventSource.close();
      break;
    case 'error':
      console.error('Error:', data.message);
      eventSource.close();
      break;
  }
};

🔧 Server Configuration

Command-Line Options

perpendicularity api \
  --host 0.0.0.0 \
  --port 8000 \
  --workers 4 \
  --reload \
  --log-level info \
  --config config/agent_config.yaml

Environment Variables

# Config file path
export PERPENDICULARITY_CONFIG="/path/to/config.yaml"

# API keys (for cloud models)
export GOOGLE_API_KEY="your-key"
export ANTHROPIC_API_KEY="your-key"

perpendicularity api

🌍 CORS Configuration

CORS is pre-configured for development:

# api/main.py
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:5173",  # Vite
        "http://localhost:3000",  # Alternative
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

For production: Update allow_origins in api/main.py.


📊 Interactive API Docs

FastAPI provides automatic API documentation:

Swagger UI: http://localhost:8000/docs

  • Interactive testing
  • Try endpoints directly in browser
  • See request/response schemas

ReDoc: http://localhost:8000/redoc

  • Alternative documentation format
  • Better for reading

🐛 Troubleshooting

Port Already in Use

# Find process using port 8000
lsof -i :8000

# Use different port
perpendicularity api --port 3000

CORS Errors

Add your origin to allow_origins in api/main.py:

allow_origins=[
    "http://localhost:5173",
    "http://your-domain.com",  # Add this
],

Streaming Not Working

# Check SSE support in browser console
# Modern browsers support SSE natively

# Test with curl
curl -N http://localhost:8000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"question":"test","stream":true}'

📚 See Also

For questions, see Troubleshooting or open an issue.