-CHAT_COMPLETIONS_API_VERSION=2024-05-01-preview
-```
-
-### High-Security Setup
-
-```bash
-# .env
-UPSTREAM_BASE_URL=https://api.openai.com/v1
-UPSTREAM_API_KEY=sk-...
-ADMIN_PASSWORD=very-long-secure-password-here
-CORS_ORIGINS=https://myapp.com,https://app.myapp.com
-TOR_PROXY_URL=socks5://tor:9050
-LOG_LEVEL=WARNING
-```
-
-### Public Node Configuration
-
-```bash
-# .env
-NAME=Lightning AI Gateway
-DESCRIPTION=Fast and reliable AI API access with Bitcoin payments
-NPUB=npub1abcd...
-HTTP_URL=https://api.lightning-ai.com
-ONION_URL=http://lightningai.onion
-CASHU_MINTS=https://mint1.com,https://mint2.com
-```
-
-## Pricing
-
-- Default: pricing comes from your `models.json`.
-- Force fixed per-request pricing: set `FIXED_PRICING=true` and `FIXED_COST_PER_REQUEST`.
-- Optional token overrides when using model pricing: set
- `FIXED_PER_1K_INPUT_TOKENS` and/or `FIXED_PER_1K_OUTPUT_TOKENS`.
-- Legacy envs are still accepted and mapped automatically:
- `MODEL_BASED_PRICING` → `!FIXED_PRICING`, `COST_PER_REQUEST` → `FIXED_COST_PER_REQUEST`,
- `COST_PER_1K_*` → `FIXED_PER_1K_*`.
-
-Example fixed pricing:
-
-```bash
-FIXED_PRICING=true
-FIXED_COST_PER_REQUEST=10
-```
-
-## Custom Models Configuration
-
-Create a `models.json` file:
-
-```json
-{
- "models": [
- {
- "id": "gpt-4",
- "name": "GPT-4",
- "pricing": {
- "prompt": "0.00003",
- "completion": "0.00006",
- "request": "0"
- }
- },
- {
- "id": "gpt-3.5-turbo",
- "name": "GPT-3.5 Turbo",
- "pricing": {
- "prompt": "0.0000015",
- "completion": "0.000002",
- "request": "0"
- }
- }
- ]
-}
-```
-
-## Security Best Practices
-
-### Admin Password
-
-Generate a strong password:
-
-```bash
-openssl rand -base64 32
-```
-
-### API Keys
-
-- Rotate upstream API keys regularly
-- Use read-only keys when possible
-- Monitor key usage
-
-### Network Security
-
-- Restrict CORS origins in production
-- Use HTTPS for public endpoints
-- Enable Tor for anonymity
-
-### Database Security
-
-- Regular backups
-- Encrypted storage volumes
-- Restricted file permissions
-
-## Troubleshooting
-
-### Check Current Configuration
-
-```bash
-# View all environment variables
-docker exec routstr env | sort
-
-# Test configuration
-curl http://localhost:8000/v1/info
-```
-
-### Common Issues
-
-**Missing Upstream URL**
-
-```
-ERROR: UPSTREAM_BASE_URL not set
-Solution: Set UPSTREAM_BASE_URL in .env
-```
-
-**Invalid Cashu Mint**
-
-```
-ERROR: Failed to connect to mint
-Solution: Verify CASHU_MINTS URLs are accessible
-```
-
-**Database Errors**
-
-```
-ERROR: Database connection failed
-Solution: Check DATABASE_URL and file permissions
-```
-
-## Advanced Configuration
-
-### Multiple Mints
-
-Configure fallback mints:
-
-```bash
-CASHU_MINTS=https://primary.mint,https://backup1.mint,https://backup2.mint
-```
-
-### Custom Database
-
-Use PostgreSQL instead of SQLite:
-
-```bash
-DATABASE_URL=postgresql+asyncpg://user:pass@localhost/routstr
-```
-
-### Proxy Settings
-
-For corporate environments:
-
-```bash
-HTTP_PROXY=http://proxy.company.com:8080
-HTTPS_PROXY=http://proxy.company.com:8080
-```
-
-## Next Steps
-
-- [User Guide](../user-guide/introduction.md) - Start using Routstr
-- [Admin Dashboard](../user-guide/admin-dashboard.md) - Manage your node
-- [Custom Pricing](../advanced/custom-pricing.md) - Advanced pricing strategies
diff --git a/docs/getting-started/docker.md b/docs/getting-started/docker.md
deleted file mode 100644
index 9357a44f..00000000
--- a/docs/getting-started/docker.md
+++ /dev/null
@@ -1,337 +0,0 @@
-# Docker Setup
-
-This guide covers deploying Routstr Core using Docker for production environments.
-
-## Docker Images
-
-Official images are available on GitHub Container Registry:
-
-```bash
-ghcr.io/routstr/proxy:latest
-```
-
-## Basic Docker Run
-
-### Minimal Setup
-
-```bash
-docker run -d \
- --name routstr \
- -p 8000:8000 \
- -e UPSTREAM_BASE_URL=https://api.openai.com/v1 \
- -e UPSTREAM_API_KEY=sk-... \
- -e ADMIN_PASSWORD=secure-password \
- ghcr.io/routstr/proxy:latest
-```
-
-### With Persistent Storage
-
-```bash
-docker run -d \
- --name routstr \
- -p 8000:8000 \
- -v routstr-data:/app/data \
- -v routstr-logs:/app/logs \
- -e UPSTREAM_BASE_URL=https://api.openai.com/v1 \
- -e UPSTREAM_API_KEY=sk-... \
- -e DATABASE_URL=sqlite+aiosqlite:///data/keys.db \
- ghcr.io/routstr/proxy:latest
-```
-
-## Docker Compose Setup
-
-### Basic Configuration
-
-Create `compose.yml`:
-
-```yaml
-version: '3.8'
-
-services:
- routstr:
- image: ghcr.io/routstr/proxy:latest
- ports:
- - "8000:8000"
- volumes:
- - ./data:/app/data
- - ./logs:/app/logs
- env_file:
- - .env
- restart: unless-stopped
-```
-
-### With Tor Hidden Service
-
-The included `compose.yml` provides Tor support:
-
-```yaml
-version: '3.8'
-
-services:
- routstr:
- build: . # Or use image: ghcr.io/routstr/proxy:latest
- volumes:
- - .:/app
- - ./logs:/app/logs
- env_file:
- - .env
- environment:
- - TOR_PROXY_URL=socks5://tor:9050
- ports:
- - 8000:8000
- extra_hosts:
- - "host.docker.internal:host-gateway"
-
- tor:
- image: ghcr.io/hundehausen/tor-hidden-service:latest
- volumes:
- - tor-data:/var/lib/tor
- environment:
- - HS_ROUTER=routstr:8000:80
- depends_on:
- - routstr
-
-volumes:
- tor-data:
-```
-
-### Environment File
-
-Create `.env` file:
-
-```bash
-# Required
-UPSTREAM_BASE_URL=https://api.openai.com/v1
-UPSTREAM_API_KEY=your-api-key
-ADMIN_PASSWORD=secure-admin-password
-
-# Cashu Configuration
-CASHU_MINTS=https://mint.minibits.cash/Bitcoin
-
-# Optional
-NAME=My Routstr Node
-DESCRIPTION=Pay-per-use AI API proxy
-NPUB=npub1...
-HTTP_URL=https://api.mynode.com
-ONION_URL=http://mynode.onion
-
-# Pricing (optional)
-FIXED_PRICING=false
-EXCHANGE_FEE=1.005
-UPSTREAM_PROVIDER_FEE=1.05
-```
-
-## Building Custom Image
-
-### Dockerfile Overview
-
-The provided Dockerfile:
-
-- Uses Alpine Linux for small size
-- Installs required dependencies for secp256k1
-- Runs as non-root user
-- Exposes port 8000
-
-### Build Locally
-
-```bash
-# Clone repository
-git clone https://github.com/routstr/routstr-core.git
-cd routstr-core
-
-# Build image
-docker build -t my-routstr:latest .
-
-# Run custom image
-docker run -d \
- --name routstr \
- -p 8000:8000 \
- --env-file .env \
- my-routstr:latest
-```
-
-## Deployment Considerations
-
-### Resource Requirements
-
-- **CPU**: 1-2 cores recommended
-- **Memory**: 512MB-1GB
-- **Storage**: 1GB + database growth
-- **Network**: Low latency to upstream provider
-
-### Health Checks
-
-Add health check to compose.yml:
-
-```yaml
-services:
- routstr:
- # ... other config ...
- healthcheck:
- test: ["CMD", "curl", "-f", "http://localhost:8000/v1/info"]
- interval: 30s
- timeout: 10s
- retries: 3
- start_period: 40s
-```
-
-### Reverse Proxy Setup
-
-#### Nginx Example
-
-```nginx
-server {
- listen 443 ssl http2;
- server_name api.yournode.com;
-
- ssl_certificate /path/to/cert.pem;
- ssl_certificate_key /path/to/key.pem;
-
- location / {
- proxy_pass http://localhost:8000;
- proxy_set_header Host $host;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
-
- # For streaming responses
- proxy_buffering off;
- proxy_cache off;
- proxy_set_header Connection '';
- proxy_http_version 1.1;
- chunked_transfer_encoding off;
- }
-}
-```
-
-#### Caddy Example
-
-```caddy
-api.yournode.com {
- reverse_proxy localhost:8000 {
- flush_interval -1
- }
-}
-```
-
-## Monitoring
-
-### Log Management
-
-View logs:
-
-```bash
-# Docker
-docker logs -f routstr
-
-# Docker Compose
-docker compose logs -f routstr
-
-# Log files
-tail -f ./logs/routstr.log
-```
-
-### Metrics
-
-Monitor key metrics:
-
-- Request count and latency
-- Token validation success rate
-- Upstream API errors
-- Database size growth
-
-## Backup and Recovery
-
-### Database Backup
-
-```bash
-# Backup SQLite database
-docker exec routstr sqlite3 /app/data/keys.db ".backup /app/data/backup.db"
-
-# Copy backup locally
-docker cp routstr:/app/data/backup.db ./backup-$(date +%Y%m%d).db
-```
-
-### Restore from Backup
-
-```bash
-# Stop service
-docker compose down
-
-# Restore database
-docker cp ./backup.db routstr:/app/data/keys.db
-
-# Restart service
-docker compose up -d
-```
-
-## Security Considerations
-
-### Environment Variables
-
-- Never commit `.env` files
-- Use Docker secrets for sensitive data
-- Rotate API keys regularly
-- Use strong admin passwords
-
-### Network Security
-
-- Use HTTPS/TLS termination
-- Restrict admin interface access
-- Enable firewall rules
-- Monitor for suspicious activity
-
-### Container Security
-
-- Run as non-root user
-- Use read-only filesystem where possible
-- Limit container capabilities
-- Keep base image updated
-
-## Troubleshooting
-
-### Container Won't Start
-
-```bash
-# Check logs
-docker logs routstr
-
-# Verify environment
-docker exec routstr env | grep -E "(UPSTREAM|CASHU|ADMIN)"
-
-# Test database connection
-docker exec routstr sqlite3 /app/data/keys.db ".tables"
-```
-
-### Permission Issues
-
-```bash
-# Fix volume permissions
-sudo chown -R 1000:1000 ./data ./logs
-```
-
-### Network Issues
-
-```bash
-# Test upstream connectivity
-docker exec routstr curl -I https://api.openai.com
-
-# Check DNS resolution
-docker exec routstr nslookup api.openai.com
-```
-
-## Production Checklist
-
-- [ ] Set strong `ADMIN_PASSWORD`
-- [ ] Configure proper `UPSTREAM_BASE_URL` and `UPSTREAM_API_KEY`
-- [ ] Set up persistent volumes for data and logs
-- [ ] Configure reverse proxy with TLS
-- [ ] Set up monitoring and alerting
-- [ ] Implement backup strategy
-- [ ] Test disaster recovery
-- [ ] Document deployment process
-
-## Next Steps
-
-- [Configuration Guide](configuration.md) - All environment variables
-- [Admin Dashboard](../user-guide/admin-dashboard.md) - Manage your node
diff --git a/docs/getting-started/overview.md b/docs/getting-started/overview.md
deleted file mode 100644
index 1381f2fb..00000000
--- a/docs/getting-started/overview.md
+++ /dev/null
@@ -1,156 +0,0 @@
-# Overview
-
-Routstr Core is a powerful payment proxy that brings Bitcoin micropayments to AI APIs. This overview will help you understand the core concepts and architecture.
-
-## Core Concepts
-
-### Payment Proxy
-
-Routstr acts as a transparent proxy between your application and OpenAI-compatible APIs. It:
-
-- Intercepts API requests
-- Validates payment tokens
-- Forwards requests to the upstream provider
-- Tracks usage and deducts costs
-- Returns responses to the client
-
-### Cashu eCash Protocol
-
-[Cashu](https://cashu.space) is a Bitcoin eCash protocol that enables:
-
-- **Privacy**: Payments are unlinkable and untraceable
-- **Instant Settlement**: No waiting for blockchain confirmations
-- **Micropayments**: Send fractions of a satoshi
-- **Offline Capability**: Tokens can be transferred without internet
-
-### Lightning Network Integration
-
-Routstr connects to the Lightning Network through Cashu mints, enabling:
-
-- Fast Bitcoin deposits and withdrawals
-- Global payment reach
-- Low transaction fees
-- No minimum payment amounts
-
-## Architecture
-
-### System Components
-
-```mermaid
-graph TB
- subgraph "Client Side"
- A[AI Application]
- B[OpenAI SDK]
- C[eCash Wallet]
- end
-
- subgraph "Routstr Core"
- D[FastAPI Server]
- E[Auth Module]
- F[Payment Module]
- G[Proxy Module]
- H[SQLite Database]
- end
-
- subgraph "External Services"
- I[Upstream AI Provider]
- J[Cashu Mint]
- K[Bitcoin/Lightning]
- end
-
- A --> B
- B --> D
- C --> D
- D --> E
- E --> F
- F --> J
- D --> G
- G --> I
- D --> H
- J --> K
-```
-
-### Key Modules
-
-1. **Authentication** (`auth.py`)
- - API key validation
- - Balance checking
- - Request authorization
-
-2. **Payment Processing** (`payment/`)
- - Token validation
- - Cost calculation
- - Balance updates
- - Pricing models
-
-3. **Proxy Handler** (`proxy.py`)
- - Request forwarding
- - Response streaming
- - Usage tracking
- - Error handling
-
-4. **Wallet Management** (`wallet.py`)
- - Cashu wallet integration
- - Token redemption
- - Balance management
- - Automatic payouts
-
-5. **Admin Interface** (`core/admin.py`)
- - Web dashboard
- - Balance viewing
- - Key management
- - Withdrawal interface
-
-## Payment Flow
-
-### Standard Flow (API Key)
-
-1. User deposits eCash tokens to create an API key
-2. Client sends requests with the API key
-3. Routstr checks balance and forwards request
-4. Cost is deducted based on actual usage
-5. Response is returned to client
-
-### Per-Request Flow (Coming Soon)
-
-1. Client includes eCash token in request header
-2. Routstr validates token meets minimum amount
-3. Request is processed
-4. Change is returned in response header
-5. No account or balance needed
-
-## Supported Features
-
-### API Compatibility
-
-- ✅ Chat completions (streaming and non-streaming)
-- ✅ Text completions
-- ✅ Embeddings
-- ✅ Image generation
-- ✅ Audio transcription/translation
-- ✅ Model listing
-- ✅ Custom endpoints
-
-### Payment Features
-
-- ✅ Multiple Cashu mint support
-- ✅ Automatic balance tracking
-- ✅ Model-based pricing
-- ✅ USD to BTC conversion
-- ✅ Configurable fees
-- ✅ Balance withdrawals
-
-### Operational Features
-
-- ✅ Docker deployment
-- ✅ Tor hidden service support
-- ✅ Nostr relay discovery
-- ✅ Database migrations
-- ✅ Comprehensive logging
-- ✅ Admin dashboard
-
-## Next Steps
-
-- [Quick Start](quickstart.md) - Get running in minutes
-- [Docker Setup](docker.md) - Deploy with containers
-- [Configuration](configuration.md) - Customize your instance
\ No newline at end of file
diff --git a/docs/getting-started/quickstart.md b/docs/getting-started/quickstart.md
deleted file mode 100644
index de17dc0c..00000000
--- a/docs/getting-started/quickstart.md
+++ /dev/null
@@ -1,226 +0,0 @@
-# Quick Start
-
-Get Routstr Core up and running in minutes with Docker or local development setup.
-
-## Prerequisites
-
-- Docker and Docker Compose (for production)
-- Python 3.11+ (for development)
-- A Cashu-compatible wallet (optional for testing)
-
-## Option 1: Docker (Recommended)
-
-### Quick Run
-
-The fastest way to start Routstr Core:
-
-```bash
-docker run -d \
- --name routstr-proxy \
- -p 8000:8000 \
- -e UPSTREAM_BASE_URL=https://api.openai.com/v1 \
- -e UPSTREAM_API_KEY=your-openai-api-key \
- ghcr.io/routstr/proxy:latest
-```
-
-### Docker Compose
-
-For a full setup with Tor support:
-
-1. Clone the repository:
-
-```bash
-git clone https://github.com/routstr/routstr-core.git
-cd routstr-core
-```
-
-2. Create environment file:
-
-```bash
-cp .env.example .env
-# Edit .env with your settings
-```
-
-3. Start the services:
-
-```bash
-docker compose up -d
-```
-
-This will start:
-
-- Routstr proxy on port 8000
-- Tor hidden service (optional)
-- Automatic database migrations
-
-### Verify Installation
-
-Check that Routstr is running:
-
-```bash
-curl http://localhost:8000/v1/info
-```
-
-You should see:
-
-```json
-{
- "name": "ARoutstrNode",
- "description": "A Routstr Node",
- "version": "0.2.0",
- "npub": "",
- "mints": ["https://mint.minibits.cash/Bitcoin"],
- "models": {...}
-}
-```
-
-## Option 2: Local Development
-
-### Install Dependencies
-
-1. Install [uv](https://github.com/astral-sh/uv) package manager:
-
-```bash
-curl -LsSf https://astral.sh/uv/install.sh | sh
-```
-
-2. Clone and setup:
-
-```bash
-git clone https://github.com/routstr/routstr-core.git
-cd routstr-core
-uv sync
-```
-
-3. Configure environment:
-
-```bash
-cp .env.example .env
-# Edit .env with your settings
-```
-
-### Run the Server
-
-```bash
-fastapi run routstr --host 0.0.0.0 --port 8000
-```
-
-## First API Call
-
-### 1. Get an eCash Token
-
-You'll need a Cashu token to pay for API calls. Options:
-
-- Use a [Cashu wallet](https://cashu.space) to create tokens
-- Get test tokens from a testnet mint
-- Use the example token (for testing only)
-
-### 2. Create an API Key
-
-Send your eCash token to create an API key:
-
-```bash
-curl -X POST http://localhost:8000/v1/wallet/create \
- -H "Content-Type: application/json" \
- -d '{
- "cashu_token": "cashuAeyJ0b2..."
- }'
-```
-
-Response:
-
-```json
-{
- "api_key": "rUvK7...",
- "balance": 10000
-}
-```
-
-### 3. Make an API Call
-
-Use your API key like a normal OpenAI key:
-
-```python
-import openai
-
-client = openai.OpenAI(
- api_key="rUvK7...", # Your Routstr API key
- base_url="http://localhost:8000/v1"
-)
-
-response = client.chat.completions.create(
- model="gpt-4o-mini",
- messages=[{"role": "user", "content": "Hello!"}]
-)
-
-print(response.choices[0].message.content)
-```
-
-## Example Client
-
-Run the included example:
-
-```bash
-CASHU_TOKEN="your-token" python example.py
-```
-
-This demonstrates:
-
-- Creating an API key from a token
-- Making streaming chat requests
-- Automatic balance deduction
-
-## Testing the Setup
-
-### Check Available Models
-
-```bash
-curl http://localhost:8000/v1/models
-```
-
-### View Admin Dashboard
-
-Open in your browser.
-
-Default password is set in `ADMIN_PASSWORD` environment variable.
-
-### Monitor Logs
-
-Docker:
-
-```bash
-docker compose logs -f routstr
-```
-
-Local:
-
-```bash
-# Logs are in ./logs/ directory
-tail -f logs/routstr.log
-```
-
-## Common Issues
-
-### Connection Refused
-
-- Ensure the service is running: `docker ps`
-- Check firewall settings
-- Verify port 8000 is not in use
-
-### Invalid API Key
-
-- Ensure you've created an API key with sufficient balance
-- Check the token was valid and had value
-- Verify the mint URL is accessible
-
-### Upstream Errors
-
-- Check `UPSTREAM_BASE_URL` is correct
-- Verify `UPSTREAM_API_KEY` if required
-- Test upstream service directly
-
-## Next Steps
-
-- [Configuration Guide](configuration.md) - Customize settings
-- [Docker Setup](docker.md) - Production deployment
-- [User Guide](../user-guide/introduction.md) - Detailed usage
diff --git a/docs/getting-started/ui-configuration.md b/docs/getting-started/ui-configuration.md
deleted file mode 100644
index b619b160..00000000
--- a/docs/getting-started/ui-configuration.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# UI Configuration
-
-This guide explains how to configure the Routstr UI for different environments.
-
-## Environment Variables
-
-The UI uses Next.js environment variables to configure API endpoints and authentication.
-
-### Centralized Configuration
-
-This project uses a centralized configuration approach with a single `.env` file in the project root. This file contains both backend and frontend configuration variables.
-
-Create or update your `.env` file in the project root:
-
-```bash
-# .env (in project root)
-
-# UI Configuration (NEXT_PUBLIC_ variables are exposed to the browser)
-NEXT_PUBLIC_API_URL=http://127.0.0.1:8000
-```
-
-### Development vs Production
-
-The same `.env` file is used for both development and production. Simply change the values:
-
-**Development:**
-
-```bash
-NEXT_PUBLIC_API_URL=http://127.0.0.1:8000
-```
-
-**Production:**
-
-```bash
-NEXT_PUBLIC_API_URL=https://api.yourroutstr.com
-```
-
-## Building the UI
-
-The build process automatically reads configuration from the root `.env` file:
-
-```bash
-# From the project root
-make ui-build
-# or
-./scripts/build-ui.sh
-```
-
-The build script will automatically:
-
-- Load `NEXT_PUBLIC_*` variables from the root `.env` file
-- Use them during the Next.js build process
-- Display warnings if the `.env` file is missing
diff --git a/docs/index.md b/docs/index.md
index aeacbcf4..9a72b9b7 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,83 +1,44 @@
# Routstr Core Documentation
-Welcome to the official documentation for **Routstr Core** - a FastAPI-based reverse proxy that enables Bitcoin micropayments for OpenAI-compatible APIs using the Cashu eCash protocol.
+**Routstr** is a decentralized protocol for permissionless AI inference. It enables an open marketplace where anyone can buy and sell compute using **Bitcoin eCash (Cashu)**.
-## What is Routstr Core?
+---
-Routstr Core is a payment proxy that sits between API clients and OpenAI-compatible services. It enables:
+## 🐣 For Clients (Users & Builders)
-- **Pay-per-request billing** using Bitcoin eCash tokens
-- **Seamless integration** with existing OpenAI clients
-- **Privacy-preserving payments** through the Cashu protocol
-- **Flexible pricing models** with per-token or per-request billing
-- **Multi-provider support** for various AI model providers
+If you want to use AI models in your application without accounts or KYC.
-### Key Features
+- **[Introduction](client/introduction.md)**: How the ecosystem works.
+- **[Payment Flow](client/payments.md)**: Funding sessions, topping up, and refunds.
+- **[Integration Guide](client/integration.md)**: Code examples for Python, JS, and cURL.
-- 🪙 **Cashu Wallet Integration** - Accept Lightning payments and redeem eCash tokens
-- 🔑 **API Key Management** - Secure key storage with balance tracking
-- 💰 **Dynamic Pricing** - Model-based pricing with live BTC/USD conversion
-- 🎛️ **Admin Dashboard** - Web interface for balance and key management
-- 🌐 **Nostr Discovery** - Find providers through decentralized relay network
-- 🐋 **Docker Support** - Easy deployment with optional Tor hidden service
-- ⚡ **Lightning Fast** - Minimal latency overhead for API requests
+## 🦁 For Providers (Node Operators)
-## How It Works
+If you want to run a node, resell API access, or monetize hardware.
-```mermaid
-sequenceDiagram
- participant Client
- participant Routstr as Routstr Proxy
- participant DB as Database
- participant Upstream as AI Provider
- participant Wallet as Cashu Wallet
+- **[Quick Start](provider/quickstart.md)**: Deploy a node in 5 minutes.
+- **[Deployment](provider/deployment.md)**: Production Docker setup.
+- **[Configuration](provider/configuration.md)**: Environment variables and settings.
+- **[Dashboard](provider/dashboard.md)**: Managing your node visually.
+- **[Pricing Strategy](provider/pricing.md)**: Setting margins and fees.
+- **[Discovery](provider/discovery.md)**: Announcing your node on Nostr.
+- **[Tor Support](provider/tor.md)**: Running an anonymous hidden service.
- Client->>Routstr: API Request + eCash Token
- Routstr->>Wallet: Validate & Redeem Token
- Wallet-->>Routstr: Token Value (sats)
- Routstr->>DB: Store/Update Balance
- Routstr->>Upstream: Forward API Request
- Upstream-->>Routstr: API Response + Usage Data
- Routstr->>DB: Deduct Actual Cost
- Routstr-->>Client: API Response
-```
+---
-## Quick Links
+## 🔌 API Reference
-
+- **[Overview](api/overview.md)**: Base URL, headers, and standards.
+- **[Endpoints](api/endpoints.md)**: Full list of REST endpoints.
+- **[Authentication](api/authentication.md)**: Handling API keys and tokens.
+- **[Errors](api/errors.md)**: Status codes and debugging.
-- :rocket: **[Quick Start](getting-started/quickstart.md)**
+## 🛠️ Contributing
- Get up and running with Docker in minutes
+- **[Architecture](contributing/architecture.md)**: System design.
+- **[Setup](contributing/setup.md)**: Development environment.
+- **[Testing](contributing/testing.md)**: Running tests.
-- :gear: **[Configuration](getting-started/configuration.md)**
+---
- Learn about environment variables and settings
-
-- :book: **[User Guide](user-guide/introduction.md)**
-
- Comprehensive guide for using Routstr
-
-- :hammer: **[Contributing](contributing/setup.md)**
-
- Help improve Routstr Core
-
-
-
-## Use Cases
-
-- **AI Application Developers** - Add Bitcoin payments to your AI apps without managing infrastructure
-- **API Resellers** - Resell API access with custom pricing and profit margins
-- **Privacy-Focused Users** - Access AI models without revealing personal information
-- **Micropayment Experiments** - Test new business models with instant, small payments
-
-## Getting Help
-
-- 📖 Browse the [User Guide](user-guide/introduction.md) for detailed usage instructions
-- 🐛 Report issues on [GitHub](https://github.com/routstr/routstr-core/issues)
-- 💬 Join the community discussions
-- 🔧 Check the [API Reference](api/overview.md) for technical details
-
-## License
-
-Routstr Core is open source software licensed under the GPLv3. See the [LICENSE](https://github.com/routstr/routstr-core/blob/main/LICENSE) file for details.
+*Powered by [Cashu](https://cashu.space) and [Nostr](https://nostr.com).*
diff --git a/docs/overview.md b/docs/overview.md
new file mode 100644
index 00000000..9e0ddbc8
--- /dev/null
+++ b/docs/overview.md
@@ -0,0 +1,76 @@
+# Overview
+
+Routstr is a decentralized protocol for **permissionless, private, and censorship-resistant AI inference**. It creates an open marketplace where anyone can sell llm-tokens and anyone can buy them using privacy-preserving micropayments.
+
+By combining **Nostr** (for censorship-resistant discovery and communication) and **Cashu** (for private, instant Bitcoin eCash payments), Routstr effectively removes the "middleman" from the AI ecosystem.
+
+## How it Works
+
+The network consists of independent **Providers** (Sellers) and **Clients** (Buyers). There is no central server, no login, and no credit card required.
+
+1. **Discovery (Nostr)**: Providers announce their availability, models (e.g., `gpt-4o`, `deepseek-r1`), and prices on the Nostr network.
+2. **Payment (Cashu)**: Clients pay providers directly using Bitcoin eCash (Cashu tokens). These payments are untraceable and settle instantly.
+3. **Inference (Proxy)**: The Provider acts as a gateway (or runs local hardware), executing the AI model and returning the result to the Client.
+
+## Who is this for?
+
+The documentation is split into two paths depending on your goal:
+
+### 🐣 I want to BUILD on Routstr (Client)
+
+You are a developer building an AI agent, a chat app, or a script, and you want access to AI models without API keys, subscriptions, or KYC.
+
+* **No Accounts**: Just get a wallet.
+* **Privacy**: Your requests are mixed with thousands of others; providers can't profile you.
+* **Choice**: Switch between hundreds of providers instantly for the best price/performance.
+
+👉 **[Go to Client Guide](client/introduction.md)**
+
+### 🦁 I want to RUN a Node (Provider)
+
+You have API credits (OpenAI, Anthropic, etc.) or GPU capacity and want to earn Bitcoin by selling AI access to the network.
+
+* **Monetize API Keys**: Connect your OpenAI/Anthropic/OpenRouter accounts and earn sats on every request.
+* **Monetize Hardware**: Run local models (via vLLM, Ollama) and sell access.
+* **Permissionless**: No approval needed. Start the container, configure via dashboard, start earning.
+
+!!! note "Coming Soon"
+ Future versions will support node-to-node routing—run a gateway without needing your own AI provider credentials.
+
+👉 **[Go to Provider Guide](provider/quickstart.md)**
+
+---
+
+## Architecture
+
+Routstr is built on a modular stack defined by the [Routstr Improvement Protocols (RIPs)](https://github.com/routstr/rips).
+
+```mermaid
+flowchart LR
+ subgraph Client
+ A[App / Agent]
+ end
+
+ subgraph Provider
+ B[Routstr Node
Proxy + Auth + Billing]
+ end
+
+ subgraph Upstream
+ C[OpenAI / Anthropic
vLLM / Ollama / ...]
+ end
+
+ A -- "Request +
Cashu Token" --> B
+ B -- "Forward
Request" --> C
+ C -- "Response +
Usage" --> B
+ B -- "Response +
Refund Token" --> A
+```
+
+## Why Routstr?
+
+| Feature | Closed AI | Routstr |
+| :--- | :--- | :--- |
+| **Access** | Account, KYC, Credit Card | Permissionless, Bitcoin-native |
+| **Privacy** | Full Logging & Tracking | Blinded Payments, Ephemeral Sessions |
+| **Resilience** | Single Point of Failure | Decentralized Network |
+| **Pricing** | Fixed, Monopolistic | Dynamic, Market-driven |
+| **Global** | Geofenced | Borderless (Tor/I2P supported) |
diff --git a/docs/provider/advanced-pricing.md b/docs/provider/advanced-pricing.md
new file mode 100644
index 00000000..7bb3bd21
--- /dev/null
+++ b/docs/provider/advanced-pricing.md
@@ -0,0 +1,114 @@
+# Advanced Pricing
+
+Advanced pricing strategies for fine-tuned control over your revenue model.
+
+---
+
+## Default Behavior
+
+By default, Routstr:
+
+1. **Fetches costs** from your upstream provider
+2. **Applies markup** using your fee settings
+3. **Converts to sats** using real-time BTC price
+
+**Formula**: `Price = Upstream Cost × Exchange Fee × Upstream Fee`
+
+---
+
+## Strategy 1: Fixed Per-Request
+
+Charge a flat fee regardless of model or tokens used.
+
+**Configure in Dashboard** → **Settings** → **Pricing**:
+
+- Enable **Fixed Pricing**
+- Set **Fixed Cost Per Request** (in sats)
+
+**Use cases**:
+
+- Internal tools with predictable usage
+- Simple "pay once, get response" APIs
+- Subscription-like tiers
+
+---
+
+## Strategy 2: Fixed Per-Token
+
+Override dynamic pricing with global per-token rates.
+
+**Configure in Dashboard** → **Settings** → **Pricing**:
+
+| Setting | Description |
+|---------|-------------|
+| **Fixed Per 1K Input** | Sats per 1,000 prompt tokens |
+| **Fixed Per 1K Output** | Sats per 1,000 completion tokens |
+
+When set to non-zero values, these override model-specific pricing for all models.
+
+---
+
+## Strategy 3: Per-Model Custom Pricing
+
+Set specific prices for individual models, overriding both upstream cost and global fees.
+
+**Configure in Dashboard** → **Models**:
+
+1. Click on a model (e.g., `gpt-4`)
+2. Enter **Prompt Price** and **Completion Price** (USD per 1M tokens)
+3. Save
+
+**Example**: OpenAI charges $30/1M for GPT-4. Set your price to $35/1M to lock in a margin regardless of fee settings.
+
+---
+
+## Minimum Charge
+
+Prevent dust transactions and spam:
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| **Min Request Cost** | Minimum charge in msats | 1000 (1 sat) |
+
+If a request's calculated cost falls below this (e.g., very short prompts), the client pays the minimum.
+
+---
+
+## Combining Strategies
+
+Strategies apply in order of specificity:
+
+1. **Per-model override** (highest priority)
+2. **Fixed per-token rates**
+3. **Dynamic pricing with fees** (default)
+4. **Fixed per-request** (overrides all above if enabled)
+
+**Example setup**:
+
+- Dynamic pricing as default (10% markup)
+- GPT-4 locked at $35/1M (premium model)
+- Claude Haiku at 5 sats/1K tokens (budget option)
+- Minimum 1 sat per request
+
+---
+
+## Pricing for Profit
+
+### High-Volume Strategy
+
+Lower margins, more clients:
+
+- Exchange Fee: 1.002 (0.2%)
+- Upstream Fee: 1.05 (5%)
+
+### Premium Strategy
+
+Higher margins, fewer clients:
+
+- Exchange Fee: 1.01 (1%)
+- Upstream Fee: 1.25 (25%)
+
+### Mixed Strategy
+
+- Cheap models (GPT-3.5, Haiku): Low margin to attract volume
+- Premium models (GPT-4, Opus): High margin for profit
diff --git a/docs/provider/configuration.md b/docs/provider/configuration.md
new file mode 100644
index 00000000..aaa00e86
--- /dev/null
+++ b/docs/provider/configuration.md
@@ -0,0 +1,122 @@
+# Configuration
+
+Routstr is configured primarily through the **Admin Dashboard**. All settings persist in the database and take effect immediately—no restarts required.
+
+For automated deployments, you can optionally pre-configure settings via environment variables.
+
+---
+
+## Admin Dashboard (Primary)
+
+Access the dashboard at `/admin/` on your node.
+
+### Upstream Providers
+
+Connect to your AI provider(s):
+
+| Setting | Description |
+|---------|-------------|
+| **Upstream URL** | API endpoint (e.g., `https://api.openai.com/v1`) |
+| **API Key** | Your provider's API key |
+
+### Node Identity
+
+How your node appears to clients:
+
+| Setting | Description |
+|---------|-------------|
+| **Name** | Display name (e.g., "Fast GPT-4 Node") |
+| **Description** | Brief description of your service |
+
+### Pricing
+
+Control your profit margins:
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| **Fixed Pricing** | Charge flat rate per request vs. per-token | Off |
+| **Exchange Fee** | Buffer for BTC volatility | 1.005 (0.5%) |
+| **Upstream Fee** | Your profit markup | 1.10 (10%) |
+
+See [Pricing](pricing.md) for detailed strategies.
+
+### Cashu Mints
+
+Which mints to accept payments from:
+
+| Setting | Description |
+|---------|-------------|
+| **Mints** | List of trusted Cashu mint URLs |
+
+### Lightning Withdrawals
+
+Automatic profit withdrawal:
+
+| Setting | Description |
+|---------|-------------|
+| **Lightning Address** | Your LN address for withdrawals |
+
+### Security
+
+| Setting | Description |
+|---------|-------------|
+| **Admin Password** | Password for dashboard access |
+
+### Nostr Discovery
+
+Announce your node on the network:
+
+| Setting | Description |
+|---------|-------------|
+| **Npub** | Your Nostr public key |
+| **Nsec** | Your Nostr private key (for signing) |
+| **Relays** | Relays to publish announcements |
+
+See [Discovery](discovery.md) for details.
+
+---
+
+## Environment Variables (Optional)
+
+Use environment variables for:
+
+- **Automated deployments** (CI/CD, infrastructure-as-code)
+- **Secrets management** (external secret stores)
+- **Initial bootstrap** (set once, manage via dashboard later)
+
+### All Variables
+
+| Variable | Description | Default |
+|----------|-------------|---------|
+| `UPSTREAM_BASE_URL` | Upstream API endpoint | — |
+| `UPSTREAM_API_KEY` | Upstream API key | — |
+| `ADMIN_PASSWORD` | Dashboard password | (none) |
+| `DATABASE_URL` | Database connection string | `sqlite+aiosqlite:///keys.db` |
+| `NAME` | Node display name | `ARoutstrNode` |
+| `DESCRIPTION` | Node description | `A Routstr Node` |
+| `NPUB` | Nostr public key (bech32) | — |
+| `NSEC` | Nostr private key | — |
+| `CASHU_MINTS` | Comma-separated mint URLs | `https://mint.minibits.cash/Bitcoin` |
+| `RECEIVE_LN_ADDRESS` | Lightning address for withdrawals | — |
+| `TOR_PROXY_URL` | SOCKS5 proxy for Tor | `socks5://127.0.0.1:9050` |
+| `CORS_ORIGINS` | Allowed CORS origins | `*` |
+| `RELAYS` | Nostr relays (comma-separated) | (default set) |
+
+### Priority
+
+Environment variables are read on startup. Dashboard settings override them and persist in the database. Once you change a setting in the dashboard, the env var is ignored for that setting.
+
+---
+
+## Models
+
+Manage which AI models you offer:
+
+1. Go to **Models** in the dashboard
+2. Models are auto-discovered from your upstream
+3. For each model, you can:
+ - **Enable/Disable** — hide expensive models you don't want to serve
+ - **Override pricing** — set custom per-token rates
+ - **Create aliases** — friendly names for models
+
+See [Pricing](pricing.md) for per-model pricing strategies.
diff --git a/docs/provider/dashboard.md b/docs/provider/dashboard.md
new file mode 100644
index 00000000..aaa860bf
--- /dev/null
+++ b/docs/provider/dashboard.md
@@ -0,0 +1,208 @@
+# Admin Dashboard
+
+The Admin Dashboard is your command center for managing your Routstr provider node. Configure providers, monitor earnings, manage models, and withdraw profits—all from a web interface.
+
+**URL**: `http://your-node:8000/admin/`
+
+---
+
+## Overview Tab
+
+The main dashboard view shows your node's financial status at a glance.
+
+### Wallet Summary
+
+| Metric | Description |
+|--------|-------------|
+| **Total Wallet** | All Bitcoin currently held by your node |
+| **User Balances** | Funds belonging to active client sessions |
+| **Your Balance** | Your profit: `Total - User Balances` |
+
+### Mint Status
+
+Shows connected Cashu mints and their balances. Each mint displays:
+
+- Connection status
+- Balance in sats/msats
+- Unit type
+
+
+
+---
+
+## Sessions Tab
+
+View and manage active client sessions (API keys).
+
+### Session List
+
+| Column | Description |
+|--------|-------------|
+| **Hashed Key** | Privacy-preserving identifier (not the actual key) |
+| **Balance** | Remaining funds in the session |
+| **Spent** | Total amount spent by this session |
+| **Requests** | Number of API calls made |
+| **Created** | When the session was created |
+| **Expires** | Auto-expiry time (if set) |
+
+### Actions
+
+- **View Details** — See full session history
+- **Revoke** — Terminate a session (remaining balance returns to your wallet)
+
+
+
+---
+
+## Models Tab
+
+Manage which AI models you offer to clients.
+
+### Model List
+
+Shows all models available from your upstream provider(s):
+
+| Column | Description |
+|--------|-------------|
+| **Model ID** | The model identifier (e.g., `gpt-4o`) |
+| **Enabled** | Whether clients can use this model |
+| **Input Price** | Cost per 1M input tokens (USD) |
+| **Output Price** | Cost per 1M output tokens (USD) |
+| **Custom** | Whether pricing is overridden |
+
+### Actions
+
+- **Import Models** — Fetch latest model list from upstream
+- **Enable/Disable** — Toggle model availability
+- **Edit Pricing** — Override default pricing for a model
+- **Create Alias** — Map a friendly name to a model
+
+### Editing a Model
+
+Click on any model to configure:
+
+| Field | Description |
+|-------|-------------|
+| **Enabled** | Show this model to clients |
+| **Prompt Price** | Custom price per 1M input tokens (USD) |
+| **Completion Price** | Custom price per 1M output tokens (USD) |
+| **Alias** | Alternative name for this model |
+
+
+
+
+---
+
+## Settings Tab
+
+Configure all node settings. Changes take effect immediately.
+
+### Upstream
+
+Connect to your AI provider:
+
+| Field | Description |
+|-------|-------------|
+| **Base URL** | API endpoint (e.g., `https://api.openai.com/v1`) |
+| **API Key** | Your provider's secret key |
+
+
+
+### Node Identity
+
+| Field | Description |
+|-------|-------------|
+| **Name** | Public display name |
+| **Description** | Brief description of your service |
+| **Npub** | Nostr public key for discovery |
+
+### Pricing
+
+| Field | Description |
+|-------|-------------|
+| **Fixed Pricing** | Toggle flat-rate vs. per-token pricing |
+| **Fixed Cost** | Sats per request (when fixed pricing enabled) |
+| **Exchange Fee** | Multiplier for BTC volatility buffer |
+| **Upstream Fee** | Your profit margin multiplier |
+
+**Example**: With Exchange Fee `1.005` and Upstream Fee `1.10`:
+
+- Upstream cost: $30/1M tokens
+- Your price: $30 × 1.005 × 1.10 = $33.17/1M tokens
+
+### Cashu Mints
+
+Manage which mints you accept payments from:
+
+- **Add Mint** — Enter a mint URL
+- **Remove Mint** — Stop accepting from a mint
+- **Test Connection** — Verify mint is reachable
+
+
+
+### Lightning
+
+| Field | Description |
+|-------|-------------|
+| **Lightning Address** | Your LN address for automatic withdrawals |
+
+### Nostr Discovery
+
+| Field | Description |
+|-------|-------------|
+| **Nsec** | Private key for signing announcements |
+| **Relays** | Where to publish your node advertisement |
+
+### Security
+
+| Field | Description |
+|-------|-------------|
+| **Admin Password** | Password for dashboard access |
+
+!!! warning "Set a Password"
+ The dashboard has no password by default. Always set one for production nodes.
+
+
+
+---
+
+## Withdraw Tab
+
+Withdraw your profits to a Lightning wallet.
+
+### Steps
+
+1. **Select Mint** — Choose which mint to withdraw from
+2. **Enter Amount** — How many sats to withdraw
+3. **Generate Token** — Creates a Cashu token
+4. **Redeem** — Paste the token into your Cashu wallet and melt to Lightning
+
+
+
+### Alternative: Lightning Address
+
+If you've configured a Lightning Address in Settings, profits can be automatically swept to your wallet (coming soon).
+
+---
+
+## Logs Tab
+
+View node logs for debugging without SSH access.
+
+### Features
+
+- **Filter by Level** — Error, Warning, Info, Debug
+- **Search** — Find specific entries
+- **Time Range** — View logs from specific periods
+- **Auto-refresh** — Watch logs in real-time
+
+### Common Log Entries
+
+| Entry | Meaning |
+|-------|---------|
+| `Upstream request failed` | Problem connecting to your AI provider |
+| `Invalid token` | Client sent an invalid Cashu token |
+| `Session expired` | API key reached its time limit |
+| `Insufficient balance` | Client ran out of funds mid-request |
+
+
diff --git a/docs/provider/deployment.md b/docs/provider/deployment.md
new file mode 100644
index 00000000..4ad21e78
--- /dev/null
+++ b/docs/provider/deployment.md
@@ -0,0 +1,196 @@
+# Deployment
+
+Production deployment guide for Routstr Provider nodes.
+
+## Docker Compose (Recommended)
+
+For production, use Docker Compose with persistent storage and optional Tor support.
+
+### Basic Setup
+
+Create a `compose.yml`:
+
+```yaml
+services:
+ routstr:
+ image: ghcr.io/routstr/proxy:latest
+ container_name: routstr
+ restart: unless-stopped
+ ports:
+ - "8000:8000"
+ volumes:
+ - ./data:/app/data
+ - ./logs:/app/logs
+```
+
+Start the node:
+
+```bash
+docker compose up -d
+```
+
+Then configure everything via the [Admin Dashboard](http://localhost:8000/admin/).
+
+---
+
+## With Tor (Anonymous Access)
+
+Add Tor to serve your node as a hidden service—no port forwarding needed.
+
+```yaml
+services:
+ routstr:
+ image: ghcr.io/routstr/proxy:latest
+ container_name: routstr
+ restart: unless-stopped
+ ports:
+ - "8000:8000"
+ volumes:
+ - ./data:/app/data
+ - ./logs:/app/logs
+ environment:
+ - TOR_PROXY_URL=socks5://tor:9050
+ depends_on:
+ - tor
+
+ tor:
+ image: ghcr.io/hundehausen/tor-hidden-service:latest
+ container_name: tor
+ restart: unless-stopped
+ volumes:
+ - ./tor-data:/var/lib/tor
+ environment:
+ - HS_ROUTER=routstr:8000:80
+```
+
+After starting, find your `.onion` address:
+
+```bash
+docker exec tor cat /var/lib/tor/hidden_service/hostname
+```
+
+See [Tor Support](tor.md) for details.
+
+---
+
+## Pre-Configuration (Optional)
+
+While everything can be configured via the dashboard, you can pre-configure settings with environment variables for automated deployments.
+
+### Using Environment Variables
+
+```yaml
+services:
+ routstr:
+ image: ghcr.io/routstr/proxy:latest
+ environment:
+ # Pre-configure upstream (optional)
+ - UPSTREAM_BASE_URL=https://api.openai.com/v1
+ - UPSTREAM_API_KEY=sk-proj-...
+
+ # Secure the dashboard (recommended)
+ - ADMIN_PASSWORD=your-secure-password
+
+ # Node identity
+ - NAME=My Provider Node
+ - DESCRIPTION=Fast GPT-4 access via Lightning
+
+ # Lightning withdrawals
+ - RECEIVE_LN_ADDRESS=me@walletofsatoshi.com
+ volumes:
+ - ./data:/app/data
+```
+
+### Using an .env File
+
+```yaml
+services:
+ routstr:
+ image: ghcr.io/routstr/proxy:latest
+ env_file:
+ - .env
+ volumes:
+ - ./data:/app/data
+```
+
+Example `.env`:
+
+```bash
+UPSTREAM_BASE_URL=https://api.openai.com/v1
+UPSTREAM_API_KEY=sk-proj-...
+ADMIN_PASSWORD=change-me
+NAME=My Provider Node
+RECEIVE_LN_ADDRESS=me@walletofsatoshi.com
+```
+
+See [Configuration](configuration.md) for all available options.
+
+---
+
+## Persistence
+
+Routstr stores all data in `/app/data`:
+
+| Path | Contents |
+|------|----------|
+| `keys.db` | SQLite database (settings, API keys, sessions) |
+| `.wallet/` | Cashu wallet data (your Bitcoin!) |
+
+!!! warning "Back Up Your Data"
+ The `./data` volume contains your wallet. Losing it means losing funds. Back up regularly.
+
+---
+
+## Reverse Proxy (Optional)
+
+For custom domains and SSL, use a reverse proxy like Caddy or nginx.
+
+### Caddy Example
+
+```
+api.yournode.com {
+ reverse_proxy localhost:8000
+}
+```
+
+### nginx Example
+
+```nginx
+server {
+ listen 443 ssl;
+ server_name api.yournode.com;
+
+ ssl_certificate /path/to/cert.pem;
+ ssl_certificate_key /path/to/key.pem;
+
+ location / {
+ proxy_pass http://localhost:8000;
+ proxy_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection "upgrade";
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ }
+}
+```
+
+---
+
+## Updates
+
+Pull the latest image and restart:
+
+```bash
+docker compose pull
+docker compose up -d
+```
+
+---
+
+## Building from Source
+
+```bash
+git clone https://github.com/routstr/routstr-core.git
+cd routstr-core
+docker build -t routstr-local .
+```
diff --git a/docs/provider/discovery.md b/docs/provider/discovery.md
new file mode 100644
index 00000000..c0d06036
--- /dev/null
+++ b/docs/provider/discovery.md
@@ -0,0 +1,95 @@
+# Discovery
+
+Routstr uses **Nostr** as a decentralized directory for service discovery. Your node announces its presence, models, and pricing on Nostr relays, allowing clients to find you without a central server.
+
+---
+
+## How It Works
+
+1. **Provider Advertisement (Kind 38421)**: Your node periodically publishes an event with its URL, models, and pricing
+2. **Client Discovery**: Clients query relays for these events to find suitable providers
+
+---
+
+## Configuration
+
+Configure discovery in **Dashboard** → **Settings** → **Nostr**.
+
+### Required Settings
+
+| Field | Description |
+|-------|-------------|
+| **Npub** | Your node's public identity (clients use this to verify your node) |
+| **Nsec** | Your node's private key (used to sign advertisements) |
+| **Relays** | Where to publish your announcements |
+
+### Default Relays
+
+If not configured, Routstr publishes to:
+
+- `wss://relay.damus.io`
+- `wss://relay.nostr.band`
+- `wss://nos.lol`
+
+---
+
+## Advertisement Format
+
+Your node publishes events like:
+
+```json
+{
+ "kind": 38421,
+ "content": {
+ "name": "My Routstr Node",
+ "description": "Fast GPT-4 access via Lightning",
+ "endpoints": {
+ "http": "https://api.mynode.com",
+ "onion": "http://xyz...onion"
+ },
+ "models": ["gpt-4", "claude-3-opus"],
+ "pricing": { ... }
+ },
+ "tags": [
+ ["d", "routstr-provider"],
+ ["g", "US"]
+ ]
+}
+```
+
+---
+
+## Tor Integration
+
+If you're running with Tor (see [Tor Support](tor.md)), your `.onion` address is automatically included in announcements. This allows clients to connect anonymously.
+
+---
+
+## Verify Your Announcements
+
+Check if your node is broadcasting:
+
+1. Copy your `Npub`
+2. Search on [Nostr.band](https://nostr.band) or [Primal](https://primal.net)
+3. Look for Kind 38421 events
+
+---
+
+## Generating Keys
+
+If you don't have a Nostr identity:
+
+1. Use any Nostr client (e.g., [Primal](https://primal.net), [Damus](https://damus.io))
+2. Create an account
+3. Export your keys (npub and nsec)
+4. Enter them in the dashboard
+
+Or generate keys programmatically:
+
+```python
+from nostr_sdk import Keys
+
+keys = Keys.generate()
+print(f"npub: {keys.public_key().to_bech32()}")
+print(f"nsec: {keys.secret_key().to_bech32()}")
+```
diff --git a/docs/provider/pricing.md b/docs/provider/pricing.md
new file mode 100644
index 00000000..2907c691
--- /dev/null
+++ b/docs/provider/pricing.md
@@ -0,0 +1,91 @@
+# Pricing
+
+Routstr's pricing engine lets you act as a retailer of AI compute. You pay upstream providers (OpenAI, Anthropic, etc.) at their rates and sell to clients with your markup.
+
+---
+
+## Pricing Strategies
+
+Configure these in **Dashboard** → **Settings** → **Pricing**.
+
+### Dynamic Pricing (Default)
+
+Passes through upstream costs plus your percentage markup.
+
+**Formula**: `Client Price = Upstream Cost × Exchange Fee × Upstream Fee`
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| **Exchange Fee** | Buffer for BTC price volatility | 1.005 (0.5%) |
+| **Upstream Fee** | Your profit margin | 1.10 (10%) |
+
+**Example**: GPT-4 costs $30/1M tokens from OpenAI. With default settings:
+
+- Price: $30 × 1.005 × 1.10 = $33.17/1M tokens
+- At $60k BTC: ~55,000 sats/1M tokens
+
+### Fixed Pricing
+
+Charge a flat rate per request, regardless of model or token count.
+
+| Setting | Description |
+|---------|-------------|
+| **Fixed Pricing** | Enable flat-rate mode |
+| **Fixed Cost** | Sats per request |
+
+**Best for**: Simple proxies, internal tools, or subscription-like access.
+
+---
+
+## Per-Model Pricing
+
+Override pricing for specific models in **Dashboard** → **Models**.
+
+1. Click on a model
+2. Enter custom **Prompt Price** and **Completion Price** (USD per 1M tokens)
+3. Save
+
+This overrides both the upstream cost and your global markup for that model.
+
+**Example**: Lock GPT-4 at $35/1M tokens regardless of OpenAI's actual rate or your fee settings.
+
+---
+
+## Token-Based Overrides
+
+Set global fixed rates per token (overrides dynamic pricing for all models):
+
+| Setting | Description |
+|---------|-------------|
+| **Fixed Per 1K Input** | Sats per 1,000 prompt tokens |
+| **Fixed Per 1K Output** | Sats per 1,000 completion tokens |
+
+---
+
+## Minimum Charge
+
+Prevent spam with a minimum cost per request:
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| **Min Request Cost** | Minimum charge in msats | 1000 (1 sat) |
+
+If a request's calculated cost is lower than this, the client pays the minimum instead.
+
+---
+
+## Cost Tracking
+
+Routstr tracks balances in **millisats (msats)** for precision with cheap models.
+
+- 1 sat = 1,000 msats
+- API responses include cost in msats
+- Lightning withdrawals round down to whole sats
+
+### Client Verification (RIP-05)
+
+Clients can verify charges:
+
+1. Fetch `/v1/models` for your advertised rates
+2. Calculate expected cost from token counts
+3. Compare to `x-routstr-cost` response header
diff --git a/docs/provider/quickstart.md b/docs/provider/quickstart.md
new file mode 100644
index 00000000..2771c1f3
--- /dev/null
+++ b/docs/provider/quickstart.md
@@ -0,0 +1,99 @@
+# Quick Start
+
+Start earning Bitcoin by selling AI access in under 5 minutes.
+
+## What You'll Build
+
+A **Routstr Provider Node** acts as a gateway that:
+
+1. **Connects** to upstream AI providers (OpenAI, Anthropic, OpenRouter, etc.)
+2. **Accepts** Bitcoin payments via Cashu eCash
+3. **Serves** AI requests to clients on the network
+
+You bring the API keys, Routstr handles the billing, payments, and client management.
+
+!!! tip "Future: Node-to-Node Routing"
+ In future versions, you'll be able to run a node that connects to other Routstr nodes—eliminating the need to configure upstream providers yourself. For now, you'll need your own API credentials.
+
+---
+
+## Prerequisites
+
+- [Docker](https://docs.docker.com/get-docker/) installed
+- API credentials from at least one AI provider (OpenAI, Anthropic, OpenRouter, etc.)
+
+---
+
+## 1. Start the Node
+
+```bash
+docker run -d \
+ --name routstr \
+ -p 8000:8000 \
+ -v routstr-data:/app/data \
+ ghcr.io/routstr/proxy:latest
+```
+
+Verify it's running:
+
+```bash
+curl http://localhost:8000/v1/info
+```
+
+---
+
+## 2. Configure via Dashboard
+
+Open the **Admin Dashboard** at [http://localhost:8000/admin/](http://localhost:8000/admin/).
+
+!!! note "Default Access"
+ The dashboard has no password by default. Set one immediately in Settings for production use.
+
+### Connect Your AI Providers
+
+1. Navigate to **Settings** → **Upstream**
+2. Enter your upstream URL (e.g., `https://api.openai.com/v1`)
+3. Enter your API key
+4. Save
+
+### Set Your Profit Margin
+
+1. Go to **Settings** → **Pricing**
+2. Configure your markup (default is 10%)
+3. Optionally set a fixed price per request instead
+
+### Secure the Dashboard
+
+1. Go to **Settings** → **Admin**
+2. Set a strong password
+3. Save and re-login
+
+---
+
+## 3. Start Earning
+
+Once configured, your node is live. Clients pay you in Bitcoin (via Cashu tokens) for every AI request.
+
+### Monitor Your Earnings
+
+The dashboard shows:
+
+- **Total Wallet**: All Bitcoin held by your node
+- **User Balances**: Funds belonging to active client sessions
+- **Your Balance**: Your profit (`Total - User Balances`)
+
+### Withdraw Profits
+
+1. Go to **Withdraw** in the dashboard
+2. Select amount and mint
+3. Generate a Cashu token
+4. Redeem to your Lightning wallet
+
+---
+
+## Next Steps
+
+- **[Deployment](deployment.md)**: Production setup with Docker Compose and Tor
+- **[Dashboard Guide](dashboard.md)**: Full reference for all dashboard features
+- **[Pricing](pricing.md)**: Configure pricing strategies and per-model overrides
+- **[Discovery](discovery.md)**: Announce your node on Nostr for clients to find you
diff --git a/docs/provider/tor.md b/docs/provider/tor.md
new file mode 100644
index 00000000..187e4c56
--- /dev/null
+++ b/docs/provider/tor.md
@@ -0,0 +1,50 @@
+# Tor Support
+
+Running Routstr as a **Tor Hidden Service** allows you to offer API access anonymously and bypass NAT/firewalls without port forwarding.
+
+## Automatic Setup (Docker)
+
+The standard `compose.yml` includes a Tor container pre-configured to serve your node.
+
+1. **Start the stack**: `docker compose up -d`
+2. **Wait**: Tor takes about 30 seconds to generate keys and bootstrap.
+3. **Find your address**:
+ ```bash
+ docker exec tor cat /var/lib/tor/hidden_service/hostname
+ ```
+ Output: `v2xyz...longaddress.onion`
+
+Routstr will automatically detect this address (via the `discover_onion_url_from_tor` logic) and include it in:
+- The `/v1/info` endpoint.
+- Nostr announcements (RIP-02).
+
+## Manual Setup
+
+If you are running outside Docker or managing Tor yourself:
+
+1. **Install Tor**: `sudo apt install tor`
+2. **Edit `torrc`**:
+ ```
+ HiddenServiceDir /var/lib/tor/routstr/
+ HiddenServicePort 80 127.0.0.1:8000
+ ```
+3. **Restart Tor**: `sudo systemctl restart tor`
+4. **Get Address**: `sudo cat /var/lib/tor/routstr/hostname`
+5. **Configure Routstr**:
+ Set `ONION_URL=http://youraddress.onion` in your `.env` file so the node knows its own address.
+
+## Client Usage
+
+Clients connecting to your `.onion` address must route traffic through SOCKS5.
+
+**Python Example:**
+```python
+import httpx
+from openai import OpenAI
+
+client = OpenAI(
+ base_url="http://youraddress.onion/v1",
+ api_key="sk-...",
+ http_client=httpx.Client(proxy="socks5://127.0.0.1:9050")
+)
+```
diff --git a/docs/user-guide/admin-dashboard.md b/docs/user-guide/admin-dashboard.md
deleted file mode 100644
index 2bdf94b3..00000000
--- a/docs/user-guide/admin-dashboard.md
+++ /dev/null
@@ -1,216 +0,0 @@
-# Admin Dashboard
-
-The Routstr admin dashboard is a modern web interface for managing your node, monitoring wallet balances, configuring AI models and providers, and handling Bitcoin Lightning payments through Cashu eCash.
-
-## Accessing the Dashboard
-
-### Authentication
-
-The dashboard is protected by password authentication:
-
-1. Navigate to `/admin/` in your browser
-2. Enter the admin password
-3. Optional: Configure custom base URL if not pre-configured
-4. Click "Login"
-
-The interface supports both environment-configured URLs and manual URL entry for deployment flexibility.
-
-## Dashboard Overview
-
-The main dashboard consists of four primary sections accessible through a collapsible sidebar:
-
-- **Dashboard** - Wallet balance monitoring and fund management
-- **Models** - AI model management and testing
-- **Providers** - Upstream provider configuration
-- **Settings** - Node configuration and admin preferences
-
-### Navigation
-
-## Dashboard Page
-
-### Wallet Balance Management
-
-#### Balance Display Options
-
-Switch between display units using the toggle buttons:
-
-- **msat** - Millisatoshis (highest precision)
-- **sat** - Satoshis (standard Bitcoin unit)
-- **usd** - US Dollar equivalent (when exchange rate available)
-
-#### Balance Overview
-
-The dashboard displays three key metrics:
-
-- **Your Balance (Total)** - Available funds for node operator
-- **Total Wallet** - Combined balance across all Cashu mints
-- **User Balance** - Funds held for API key holders
-
-#### Detailed Balance Breakdown
-
-View balances by mint with the following information:
-
-| Column | Description |
-| ----------- | ------------------------------------- |
-| Mint / Unit | Cashu mint URL and currency unit |
-| Wallet | Total funds in this mint |
-| Users | Funds belonging to API key holders |
-| Owner | Your available funds (Wallet - Users) |
-
-### Temporary Balances
-
-Monitor API key activity with:
-
-- **Summary Cards** - Total balance, total spent, total requests
-- **Search Functionality** - Filter by key hash or refund address
-- **Detailed Table** - Individual key balances with expiry times
-- **Auto-refresh** - Updates every 60 seconds
-
-### Fund Management
-
-#### Withdrawing Funds
-
-To withdraw your available balance:
-
-1. Click the **Withdraw** button
-2. Select which mint to withdraw from
-3. Specify the amount (or withdraw full balance)
-4. Click **Generate Token**
-5. Copy the generated eCash token
-6. Import the token into your Cashu wallet
-
-#### Real-time Updates
-
-- Balances refresh automatically every 30 seconds
-- Manual refresh option available
-- Live Bitcoin/USD exchange rate integration
-- Error handling for mint connectivity issues
-
-## Models Management Page
-
-### Model Organization
-
-Models are organized by provider groups with tabs:
-
-- **All Models** - Combined view of all available models
-- **Provider-specific tabs** - Individual providers (OpenRouter, Azure, etc.)
-- Badge indicators showing active/total model counts
-
-### Model Management Features
-
-#### Individual Model Operations
-
-For each model you can:
-
-- **Toggle Enable/Disable** - Control model availability
-- **View Details** - Context length, pricing, description
-- **Edit Configuration** - Model-specific settings
-- **Status Indicators** - Green badges for enabled, gray for disabled
-
-#### Bulk Operations
-
-- **Select All/Deselect All** - Quick selection controls
-- **Bulk Enable/Disable** - Mass model management
-- **Bulk Delete** - Remove model overrides
-- **Provider-level Actions** - Apply settings to all models in a provider
-
-#### Model Information Display
-
-- **Model Types** - Text, embedding, image, audio, multimodal indicators
-- **Pricing Information** - Per-million-token costs for input/output
-- **Context Length** - Maximum tokens supported
-- **API Key Status** - Whether credentials are configured
-- **Free Model Indicators** - No-cost models clearly marked
-
-## Providers Management Page
-
-### Upstream Provider Configuration
-
-Manage AI provider connections and credentials:
-
-#### Provider Types Supported
-
-- **OpenRouter** - Multi-model aggregator
-- **Azure OpenAI** - Microsoft's OpenAI service
-- **OpenAI** - Direct OpenAI integration
-- **Custom Providers** - Any OpenAI-compatible API
-
-#### Adding New Providers
-
-1. Click **Add Provider**
-2. Select **Provider Type** from dropdown
-3. Enter **Base URL** (auto-populated for known providers)
-4. Add **API Key** for authentication
-5. Set **API Version** (required for Azure)
-6. Toggle **Enabled** status
-7. Click **Create**
-
-#### Provider Management
-
-**Provider Cards Display:**
-
-- Provider type and status (Enabled/Disabled)
-- Base URL configuration
-- Action buttons (Models, Edit, Delete)
-
-**Available Actions:**
-
-- **Edit** - Modify provider configuration
-- **Delete** - Remove provider (with confirmation)
-- **View Models** - Expand model discovery interface
-- **Enable/Disable** - Toggle provider availability
-
-#### Model Discovery
-
-Each provider shows two types of models:
-
-**Provided Models Tab:**
-
-- Auto-discovered from provider's catalog
-- Read-only model information
-- Real-time availability updates
-
-**Custom Models Tab:**
-
-- Manually configured model overrides
-- Extend or override provider catalog
-- Individual enable/disable controls
-
-## Settings Page
-
-### Node Configuration
-
-Configure core node settings and preferences:
-
-#### Basic Information
-
-- **Node Name** - Identifier for your node
-- **Node Description** - Descriptive text for your service
-- **HTTP URL** - Public HTTP endpoint
-- **Onion URL** - Tor hidden service address
-
-#### Nostr Integration
-
-- **Public Key (npub)** - Your Nostr public identity
-- **Private Key (nsec)** - Nostr private key with show/hide toggle
-- **Nostr Relays** - Configure relays for provider announcements
-
-#### Cashu Mint Management
-
-- **Add Mint URLs** - Configure multiple Cashu mint endpoints
-- **Remove Mints** - Delete unused mint configurations
-- **Mint Validation** - Verify mint endpoint connectivity
-
-#### Settings Features
-
-- **Real-time Save** - Changes apply immediately
-- **Validation** - Form validation with error feedback
-- **Secure Fields** - Password masking with reveal toggles
-- **Reload Functionality** - Refresh configuration from server
-
-## Next Steps
-
-- [Payment Flow](payment-flow.md) - Understanding Bitcoin payment processing
-- [Using the API](using-api.md) - Making API requests to your node
-- [Models & Pricing](models-pricing.md) - Configuring model pricing and fees
-- [API Reference](../api/overview.md) - Complete API documentation
diff --git a/docs/user-guide/introduction.md b/docs/user-guide/introduction.md
deleted file mode 100644
index c0fbd192..00000000
--- a/docs/user-guide/introduction.md
+++ /dev/null
@@ -1,245 +0,0 @@
-# User Guide Introduction
-
-Welcome to the Routstr Core User Guide. This guide will help you understand how to use Routstr to access AI APIs with Bitcoin micropayments.
-
-## What You'll Learn
-
-- How the payment system works
-- Creating and managing API keys
-- Making API calls through Routstr
-- Using the admin dashboard
-- Managing your balance
-
-## Prerequisites
-
-Before starting, you'll need:
-
-1. **A Running Routstr Instance**
- - Either your own deployment or access to a public node
- - The base URL (e.g., `https://api.routstr.com/v1`)
-
-2. **A Cashu Wallet** (optional but recommended)
- - [Nutstash](https://nutstash.app) - Web wallet
- - [Minibits](https://www.minibits.cash) - Mobile wallet
- - [Cashu.me](https://cashu.me) - Simple web wallet
-
-3. **An API Client**
- - OpenAI Python/JavaScript SDK
- - Any HTTP client (curl, Postman, etc.)
- - Your application code
-
-## How Routstr Works
-
-### Traditional API Access
-
-```mermaid
-graph LR
- A[Your App] --> B[OpenAI API]
- B --> A
-```
-
-- Direct connection to provider
-- Monthly billing
-- Credit card required
-- Usage limits
-
-### With Routstr
-
-```mermaid
-graph LR
- A[Your App] --> B[Routstr Proxy]
- B --> C[OpenAI API]
- C --> B
- B --> A
- D[Bitcoin/eCash] --> B
-```
-
-- Pay per request with Bitcoin
-- No credit card needed
-- Anonymous payments
-- Instant settlement
-
-## Key Concepts
-
-### eCash Tokens
-
-- Digital bearer tokens backed by Bitcoin
-- Can be sent like cash - whoever has the token owns it
-- Redeemable at Cashu mints for Bitcoin
-- Perfect for micropayments
-
-### API Keys
-
-- Created by depositing eCash tokens
-- Track your balance and usage
-- Can be topped up anytime
-- Optional expiry and refund address
-
-### Balance Management
-
-- Measured in millisatoshis (msats)
-- 1 Bitcoin = 100,000,000 sats = 100,000,000,000 msats
-- Deducted based on actual usage
-- Withdrawable as eCash tokens
-
-## Typical Workflow
-
-### 1. Get Bitcoin/eCash
-
-Options:
-
-- Buy Bitcoin and deposit to a Cashu mint
-- Receive eCash tokens from someone else
-- Use a testnet mint for testing
-
-### 2. Use Your eCash
-
-You have two options for using your eCash tokens with Routstr:
-
-#### Option A: Create a Persistent Wallet
-
-Create a wallet with an API key for multiple requests:
-
-```bash
-POST /v1/wallet/create
-{
- "cashu_token": "cashuAeyJ0..."
-}
-```
-
-This returns an API key (`sk-...`) and your balance. The wallet persists between requests.
-
-#### Option B: Direct Token Usage
-
-Use your Cashu token directly as the API key:
-
-```python
-client = OpenAI(
- api_key="cashuAeyJ0...", # Your Cashu token directly
- base_url="https://api.routstr.com/v1"
-)
-```
-
-Routstr automatically converts the token to access the associated wallet. Each request consumes from the token's balance.
-
-### 3. Make API Calls
-
-With either method:
-
-```python
-# Using persistent wallet API key
-client = OpenAI(
- api_key="sk-...",
- base_url="https://api.routstr.com/v1"
-)
-
-# Or using Cashu token directly
-client = OpenAI(
- api_key="cashuAeyJ0...",
- base_url="https://api.routstr.com/v1"
-)
-```
-
-### 4. Monitor Usage
-
-- Check balance: `GET /v1/wallet/balance`
-- View admin dashboard
-- Track costs per request
-
-### 5. Withdraw Funds
-
-When done, withdraw remaining balance as eCash through the admin interface.
-
-## Supported Endpoints
-
-Routstr supports all standard OpenAI endpoints:
-
-- ✅ `/v1/chat/completions` - Chat models
-- 🚧 `/v1/completions` - Text completion (Coming soon)
-- 🚧 `/v1/embeddings` - Text embeddings (Coming soon)
-- 🚧 `/v1/images/generations` - Image generation (Coming soon)
-- 🚧 `/v1/audio/transcriptions` - Audio to text (Coming soon)
-- 🚧 `/v1/audio/translations` - Audio translation (Coming soon)
-- ✅ `/v1/models` - List available models
-- ✅ Custom provider endpoints
-
-## Cost Structure
-
-### Pricing Models
-
-1. **Fixed Cost Per Request**
- - Simple flat fee per API call
- - Good for uniform usage
-
-2. **Token-Based Pricing**
- - Pay per input/output token
- - More accurate for varied usage
-
-3. **Model-Based Pricing**
- - Different rates per model
- - Reflects actual provider costs
-
-### Cost Calculation
-
-```
-Total Cost = Base Fee + (Input Tokens * Input Rate) + (Output Tokens * Output Rate)
-```
-
-Fees may include:
-
-- Exchange rate markup (BTC/USD conversion)
-- Provider margin
-- Node operator fee
-
-## Getting Support
-
-### Documentation
-
-- This user guide for general usage
-- [API Reference](../api/overview.md) for technical details
-- [Contributing Guide](../contributing/setup.md) for developers
-
-### Community
-
-- GitHub Issues for bugs and features
-- Nostr for decentralized discussion
-- Node operator contact info
-
-### Troubleshooting
-
-Common issues and solutions:
-
-- [Payment Flow](payment-flow.md) - Understanding the payment process
-- [Using the API](using-api.md) - API integration guide
-- [Admin Dashboard](admin-dashboard.md) - Managing your node
-
-## Security Considerations
-
-### API Key Security
-
-- Treat API keys like passwords
-- Never share or commit them
-- Rotate keys regularly
-- Use environment variables
-
-### Payment Security
-
-- eCash tokens are bearer instruments
-- Verify mint trustworthiness
-- Keep backups of tokens
-- Use small amounts for testing
-
-### Network Security
-
-- Always use HTTPS connections
-- Verify SSL certificates
-- Consider using Tor for privacy
-- Monitor for unusual activity
-
-## Next Steps
-
-Ready to start? Continue with:
-
-1. [Payment Flow](payment-flow.md) - Detailed payment process
-2. [Using the API](using-api.md) - Making your first calls
-3. [Admin Dashboard](admin-dashboard.md) - Managing your account
diff --git a/docs/user-guide/models-pricing.md b/docs/user-guide/models-pricing.md
deleted file mode 100644
index c5f08850..00000000
--- a/docs/user-guide/models-pricing.md
+++ /dev/null
@@ -1,466 +0,0 @@
-# Models & Pricing
-
-Understanding how Routstr calculates costs is essential for managing your API usage efficiently. This guide explains the pricing models and how to configure them.
-
-## Pricing Models
-
-Routstr supports three pricing models:
-
-### 1. Fixed Pricing
-
-Simple per-request charging:
-
-```bash
-FIXED_PRICING=true
-FIXED_COST_PER_REQUEST=10 # 10 sats per request
-```
-
-**Best for:**
-
-- Uniform API usage
-- Simple applications
-- Predictable costs
-
-### 2. Token-Based Pricing
-
-Charge based on actual token usage:
-
-```bash
-FIXED_PRICING=false # use model pricing
-FIXED_COST_PER_REQUEST=1 # optional base fee
-FIXED_PER_1K_INPUT_TOKENS=5 # optional override
-FIXED_PER_1K_OUTPUT_TOKENS=15 # optional override
-```
-
-**Best for:**
-
-- Varied request sizes
-- Fair usage billing
-- Cost optimization
-
-### 3. Model-Based Pricing
-
-Dynamic pricing based on model costs:
-
-```bash
-FIXED_PRICING=false
-EXCHANGE_FEE=1.005 # 0.5% exchange fee
-UPSTREAM_PROVIDER_FEE=1.05 # 5% provider fee
-```
-
-**Best for:**
-
-- Multiple models
-- Market-based pricing
-- Automatic updates
-
-## Model Configuration
-
-### Default Models
-
-Routstr includes pricing for popular models:
-
-| Model | Input ($/1K) | Output ($/1K) | Context | Notes |
-|-------|--------------|---------------|---------|-------|
-| gpt-3.5-turbo | $0.0015 | $0.002 | 16K | Fast, economical |
-| gpt-4 | $0.03 | $0.06 | 8K | Advanced reasoning |
-| gpt-4-turbo | $0.01 | $0.03 | 128K | Large context |
-| claude-3-opus | $0.015 | $0.075 | 200K | Best quality |
-| claude-3-sonnet | $0.003 | $0.015 | 200K | Balanced |
-| llama-2-70b | $0.0007 | $0.0009 | 4K | Open source |
-
-### Custom Models File
-
-Create `models.json` to override defaults:
-
-```json
-{
- "models": [
- {
- "id": "gpt-4-vision",
- "name": "GPT-4 Vision",
- "pricing": {
- "prompt": "0.00003",
- "completion": "0.00006",
- "request": "0",
- "image": "0.00255"
- },
- "context_length": 128000,
- "supports_vision": true
- },
- {
- "id": "custom-model",
- "name": "My Custom Model",
- "pricing": {
- "prompt": "0.001",
- "completion": "0.002",
- "request": "0.0001"
- },
- "context_length": 8192
- }
- ]
-}
-```
-
-### Auto-updating Models
-
-Fetch latest models from OpenRouter:
-
-```bash
-# Update models from API
-python scripts/models_meta.py
-
-# Or manually
-curl https://openrouter.ai/api/v1/models > models.json
-```
-
-## Cost Calculation
-
-### Understanding the Formula
-
-```
-Base Cost = (Input Tokens × Input Rate) + (Output Tokens × Output Rate) + Request Fee
-
-Bitcoin Price = Current BTC/USD rate (e.g., $50,000)
-Sats Cost = (Base Cost / Bitcoin Price) × 100,000,000
-
-Final Cost = Sats Cost × Exchange Fee × Provider Fee
-```
-
-### Example Calculations
-
-**Example 1: Simple Chat (gpt-3.5-turbo)**
-
-```
-Input: 50 tokens
-Output: 150 tokens
-Model rates: $0.0015/1K input, $0.002/1K output
-
-USD Cost = (50/1000 × 0.0015) + (150/1000 × 0.002)
- = $0.000075 + $0.0003
- = $0.000375
-
-At $50,000/BTC: 0.75 sats
-With 5.5% total fees: 0.79 sats
-```
-
-**Example 2: Large Context (gpt-4)**
-
-```
-Input: 2,000 tokens
-Output: 500 tokens
-Model rates: $0.03/1K input, $0.06/1K output
-
-USD Cost = (2000/1000 × 0.03) + (500/1000 × 0.06)
- = $0.06 + $0.03
- = $0.09
-
-At $50,000/BTC: 180 sats
-With 5.5% total fees: 190 sats
-```
-
-**Example 3: Image Generation (dall-e-3)**
-
-```
-Model: dall-e-3
-Size: 1024x1024
-Quality: standard
-Cost: $0.04 per image
-
-At $50,000/BTC: 80 sats
-With 5.5% fees: 84 sats
-```
-
-## Fee Structure
-
-### Exchange Fee
-
-Covers Bitcoin/USD conversion costs:
-
-```bash
-EXCHANGE_FEE=1.005 # 0.5% default
-```
-
-Factors:
-
-- Exchange rate volatility
-- Conversion costs
-- Price update frequency
-
-### Provider Fee
-
-Node operator's margin:
-
-```bash
-UPSTREAM_PROVIDER_FEE=1.05 # 5% default
-```
-
-Covers:
-
-- Infrastructure costs
-- Maintenance
-- Support
-- Profit margin
-
-### Calculating Total Fees
-
-```
-Total Multiplier = EXCHANGE_FEE × UPSTREAM_PROVIDER_FEE
-Example: 1.005 × 1.05 = 1.05525 (5.525% total)
-```
-
-## Special Pricing
-
-### Image Models
-
-Image generation uses per-image pricing:
-
-| Model | Size | Quality | Price |
-|-------|------|---------|-------|
-| dall-e-2 | 256x256 | - | $0.016 |
-| dall-e-2 | 512x512 | - | $0.018 |
-| dall-e-2 | 1024x1024 | - | $0.02 |
-| dall-e-3 | 1024x1024 | standard | $0.04 |
-| dall-e-3 | 1024x1024 | hd | $0.08 |
-| dall-e-3 | 1024x1792 | standard | $0.08 |
-| dall-e-3 | 1024x1792 | hd | $0.12 |
-
-### Audio Models
-
-Audio pricing by duration:
-
-| Model | Type | Price |
-|-------|------|-------|
-| whisper-1 | Transcription | $0.006/minute |
-| whisper-1 | Translation | $0.006/minute |
-| tts-1 | Text-to-speech | $0.015/1K chars |
-| tts-1-hd | HD speech | $0.03/1K chars |
-
-### Embedding Models
-
-Lower costs for embeddings:
-
-| Model | Price/1K tokens |
-|-------|-----------------|
-| text-embedding-3-small | $0.00002 |
-| text-embedding-3-large | $0.00013 |
-| text-embedding-ada-002 | $0.0001 |
-
-## Monitoring Costs
-
-### Per-Request Tracking
-
-Each API response includes usage data:
-
-```json
-{
- "usage": {
- "prompt_tokens": 50,
- "completion_tokens": 150,
- "total_tokens": 200
- },
- "x-routstr-cost": {
- "sats": 79,
- "usd": 0.000375,
- "breakdown": {
- "prompt_cost": 15,
- "completion_cost": 60,
- "fees": 4
- }
- }
-}
-```
-
-### Daily Summaries
-
-View in admin dashboard:
-
-- Total requests
-- Token usage by model
-- Cost distribution
-- Trending patterns
-
-### Cost Alerts
-
-Set up notifications:
-
-```python
-# Example monitoring script
-def check_daily_spend(api_key):
- balance_start = get_balance(api_key, "00:00")
- balance_now = get_balance(api_key)
- spent = balance_start - balance_now
-
- if spent > DAILY_LIMIT:
- send_alert(f"Daily spend exceeded: {spent} sats")
-```
-
-## Optimization Strategies
-
-### Model Selection
-
-Choose the right model for each task:
-
-| Task | Recommended Model | Why |
-|------|-------------------|-----|
-| Simple Q&A | gpt-3.5-turbo | Fast, cheap, sufficient |
-| Code generation | gpt-4 | Better reasoning |
-| Summarization | claude-3-haiku | Good balance |
-| Creative writing | claude-3-opus | Best quality |
-| Embeddings | text-embedding-3-small | Optimized for vectors |
-
-### Prompt Engineering
-
-Reduce costs with efficient prompts:
-
-```python
-# Expensive
-prompt = """
-You are an AI assistant. Your task is to help users.
-Please provide detailed, comprehensive answers.
-Now, answer this question: What is 2+2?
-"""
-
-# Economical
-prompt = "Calculate: 2+2"
-```
-
-### Caching Strategies
-
-Implement smart caching:
-
-```python
-# Cache embedding results
-@lru_cache(maxsize=1000)
-def get_embedding(text):
- return client.embeddings.create(
- model="text-embedding-3-small",
- input=text
- )
-
-# Cache common responses
-COMMON_RESPONSES = {
- "greeting": "Hello! How can I help you?",
- "goodbye": "Goodbye! Have a great day!"
-}
-```
-
-### Batch Processing
-
-Process multiple items efficiently:
-
-```python
-# Instead of multiple calls
-for item in items:
- response = client.chat.completions.create(...)
-
-# Use single call with formatted prompt
-prompt = "\n".join([f"{i+1}. {item}" for i, item in enumerate(items)])
-response = client.chat.completions.create(
- messages=[{"role": "user", "content": f"Process these items:\n{prompt}"}]
-)
-```
-
-## Custom Pricing Rules
-
-### Time-Based Pricing
-
-Implement off-peak discounts:
-
-```python
-def calculate_multiplier():
- hour = datetime.now().hour
- if 2 <= hour <= 6: # 2 AM - 6 AM
- return 0.8 # 20% discount
- elif 18 <= hour <= 22: # 6 PM - 10 PM
- return 1.2 # 20% premium
- return 1.0
-```
-
-### Model-Specific Rules
-
-Custom pricing logic:
-
-```python
-def adjust_model_price(model, base_price):
- # Premium for latest models
- if "turbo" in model or "latest" in model:
- return base_price * 1.1
-
- # Discount for older models
- if "legacy" in model:
- return base_price * 0.8
-
- return base_price
-```
-
-## Pricing Transparency
-
-### Public Pricing Page
-
-Display current rates:
-
-```html
-
-
-
- | Model |
- Input (sats/1K) |
- Output (sats/1K) |
-
-
-
-```
-
-### Cost Estimation API
-
-Provide cost estimates:
-
-```bash
-POST /v1/estimate
-{
- "model": "gpt-4",
- "prompt_tokens": 500,
- "max_tokens": 200
-}
-
-Response:
-{
- "estimated_cost_sats": 45,
- "breakdown": {
- "prompt": 30,
- "completion": 12,
- "fees": 3
- }
-}
-```
-
-## Troubleshooting
-
-### Pricing Mismatches
-
-**Issue**: Costs don't match expectations
-
-- Check current BTC/USD rate
-- Verify fee settings
-- Review model configuration
-
-**Issue**: Models not found
-
-- Update models.json
-- Check model ID spelling
-- Verify upstream support
-
-### Fee Calculations
-
-**Issue**: Fees seem too high
-
-- Review EXCHANGE_FEE setting
-- Check UPSTREAM_PROVIDER_FEE
-- Calculate total multiplier
-
-## Next Steps
-
-- [API Reference](../api/overview.md) - Technical details
-- [Custom Pricing](../advanced/custom-pricing.md) - Advanced configuration
-- [Contributing](../contributing/setup.md) - Help improve Routstr
diff --git a/docs/user-guide/payment-flow.md b/docs/user-guide/payment-flow.md
deleted file mode 100644
index 87784500..00000000
--- a/docs/user-guide/payment-flow.md
+++ /dev/null
@@ -1,373 +0,0 @@
-# Payment Flow
-
-Understanding how payments work in Routstr is key to using the system effectively. This guide explains the payment process in detail.
-
-## Overview
-
-Routstr uses a pre-funded account model where:
-
-1. Users deposit eCash tokens to create an API key
-2. Each API request deducts from the balance
-3. Users can withdraw remaining balance as eCash
-
-## Creating an API Key
-
-### Step 1: Obtain eCash Token
-
-Get a Cashu token from any compatible source:
-
-**Option A: From a Cashu Wallet**
-
-```bash
-# Example: Creating a 10,000 sat token
-cashu send 10000
-```
-
-**Option B: Lightning Invoice**
-
-```bash
-# Some mints support direct Lightning deposits
-curl -X POST https://mint.example.com/v1/mint/quote/bolt11 \
- -d '{"amount": 10000, "unit": "sat"}'
-```
-
-**Option C: Test Tokens**
-
-```bash
-# Get test tokens from testnet mints
-# Check mint documentation for faucets
-```
-
-### Step 2: Create API Key
-
-**Note: The POST /v1/wallet/create endpoint is coming soon. Currently, you can use Cashu tokens directly as API keys in the Authorization header.**
-
-Send your token to Routstr:
-
-```bash
-curl -X POST https://api.routstr.com/v1/wallet/create \
- -H "Content-Type: application/json" \
- -d '{
- "cashu_token": "cashuAeyJ0b2tlbiI6W3sibWludCI6Imh0dHBzOi8vbWlu..."
- }'
-```
-
-**Request Parameters:**
-
-- `cashu_token` (required): The eCash token to deposit
-
-**Response:**
-
-```json
-{
- "api_key": "sk-1234567890abcdef",
- "balance": 10000000,
- "created_at": "2024-01-01T00:00:00Z"
-}
-```
-
-### Step 3: Verify Balance
-
-Check your key's balance:
-
-```bash
-curl -X GET https://api.routstr.com/v1/wallet/balance \
- -H "Authorization: Bearer sk-1234567890abcdef"
-```
-
-Response:
-
-```json
-{
- "balance": 10000000,
- "total_deposited": 10000000,
- "total_spent": 0,
- "last_used": null
-}
-```
-
-## Making API Requests
-
-### Cost Calculation
-
-Costs are calculated based on:
-
-1. **Request Type**
- - Chat completions
- - Embeddings
- - Image generation
- - Audio processing
-
-2. **Token Usage**
- - Input tokens (prompt)
- - Output tokens (response)
- - Model-specific rates
-
-3. **Additional Costs**
- - Base request fee
- - Image generation fees
- - Audio processing time
-
-### Example: Chat Completion
-
-```python
-import openai
-
-client = openai.OpenAI(
- api_key="sk-1234567890abcdef",
- base_url="https://api.routstr.com/v1"
-)
-
-# Make request
-response = client.chat.completions.create(
- model="gpt-3.5-turbo",
- messages=[
- {"role": "user", "content": "Hello, how are you?"}
- ]
-)
-
-# Check usage
-print(f"Input tokens: {response.usage.prompt_tokens}")
-print(f"Output tokens: {response.usage.completion_tokens}")
-print(f"Total tokens: {response.usage.total_tokens}")
-```
-
-### Cost Breakdown
-
-For the above request:
-
-```
-Model: gpt-3.5-turbo
-Input tokens: 13
-Output tokens: 27
-Model rates: $0.0015/1K input, $0.002/1K output
-
-USD Cost = (13/1000 * 0.0015) + (27/1000 * 0.002) = $0.0000735
-BTC/USD Rate: $50,000
-BTC Cost = 0.0000735 / 50000 = 0.00000000147 BTC = 147 sats
-With fees (5%): 154 sats
-
-Final cost: 154 sats
-```
-
-## Balance Management
-
-### Monitoring Usage
-
-Track your usage in real-time:
-
-```bash
-# Get current balance
-curl -X GET https://api.routstr.com/v1/wallet/balance \
- -H "Authorization: Bearer your-api-key"
-
-# View recent transactions (through admin dashboard)
-# Access at https://api.routstr.com/admin/
-```
-
-### Low Balance Handling
-
-When balance is insufficient:
-
-```json
-{
- "error": {
- "type": "insufficient_balance",
- "message": "Insufficient balance. Current: 100 sats, Required: 154 sats",
- "code": "payment_required"
- }
-}
-```
-
-### Topping Up
-
-Add funds to existing key:
-
-```bash
-curl -X POST https://api.routstr.com/v1/wallet/topup \
- -H "Authorization: Bearer your-api-key" \
- -H "Content-Type: application/json" \
- -d '{
- "cashu_token": "cashuAeyJ0b2..."
- }'
-```
-
-## Withdrawing Balance
-
-### Via Admin Dashboard
-
-1. Navigate to `/admin/`
-2. Enter admin password
-3. Find your API key
-4. Click "Withdraw"
-5. Receive eCash token
-
-### Via API (if enabled)
-
-```bash
-curl -X POST https://api.routstr.com/v1/wallet/withdraw \
- -H "Authorization: Bearer your-api-key" \
- -H "Content-Type: application/json" \
- -d '{
- "amount": 5000,
- "mint": "https://mint.minibits.cash/Bitcoin"
- }'
-```
-
-## Payment Security
-
-### Token Validation
-
-Routstr validates tokens by:
-
-1. Checking signature validity
-2. Verifying with the issuing mint
-3. Ensuring no double-spending
-4. Confirming sufficient value
-
-### Failed Payments
-
-Common failure reasons:
-
-- Invalid token signature
-- Already spent token
-- Untrusted mint
-- Network issues with mint
-
-### Refund Policy
-
-- Unused balance can be withdrawn anytime
-- Expired keys with balance can be refunded
-- Node operators may have additional policies
-
-## Advanced Features
-
-### Multi-Mint Support
-
-Routstr accepts tokens from multiple mints:
-
-```bash
-CASHU_MINTS=https://mint1.com,https://mint2.com,https://mint3.com
-```
-
-Benefits:
-
-- Redundancy if one mint is down
-- User choice of mints
-- Geographic distribution
-
-### Automatic Payouts
-
-Configure automatic Lightning payouts:
-
-```bash
-RECEIVE_LN_ADDRESS=satoshi@getalby.com
-```
-
-When enabled:
-
-- Balances above threshold are swept
-- Converted to Lightning payments
-- Sent to configured address
-
-### Per-Request Payments (Coming Soon)
-
-Future support for Nut-24 headers:
-
-```bash
-curl -X POST https://api.routstr.com/v1/chat/completions \
- -H "x-cashu: cashuAeyJ0..." \
- -H "Content-Type: application/json" \
- -d '{...}'
-```
-
-Response includes change:
-
-```
-HTTP/1.1 200 OK
-x-cashu: cashuAeyJjaGFuZ2Ui...
-```
-
-## Best Practices
-
-### API Key Management
-
-1. **Separate Keys per Application**
- - Easier tracking
- - Better security
- - Independent budgets
-
-2. **Set Expiration Dates**
- - Automatic cleanup
- - Security improvement
- - Budget control
-
-3. **Monitor Balances**
- - Set up alerts
- - Regular checks
- - Usage analytics
-
-### Cost Optimization
-
-1. **Choose Appropriate Models**
- - Smaller models for simple tasks
- - Larger models only when needed
-
-2. **Optimize Prompts**
- - Concise, clear instructions
- - Avoid unnecessary tokens
-
-3. **Use Streaming**
- - Early termination possible
- - Better user experience
-
-### Security
-
-1. **Secure Storage**
- - Environment variables
- - Secrets management
- - Never in code
-
-2. **Network Security**
- - Always use HTTPS
- - Verify certificates
- - Consider Tor for privacy
-
-3. **Regular Rotation**
- - Change keys periodically
- - Withdraw unused funds
- - Audit usage logs
-
-## Troubleshooting
-
-### Payment Rejected
-
-**Error:** "Invalid token"
-
-- Check token format
-- Verify mint is trusted
-- Ensure not already spent
-
-**Error:** "Insufficient value"
-
-- Token value too low
-- Check current pricing
-- Add larger token
-
-### Balance Discrepancies
-
-- Allow for price fluctuations
-- Check model pricing updates
-- Review transaction history
-
-### Mint Issues
-
-- Try different mint from list
-- Check mint status
-- Contact mint operator
-
-## Next Steps
-
-- [Using the API](using-api.md) - Integration guide
-- [Admin Dashboard](admin-dashboard.md) - Account management
-- [Models & Pricing](models-pricing.md) - Cost details
diff --git a/docs/user-guide/using-api.md b/docs/user-guide/using-api.md
deleted file mode 100644
index 5ad32509..00000000
--- a/docs/user-guide/using-api.md
+++ /dev/null
@@ -1,545 +0,0 @@
-# Using the API
-
-This guide shows how to integrate Routstr with your applications using various programming languages and tools.
-
-## API Compatibility
-
-Routstr maintains full compatibility with the OpenAI API, meaning:
-
-- Existing OpenAI client libraries work without modification
-- Only the base URL and API key need to change
-- All parameters and responses match OpenAI's format
-
-## Basic Setup
-
-### Python
-
-Using the official OpenAI Python library:
-
-```python
-from openai import OpenAI
-
-# Initialize client with Routstr endpoint
-client = OpenAI(
- api_key="sk-...",
- base_url="https://api.routstr.com/v1"
-)
-
-# Use exactly like OpenAI
-response = client.chat.completions.create(
- model="gpt-3.5-turbo",
- messages=[
- {"role": "system", "content": "You are a helpful assistant."},
- {"role": "user", "content": "Hello!"}
- ]
-)
-
-print(response.choices[0].message.content)
-```
-
-### JavaScript/TypeScript
-
-Using the official OpenAI Node.js library:
-
-```javascript
-import OpenAI from 'openai';
-
-// Initialize client
-const openai = new OpenAI({
- apiKey: 'sk-...',
- baseURL: 'https://api.routstr.com/v1'
-});
-
-// Make a request
-async function main() {
- const completion = await openai.chat.completions.create({
- model: 'gpt-3.5-turbo',
- messages: [
- { role: 'system', content: 'You are a helpful assistant.' },
- { role: 'user', content: 'Hello!' }
- ]
- });
-
- console.log(completion.choices[0].message.content);
-}
-
-main();
-```
-
-### cURL
-
-Direct HTTP requests:
-
-```bash
-curl https://api.routstr.com/v1/chat/completions \
- -H "Content-Type: application/json" \
- -H "Authorization: Bearer sk-..." \
- -d '{
- "model": "gpt-3.5-turbo",
- "messages": [
- {"role": "user", "content": "Hello!"}
- ]
- }'
-```
-
-## Common Use Cases
-
-### Chat Completions
-
-Standard chat with conversation history:
-
-```python
-messages = []
-
-def chat(user_input):
- # Add user message
- messages.append({"role": "user", "content": user_input})
-
- # Get AI response
- response = client.chat.completions.create(
- model="gpt-3.5-turbo",
- messages=messages,
- temperature=0.7,
- max_tokens=150
- )
-
- # Add AI response to history
- ai_message = response.choices[0].message
- messages.append({"role": "assistant", "content": ai_message.content})
-
- return ai_message.content
-
-# Usage
-print(chat("What's the weather like?"))
-print(chat("How should I dress?")) # Maintains context
-```
-
-### Streaming Responses
-
-For real-time output:
-
-```python
-stream = client.chat.completions.create(
- model="gpt-3.5-turbo",
- messages=[{"role": "user", "content": "Write a short story"}],
- stream=True
-)
-
-for chunk in stream:
- if chunk.choices[0].delta.content is not None:
- print(chunk.choices[0].delta.content, end="", flush=True)
-```
-
-### Function Calling
-
-Using OpenAI's function calling feature:
-
-```python
-tools = [{
- "type": "function",
- "function": {
- "name": "get_weather",
- "description": "Get current weather",
- "parameters": {
- "type": "object",
- "properties": {
- "location": {"type": "string"},
- "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
- },
- "required": ["location"]
- }
- }
-}]
-
-response = client.chat.completions.create(
- model="gpt-4",
- messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
- tools=tools,
- tool_choice="auto"
-)
-
-# Check if function was called
-if response.choices[0].message.tool_calls:
- tool_call = response.choices[0].message.tool_calls[0]
- print(f"Function: {tool_call.function.name}")
- print(f"Arguments: {tool_call.function.arguments}")
-```
-
-### Embeddings
-
-Generate text embeddings:
-
-```python
-response = client.embeddings.create(
- model="text-embedding-3-small",
- input="The quick brown fox jumps over the lazy dog"
-)
-
-embedding = response.data[0].embedding
-print(f"Embedding dimension: {len(embedding)}")
-```
-
-### Image Generation
-
-Create images with DALL-E:
-
-```python
-response = client.images.generate(
- model="dall-e-3",
- prompt="A futuristic city with flying cars",
- size="1024x1024",
- quality="standard",
- n=1
-)
-
-image_url = response.data[0].url
-print(f"Image URL: {image_url}")
-```
-
-### Audio Transcription
-
-Convert speech to text:
-
-```python
-with open("audio.mp3", "rb") as audio_file:
- response = client.audio.transcriptions.create(
- model="whisper-1",
- file=audio_file,
- response_format="text"
- )
-
-print(response.text)
-```
-
-## Error Handling
-
-### Balance Errors
-
-Handle insufficient balance gracefully:
-
-```python
-try:
- response = client.chat.completions.create(
- model="gpt-4",
- messages=[{"role": "user", "content": "Hello"}]
- )
-except Exception as e:
- if "insufficient_balance" in str(e):
- print("Low balance! Please top up your API key.")
- # Implement top-up logic
- else:
- raise
-```
-
-### Rate Limiting
-
-Implement exponential backoff:
-
-```python
-import time
-from typing import Optional
-
-def make_request_with_retry(
- func,
- max_retries: int = 3,
- initial_delay: float = 1.0
-) -> Optional[any]:
- for attempt in range(max_retries):
- try:
- return func()
- except Exception as e:
- if "rate_limit" in str(e) and attempt < max_retries - 1:
- delay = initial_delay * (2 ** attempt)
- print(f"Rate limited. Waiting {delay}s...")
- time.sleep(delay)
- else:
- raise
- return None
-```
-
-### Connection Errors
-
-Handle network issues:
-
-```python
-import httpx
-
-# Configure timeout and retries
-client = OpenAI(
- api_key="sk-...",
- base_url="https://your-node.com/v1",
- timeout=httpx.Timeout(60.0, connect=5.0),
- max_retries=2
-)
-```
-
-## Advanced Features
-
-### Using Tor
-
-Route requests through Tor for privacy:
-
-```python
-import httpx
-
-# Configure Tor proxy
-proxies = {
- "http://": "socks5://127.0.0.1:9050",
- "https://": "socks5://127.0.0.1:9050"
-}
-
-http_client = httpx.Client(proxies=proxies)
-
-client = OpenAI(
- api_key="sk-...",
- base_url="http://your-onion-address.onion/v1",
- http_client=http_client
-)
-```
-
-### Custom Headers
-
-Add custom headers if needed:
-
-```python
-import httpx
-
-class CustomClient(httpx.Client):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.headers["X-Custom-Header"] = "value"
-
-client = OpenAI(
- api_key="sk-...",
- base_url="https://your-node.com/v1",
- http_client=CustomClient()
-)
-```
-
-### Azure OpenAI compatibility
-
-To use Azure OpenAI through Routstr with minimal changes:
-
-- Set `UPSTREAM_BASE_URL` to your Azure deployments URL, for example: `https://.openai.azure.com/openai/deployments/`
-- Set `CHAT_COMPLETIONS_API_VERSION=2024-05-01-preview`
-
-When this env var is set, Routstr automatically appends `api-version=2024-05-01-preview` to all upstream `/chat/completions` requests.
-
-### Async Operations
-
-For high-performance applications:
-
-```python
-import asyncio
-from openai import AsyncOpenAI
-
-async_client = AsyncOpenAI(
- api_key="sk-...",
- base_url="https://your-node.com/v1"
-)
-
-async def process_messages(messages):
- tasks = []
- for msg in messages:
- task = async_client.chat.completions.create(
- model="gpt-3.5-turbo",
- messages=[{"role": "user", "content": msg}]
- )
- tasks.append(task)
-
- responses = await asyncio.gather(*tasks)
- return [r.choices[0].message.content for r in responses]
-
-# Run async
-messages = ["Hello", "How are you?", "What's 2+2?"]
-results = asyncio.run(process_messages(messages))
-```
-
-## Best Practices
-
-### 1. Environment Variables
-
-Never hardcode API keys:
-
-```python
-import os
-from openai import OpenAI
-
-client = OpenAI(
- api_key=os.getenv("ROUTSTR_API_KEY"),
- base_url=os.getenv("ROUTSTR_BASE_URL", "https://api.routstr.com/v1")
-)
-```
-
-### 2. Error Logging
-
-Implement comprehensive logging:
-
-```python
-import logging
-
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
-
-try:
- response = client.chat.completions.create(...)
- logger.info(f"Request successful. Tokens used: {response.usage.total_tokens}")
-except Exception as e:
- logger.error(f"API request failed: {e}")
- raise
-```
-
-### 3. Cost Tracking
-
-Monitor your usage:
-
-```python
-class UsageTracker:
- def __init__(self):
- self.total_tokens = 0
- self.total_requests = 0
-
- def track(self, response):
- self.total_tokens += response.usage.total_tokens
- self.total_requests += 1
-
- # Estimate cost (example rates)
- cost_per_1k = 0.002 # $0.002 per 1K tokens
- estimated_cost = (self.total_tokens / 1000) * cost_per_1k
-
- logger.info(f"Total usage: {self.total_tokens} tokens, "
- f"${estimated_cost:.4f} (~{estimated_cost * 50000:.0f} sats)")
-
-tracker = UsageTracker()
-response = client.chat.completions.create(...)
-tracker.track(response)
-```
-
-### 4. Caching Responses
-
-Reduce costs with intelligent caching:
-
-```python
-import hashlib
-import json
-from functools import lru_cache
-
-@lru_cache(maxsize=100)
-def cached_completion(prompt: str, model: str = "gpt-3.5-turbo"):
- response = client.chat.completions.create(
- model=model,
- messages=[{"role": "user", "content": prompt}],
- temperature=0 # Deterministic for caching
- )
- return response.choices[0].message.content
-
-# Repeated calls with same prompt use cache
-result1 = cached_completion("What is 2+2?")
-result2 = cached_completion("What is 2+2?") # From cache, no API call
-```
-
-## Testing
-
-### Mock Responses
-
-For development without spending sats:
-
-```python
-class MockOpenAI:
- class Completions:
- def create(self, **kwargs):
- return type('Response', (), {
- 'choices': [type('Choice', (), {
- 'message': type('Message', (), {
- 'content': 'Mock response'
- })()
- })],
- 'usage': type('Usage', (), {
- 'total_tokens': 10
- })()
- })()
-
- def __init__(self):
- self.chat = type('Chat', (), {
- 'completions': self.Completions()
- })()
-
-# Use mock in tests
-if os.getenv('TESTING'):
- client = MockOpenAI()
-else:
- client = OpenAI(...)
-```
-
-### Integration Tests
-
-Test your Routstr integration:
-
-```python
-def test_routstr_connection():
- try:
- # Test models endpoint
- models = client.models.list()
- assert len(models.data) > 0
-
- # Test simple completion
- response = client.chat.completions.create(
- model="gpt-3.5-turbo",
- messages=[{"role": "user", "content": "test"}],
- max_tokens=5
- )
- assert response.choices[0].message.content
-
- print("✅ Routstr integration working!")
- return True
- except Exception as e:
- print(f"❌ Integration test failed: {e}")
- return False
-```
-
-## Troubleshooting
-
-### Common Issues
-
-**SSL Certificate Errors**
-
-```python
-# For development only - not for production!
-import ssl
-import httpx
-
-client = OpenAI(
- api_key="sk-...",
- base_url="https://localhost:8000/v1",
- http_client=httpx.Client(verify=False)
-)
-```
-
-**Timeout Issues**
-
-```python
-# Increase timeout for slow connections
-client = OpenAI(
- api_key="sk-...",
- base_url="https://your-node.com/v1",
- timeout=httpx.Timeout(120.0) # 2 minutes
-)
-```
-
-**Debugging Requests**
-
-```python
-import logging
-import httpx
-
-# Enable debug logging
-logging.basicConfig(level=logging.DEBUG)
-httpx_logger = logging.getLogger("httpx")
-httpx_logger.setLevel(logging.DEBUG)
-```
-
-## Next Steps
-
-- [Admin Dashboard](admin-dashboard.md) - Manage your account
-- [Models & Pricing](models-pricing.md) - Understanding costs
-- [API Reference](../api/overview.md) - Technical details
diff --git a/mkdocs.yml b/mkdocs.yml
index b8cbfaac..9221c714 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -77,29 +77,27 @@ extra:
nav:
- Home: index.md
- - Getting Started:
- - Overview: getting-started/overview.md
- - Quick Start: getting-started/quickstart.md
- - Docker Setup: getting-started/docker.md
- - Configuration: getting-started/configuration.md
- - User Guide:
- - Introduction: user-guide/introduction.md
- - Payment Flow: user-guide/payment-flow.md
- - Using the API: user-guide/using-api.md
- - Admin Dashboard: user-guide/admin-dashboard.md
- - Models & Pricing: user-guide/models-pricing.md
- - Contributing:
- - Setup Development: contributing/setup.md
- - Architecture: contributing/architecture.md
- - Code Structure: contributing/code-structure.md
- - Testing: contributing/testing.md
+ - Overview: overview.md
+ - Client Guide:
+ - Introduction: client/introduction.md
+ - Payment Flow: client/payments.md
+ - Integration: client/integration.md
+ - Provider Guide:
+ - Quick Start: provider/quickstart.md
+ - Dashboard: provider/dashboard.md
+ - Deployment: provider/deployment.md
+ - Configuration: provider/configuration.md
+ - Pricing: provider/pricing.md
+ - Advanced Pricing: provider/advanced-pricing.md
+ - Discovery: provider/discovery.md
+ - Tor Support: provider/tor.md
- API Reference:
- Overview: api/overview.md
- Authentication: api/authentication.md
- Endpoints: api/endpoints.md
- Errors: api/errors.md
- - Advanced:
- - Tor Support: advanced/tor.md
- - Nostr Discovery: advanced/nostr.md
- - Custom Pricing: advanced/custom-pricing.md
- - Migrations: advanced/migrations.md
+ - Contributing:
+ - Setup Development: contributing/setup.md
+ - Architecture: contributing/architecture.md
+ - Code Structure: contributing/code-structure.md
+ - Testing: contributing/testing.md