Skip to main content
Archived

This project has been archived by its maintainers, and is no longer receiving any updates.

socrates-api

REST API server for the Socrates AI platform. Provides a complete API for programmatic access to Socrates functionality.

Installation

pip install socrates-api

Quick Start

1. Set Environment Variables

export ANTHROPIC_API_KEY="your-api-key-here"
export SOCRATES_DATA_DIR="~/.socrates"  # Optional
export SOCRATES_API_HOST="0.0.0.0"      # Optional, default: 127.0.0.1
export SOCRATES_API_PORT="8000"         # Optional, default: 8000

2. Run the Server

socrates-api

Or use Python directly:

python -m socrates_api.main

3. Access the API

  • Swagger Documentation: http://localhost:8000/docs
  • ReDoc Documentation: http://localhost:8000/redoc
  • Health Check: http://localhost:8000/health

API Endpoints

System Management

  • GET /health - Health check
  • POST /initialize - Initialize API with configuration
  • GET /info - Get system information

Projects

  • POST /projects - Create a new project
  • GET /projects - List projects (optionally filtered by owner)

Socratic Questions

  • POST /projects/{project_id}/question - Get a Socratic question
  • POST /projects/{project_id}/response - Process user response

Code Generation

  • POST /code/generate - Generate code for a project

Usage Examples

Initialize the API

curl -X POST http://localhost:8000/initialize \
  -H "Content-Type: application/json" \
  -d '{"api_key": "sk-ant-..."}'

Create a Project

curl -X POST http://localhost:8000/projects \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Python API Development",
    "owner": "alice",
    "description": "Building REST APIs with FastAPI"
  }'

List Projects

curl http://localhost:8000/projects

Ask a Socratic Question

curl -X POST http://localhost:8000/projects/proj_abc123/question \
  -H "Content-Type: application/json" \
  -d '{
    "topic": "REST API design",
    "difficulty_level": "intermediate"
  }'

Process a Response

curl -X POST http://localhost:8000/projects/proj_abc123/response \
  -H "Content-Type: application/json" \
  -d '{
    "question_id": "q_xyz789",
    "user_response": "REST APIs should follow resource-oriented design principles...",
    "project_id": "proj_abc123"
  }'

Generate Code

curl -X POST http://localhost:8000/code/generate \
  -H "Content-Type: application/json" \
  -d '{
    "project_id": "proj_abc123",
    "specification": "Create a FastAPI endpoint for user registration",
    "language": "python"
  }'

Python Client Example

import requests
import json

BASE_URL = "http://localhost:8000"

# Initialize
resp = requests.post(f"{BASE_URL}/initialize", json={
    "api_key": "sk-ant-..."
})
print(resp.json())

# Create project
resp = requests.post(f"{BASE_URL}/projects", json={
    "name": "My Project",
    "owner": "alice",
    "description": "Learning FastAPI"
})
project = resp.json()
project_id = project["project_id"]

# Get a question
resp = requests.post(f"{BASE_URL}/projects/{project_id}/question", json={
    "topic": "FastAPI basics",
    "difficulty_level": "beginner"
})
question = resp.json()
print(f"Question: {question['question']}")

# Process response
resp = requests.post(f"{BASE_URL}/projects/{project_id}/response", json={
    "question_id": question["question_id"],
    "user_response": "FastAPI is a modern Python web framework...",
    "project_id": project_id
})
feedback = resp.json()
print(f"Feedback: {feedback['feedback']}")

Async Integration Example

The API is built with FastAPI and uses asyncio internally. For high-throughput scenarios:

import asyncio
import httpx

async def main():
    async with httpx.AsyncClient() as client:
        # Initialize
        resp = await client.post("http://localhost:8000/initialize", json={
            "api_key": "sk-ant-..."
        })
        print(resp.json())

        # Create multiple projects concurrently
        tasks = [
            client.post("http://localhost:8000/projects", json={
                "name": f"Project {i}",
                "owner": "alice"
            })
            for i in range(5)
        ]

        results = await asyncio.gather(*tasks)
        for r in results:
            print(r.json())

asyncio.run(main())

Event Integration

The API automatically registers event listeners with the Socrates library. Events are logged and can be monitored via the logging system:

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("socrates_api.main")

# API will log events like:
# [Event] PROJECT_CREATED: {'project_id': 'proj_abc123', ...}
# [Event] CODE_GENERATED: {'lines': 150, ...}
# [Event] AGENT_ERROR: {'agent_name': 'code_generator', ...}

Configuration

The API respects these environment variables:

Variable Default Description
ANTHROPIC_API_KEY None Claude API key (required)
SOCRATES_DATA_DIR ~/.socrates Directory for storing data
SOCRATES_API_HOST 127.0.0.1 Server host
SOCRATES_API_PORT 8000 Server port
SOCRATES_API_RELOAD false Enable auto-reload in development

