Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# API Keys
GOOGLE_API_KEY=your_key_here

# Application Settings
APP_SECRET=your_secret_here

# URLs and Origins
CORS_ORIGINS=http://localhost:3000
API_URL=http://localhost:8000
39 changes: 39 additions & 0 deletions .env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# API Configuration
API_URL=https://chat-app-backend.fly.dev
API_PORT=8000

# Frontend Configuration
FRONTEND_URL=https://chat-app-frontend.fly.dev
FRONTEND_PORT=80

# Database Configuration
DATABASE_URL=postgresql://user:password@host:5432/dbname
DATABASE_SSL_MODE=require

# Authentication
JWT_SECRET=your-jwt-secret-here
JWT_EXPIRATION=24h

# Service API Keys
OPENAI_API_KEY=your-openai-api-key
ANTHROPIC_API_KEY=your-anthropic-api-key

# Monitoring and Logging
SENTRY_DSN=your-sentry-dsn
LOG_LEVEL=info

# Redis Configuration (if needed)
REDIS_URL=redis://user:password@host:6379

# Fly.io Specific
FLY_API_TOKEN=your-fly-api-token
FLY_REGION=your-preferred-region

# Security
CORS_ORIGINS=https://chat-app-frontend.fly.dev
RATE_LIMIT_REQUESTS=100
RATE_LIMIT_PERIOD=60

# Feature Flags
ENABLE_CACHE=true
ENABLE_RATE_LIMITING=true
72 changes: 35 additions & 37 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: CI
name: CI/CD

on:
push:
Expand All @@ -7,41 +7,39 @@ on:
branches: [ main ]

jobs:
build:

test:
runs-on: ubuntu-latest

strategy:
matrix:
node-version: [14.x, 16.x]
python-version: [3.8, 3.9, 3.10]

steps:
- uses: actions/checkout@v3

- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}

- name: Install Dependencies (Node.js)
run: |
npm install

- name: Install Dependencies (Python)
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt

- name: Run Tests (Node.js)
run: |
npm test

- name: Run Tests (Python)
run: |
pytest
- uses: actions/checkout@v2

- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.9'

- name: Install Poetry
run: pip install poetry

- name: Install dependencies
run: |
cd backend
poetry install

- name: Run tests
run: |
cd backend
poetry run pytest

deploy:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2

- uses: superfly/flyctl-actions/setup-flyctl@master

- name: Deploy to fly.io
run: flyctl deploy --remote-only
env:
FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}
71 changes: 71 additions & 0 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Base image for both dev and prod
FROM python:3.9-slim as python-base
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PIP_NO_CACHE_DIR=off \
PIP_DISABLE_PIP_VERSION_CHECK=on \
PIP_DEFAULT_TIMEOUT=100 \
POETRY_VERSION=1.4.2 \
POETRY_HOME="/opt/poetry" \
POETRY_VIRTUALENVS_IN_PROJECT=true \
POETRY_NO_INTERACTION=1 \
PYSETUP_PATH="/opt/pysetup" \
VENV_PATH="/opt/pysetup/.venv"

ENV PATH="$POETRY_HOME/bin:$VENV_PATH/bin:$PATH"

# Builder stage
FROM python-base as builder
RUN apt-get update \
&& apt-get install --no-install-recommends -y \
curl \
build-essential

# Install poetry
RUN curl -sSL https://install.python-poetry.org | python3 -

# Copy project dependency files
WORKDIR $PYSETUP_PATH
COPY poetry.lock pyproject.toml ./

# Install runtime deps
RUN poetry install --no-dev

# Development image
FROM python-base as development
ENV FASTAPI_ENV=development

WORKDIR $PYSETUP_PATH

# Copy dependencies from builder
COPY --from=builder $POETRY_HOME $POETRY_HOME
COPY --from=builder $PYSETUP_PATH $PYSETUP_PATH

# Copy application code
COPY . .

EXPOSE 8000

CMD ["poetry", "run", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]

# Production image
FROM python:3.9-slim as production
ENV FASTAPI_ENV=production

WORKDIR /app

# Copy only necessary files from builder
COPY --from=builder /opt/pysetup/.venv /app/.venv
COPY . .

ENV PATH="/app/.venv/bin:$PATH"

