Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- README.md +30 -0
- dockerfile +18 -0
- main.py +77 -0
- requirements.txt +2 -2
README.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Confidential Prompt FastAPI
|
| 3 |
+
emoji: 🔒
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: docker
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
# FastAPI with Confidential Prompt
|
| 10 |
+
|
| 11 |
+
This FastAPI application allows external systems to trigger the conversational logic of an AI agent without ever revealing the sensitive prompt. It is designed to be deployed on a private Hugging Face Space using Docker.
|
| 12 |
+
|
| 13 |
+
## Features
|
| 14 |
+
- **Secure Prompt Storage**: The structured prompt is stored in the server-side environment.
|
| 15 |
+
|
| 16 |
+
- **Anonymous API Key Generation**: The `/signup` endpoint generates a new random API key (UUID4) without requiring any personal information (no email, name, or phone number needed). The key is saved in a local SQLite database.
|
| 17 |
+
|
| 18 |
+
- **Protected `/instructions` Endpoint**: The `/instructions` endpoint requires a valid API key (provided in the HTTP `Authorization` header). If the key is valid, the API returns a neutral confirmation message (`{"message": "Instructions processed"}`) without ever disclosing the prompt's content.
|
| 19 |
+
|
| 20 |
+
- **No External LLM Integration**: The application does not integrate with any external language models. All conversational logic remains internal to the server, ensuring complete confidentiality of the prompt.
|
| 21 |
+
|
| 22 |
+
## Installation and Deployment
|
| 23 |
+
1. **Environment Variable**: Set the `CHILO_JSON` environment variable before starting the application, storing the structured prompt (in JSON format). On Hugging Face Spaces, add this variable as a secret to keep it private.
|
| 24 |
+
2. **Database**: The application uses an SQLite database named `api_keys.db` to store API keys. On Hugging Face Spaces, enable persistent storage to preserve this database (`/data/api_keys.db`) across restarts. Without persistent storage, the database will be recreated on each restart, and previously generated keys will be lost.
|
| 25 |
+
3. **Launch**: The provided `Dockerfile` starts the FastAPI server via Uvicorn on port 7860 (the default port for Spaces). Once deployed, the API will be accessible at your Space's URL (or locally at `http://localhost:7860`).
|
| 26 |
+
|
| 27 |
+
## API Usage
|
| 28 |
+
- **POST** `/signup` – Generates a new API key and returns it in JSON format. For example:
|
| 29 |
+
```json
|
| 30 |
+
{"api_key": "123e4567-e89b-12d3-a456-426614174000"}
|
dockerfile
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Utilise l'image officielle de Python 3.10
|
| 2 |
+
FROM python:3.10
|
| 3 |
+
|
| 4 |
+
# Définit le répertoire de travail du conteneur
|
| 5 |
+
WORKDIR /app
|
| 6 |
+
|
| 7 |
+
# Copie le fichier des dépendances et installe les paquets
|
| 8 |
+
COPY requirements.txt .
|
| 9 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 10 |
+
|
| 11 |
+
# Copie le reste du code de l'application
|
| 12 |
+
COPY . .
|
| 13 |
+
|
| 14 |
+
# Expose le port 7860 (port par défaut pour les Spaces)
|
| 15 |
+
EXPOSE 7860
|
| 16 |
+
|
| 17 |
+
# Démarre l'application FastAPI avec Uvicorn
|
| 18 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
main.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Depends
|
| 2 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 3 |
+
import uuid
|
| 4 |
+
import os
|
| 5 |
+
import sqlite3
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
# Charge le prompt structuré depuis la variable d'environnement (secret).
|
| 10 |
+
PROMPT_SECRET = os.getenv("CHILO_JSON") # Prompt structuré stocké de manière sécurisée
|
| 11 |
+
|
| 12 |
+
# Chemin du fichier de base de données SQLite (utilise /data pour un stockage persistant éventuel).
|
| 13 |
+
DB_PATH = "/data/api_keys.db"
|
| 14 |
+
# Crée le répertoire du fichier de base de données s'il n'existe pas.
|
| 15 |
+
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
| 16 |
+
|
| 17 |
+
# Initialise la base de données (crée la table si elle n'existe pas).
|
| 18 |
+
conn = sqlite3.connect(DB_PATH)
|
| 19 |
+
cursor = conn.cursor()
|
| 20 |
+
cursor.execute("""
|
| 21 |
+
CREATE TABLE IF NOT EXISTS api_keys (
|
| 22 |
+
key TEXT PRIMARY KEY
|
| 23 |
+
)
|
| 24 |
+
""")
|
| 25 |
+
conn.commit()
|
| 26 |
+
conn.close()
|
| 27 |
+
|
| 28 |
+
# Configure la dépendance d'authentification (attend un token Bearer dans l'en-tête Authorization).
|
| 29 |
+
token_auth_scheme = HTTPBearer()
|
| 30 |
+
|
| 31 |
+
def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(token_auth_scheme)):
|
| 32 |
+
token = credentials.credentials
|
| 33 |
+
# Vérifie si le token existe dans la base de données.
|
| 34 |
+
conn = sqlite3.connect(DB_PATH)
|
| 35 |
+
cursor = conn.cursor()
|
| 36 |
+
cursor.execute("SELECT 1 FROM api_keys WHERE key = ?", (token,))
|
| 37 |
+
result = cursor.fetchone()
|
| 38 |
+
conn.close()
|
| 39 |
+
if result is None:
|
| 40 |
+
# Si la clé n'est pas trouvée, renvoie une erreur 401 (Unauthorized).
|
| 41 |
+
raise HTTPException(status_code=401, detail="Clé API invalide")
|
| 42 |
+
return token # Token valide.
|
| 43 |
+
|
| 44 |
+
@app.post("/signup")
|
| 45 |
+
def signup():
|
| 46 |
+
"""
|
| 47 |
+
Génère une nouvelle clé API anonyme et l'enregistre.
|
| 48 |
+
"""
|
| 49 |
+
# Génère une nouvelle clé API unique (UUID4).
|
| 50 |
+
new_key = str(uuid.uuid4())
|
| 51 |
+
# Insère cette clé dans la base de données.
|
| 52 |
+
conn = sqlite3.connect(DB_PATH)
|
| 53 |
+
cursor = conn.cursor()
|
| 54 |
+
try:
|
| 55 |
+
cursor.execute("INSERT OR IGNORE INTO api_keys (key) VALUES (?)", (new_key,))
|
| 56 |
+
conn.commit()
|
| 57 |
+
finally:
|
| 58 |
+
conn.close()
|
| 59 |
+
# Retourne la nouvelle clé au client.
|
| 60 |
+
return {"api_key": new_key}
|
| 61 |
+
|
| 62 |
+
@app.post("/instructions")
|
| 63 |
+
def process_instructions(api_key: str = Depends(verify_api_key)):
|
| 64 |
+
"""
|
| 65 |
+
Vérifie la clé API et traite les instructions.
|
| 66 |
+
Retourne un message de confirmation neutre sans exposer aucune partie du prompt.
|
| 67 |
+
"""
|
| 68 |
+
# À ce stade, la clé API est validée.
|
| 69 |
+
# Intentionnellement, aucune donnée du prompt secret n'est renvoyée.
|
| 70 |
+
return {"message": "Instructions traitées"}
|
| 71 |
+
|
| 72 |
+
@app.get("/")
|
| 73 |
+
def read_root():
|
| 74 |
+
"""
|
| 75 |
+
Endpoint racine optionnel pour vérifier que l'API fonctionne.
|
| 76 |
+
"""
|
| 77 |
+
return {"message": "API is running"}
|
requirements.txt
CHANGED
|
@@ -1,2 +1,2 @@
|
|
| 1 |
-
fastapi
|
| 2 |
-
uvicorn[standard]
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn[standard]
|