Error Handling

The API returns structured error responses:

{
  "error": "ProjectNotFoundError",
  "message": "Project 'proj_abc123' not found",
  "error_code": "PROJECT_NOT_FOUND",
  "details": {"project_id": "proj_abc123"}
}

All Socrates library errors are caught and returned with appropriate HTTP status codes.

Deployment

Using Gunicorn (Production)

pip install gunicorn
gunicorn -w 4 -k uvicorn.workers.UvicornWorker socrates_api.main:app

Using Docker

FROM python:3.11-slim

WORKDIR /app

RUN pip install socrates-api

ENV SOCRATES_API_HOST=0.0.0.0

CMD ["socrates-api"]
docker build -t socrates-api .
docker run -e ANTHROPIC_API_KEY="sk-ant-..." -p 8000:8000 socrates-api

Using Docker Compose

version: '3.8'

services:
  socrates-api:
    build: .
    ports:
      - "8000:8000"
    environment:
      ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY}
      SOCRATES_DATA_DIR: /data
    volumes:
      - socrates_data:/data

volumes:
  socrates_data:

Development

Setup

git clone https://github.com/Nireus79/Socrates
cd socrates-api
pip install -e ".[dev]"

Run Tests

pytest tests/ -v --cov=socrates_api

Run in Development Mode

export SOCRATES_API_RELOAD=true
socrates-api

API Response Examples

Successful Project Creation

{
  "project_id": "proj_abc123",
  "name": "Python API Development",
  "owner": "alice",
  "description": "Building REST APIs with FastAPI",
  "phase": "active",
  "created_at": "2025-12-04T10:00:00Z",
  "updated_at": "2025-12-04T10:30:00Z",
  "is_archived": false
}

Successful Question Generation

{
  "question_id": "q_xyz789",
  "question": "What are the main principles of RESTful API design?",
  "context": "You are designing an API for a tutoring system",
  "hints": [
    "Think about resource-oriented design",
    "Consider HTTP methods and status codes"
  ]
}

Successful Code Generation

{
  "code": "@app.post('/api/users/register')\nasync def register_user(user: User):\n    # Implementation here",
  "explanation": "This endpoint handles user registration using FastAPI...",
  "language": "python",
  "token_usage": {
    "input_tokens": 150,
    "output_tokens": 200,
    "total_tokens": 350
  }
}

Architecture

The API is built on three layers:

  1. FastAPI Application (main.py) - HTTP request handling, routing, and middleware
  2. Pydantic Models (models.py) - Request/response validation and serialization
  3. Socrates Library - Business logic via socrates package

Event flow:

HTTP Request → FastAPI Route → Socrates Library → Event Emission → HTTP Response
                                      ↓
                              Event Listeners (Logging)

Monitoring

The API emits events for all significant operations. Monitor them via logging:

import logging
logging.basicConfig(level=logging.INFO)

# All events will be logged like:
# [Event] PROJECT_CREATED: {...}
# [Event] AGENT_COMPLETE: {...}
# [Event] TOKEN_USAGE: {...}

Or set up custom event listeners by extending the API:

def setup_monitoring(orchestrator):
    def on_token_usage(event_type, data):
        # Send to monitoring system
        send_metrics(data)

    orchestrator.event_emitter.on(socrates.EventType.TOKEN_USAGE, on_token_usage)

Support

For issues, feature requests, or contributions, visit:

License

MIT

Metadata

Release files for socrates-core-api 0.5.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for socrates-core-api 0.5.6
File Size Uploaded
socrates_core_api-0.5.6.tar.gz 234.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for socrates-core-api 0.5.6
File Interpreter ABI Platform
socrates_core_api-0.5.6-py3-none-any.whl Python 3 none any Details

Total release size: 493.9 kB

Release files / socrates_core_api-0.5.6.tar.gz

Download URL socrates_core_api-0.5.6.tar.gz
Size 234.7 kB
Tags Source
SHA-256 checksum
How to use checksums
091fd150b3af558071ff3f8c8093fa53beb954cd2d762ebeee8f5a7388a315cf
BLAKE2b-256 checksum
How to use checksums
ef192be184b19c4939c35fc2881c7f0c37f1fb4868ce470106b4775c5261d4a4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3

Release files / socrates_core_api-0.5.6-py3-none-any.whl

Download URL socrates_core_api-0.5.6-py3-none-any.whl
Size 259.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7c860d818bfa552d37fca3d7348ed566a0e02eaffb4213a92a0f52bd891f9596
BLAKE2b-256 checksum
How to use checksums
bafdc821ad8ace88a74b8e08a0526cb6683ffff70d2922eff74b8517abdb36da
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.3
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page