# Create non-root user
RUN useradd -m -u 1000 appuser && \
chown -R appuser:appuser /app

USER appuser

EXPOSE 8000

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
1 change: 1 addition & 0 deletions backend/app/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""FastAPI backend application package."""
28 changes: 28 additions & 0 deletions backend/app/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from pydantic_settings import BaseSettings
from typing import List
from datetime import timedelta

class Settings(BaseSettings):
"""Application settings."""

# API Configuration
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "SPARC API"

# CORS
CORS_ORIGINS: List[str] = ["http://localhost:3000"]

# LLM Configuration
GOOGLE_API_KEY: str
DEFAULT_MODEL: str = "gemini-pro"

# API Key Configuration
API_KEY_ENCRYPTION_KEY: str
API_KEY_EXPIRATION: timedelta = timedelta(days=90)
API_RATE_LIMIT_MINUTE: int = 60
API_RATE_LIMIT_HOUR: int = 1000
API_RATE_LIMIT_DAY: int = 10000

class Config:
env_file = ".env"
case_sensitive = True
15 changes: 15 additions & 0 deletions backend/app/dependencies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from fastapi import Depends, HTTPException, status
from .services.llm.factory import LLMFactory
from .config import Settings

settings = Settings()

def get_llm_service():
"""Dependency for LLM service."""
try:
return LLMFactory.create("gemini", settings.GOOGLE_API_KEY)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=f"LLM service unavailable: {str(e)}"
)
Empty file.
40 changes: 40 additions & 0 deletions backend/app/dependencies/backend/app/dependencies/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from fastapi import Depends, HTTPException, Security
from fastapi.security.api_key import APIKeyHeader
from starlette.status import HTTP_403_FORBIDDEN

# Define API key header field name
API_KEY_HEADER = APIKeyHeader(name="X-API-Key", auto_error=False)

# In a real application, this would be stored securely (e.g., in a database or environment variable)
# This is just for demonstration
VALID_API_KEYS = {
"test-api-key-1": "user1",
"test-api-key-2": "user2"
}

async def get_current_user_id(api_key: str = Depends(API_KEY_HEADER)) -> str:
"""
Dependency to get the current user ID from the API key.

Args:
api_key: The API key from the request header

Returns:
str: The user ID associated with the API key

Raises:
HTTPException: If the API key is invalid or missing
"""
if not api_key:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="No API key provided"
)

if api_key not in VALID_API_KEYS:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Invalid API key"
)

return VALID_API_KEYS[api_key]
27 changes: 27 additions & 0 deletions backend/app/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from .routers import chat, preview
from .config import Settings

settings = Settings()

app = FastAPI(
title="SPARC API",
description="SPARC Framework API with LLM integration",
version="1.0.0"
)

app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

app.include_router(chat.router, prefix="/api/v1")
app.include_router(preview.router, prefix="/api/v1")

@app.get("/health")
async def health_check():
return {"status": "healthy"}
32 changes: 32 additions & 0 deletions backend/app/models/api_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from sqlalchemy import Column, Integer, String, DateTime, Boolean, func
from sqlalchemy.orm import relationship
from datetime import datetime
from cryptography.fernet import Fernet
from ..database import Base
from ..config import Settings

settings = Settings()
fernet = Fernet(settings.API_KEY_ENCRYPTION_KEY.encode())

class APIKey(Base):
"""Model for storing API keys"""
__tablename__ = "api_keys"

id = Column(Integer, primary_key=True, index=True)
key = Column(String, unique=True, index=True, nullable=False)
provider = Column(String, nullable=False)
user_id = Column(Integer, nullable=False)
created_at = Column(DateTime, default=func.now(), nullable=False)
last_used = Column(DateTime, nullable=True)
usage_count = Column(Integer, default=0)
is_active = Column(Boolean, default=True)

@property
def decrypted_key(self) -> str:
"""Decrypt and return the API key"""
return fernet.decrypt(self.key.encode()).decode()

@classmethod
def encrypt_key(cls, key: str) -> str:
"""Encrypt an API key"""
return fernet.encrypt(key.encode()).decode()
8 changes: 8 additions & 0 deletions backend/app/models/chat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from pydantic import BaseModel

class ChatRequest(BaseModel):
prompt: str
stream: bool = False

class ChatResponse(BaseModel):
response: str
Loading