| import os |
| from openai import OpenAI |
| from fastapi import FastAPI, HTTPException, Depends |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials |
| from pydantic import BaseModel |
| from typing import List, Any |
| import uvicorn |
|
|
| |
| API_TOKEN = os.getenv("API_TOKEN") |
| if not API_TOKEN: |
| raise Exception("La variable de ambiente API_TOKEN no está definida") |
|
|
| OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") |
| if not OPENAI_API_KEY: |
| raise Exception("La variable de ambiente OPENAI_API_KEY no está definida") |
|
|
| MODEL = os.getenv("MODEL") |
| if not MODEL: |
| raise Exception("La variable de ambiente MODEL no está definida") |
|
|
| PORT = os.getenv("PORT") |
| if not PORT: |
| raise Exception("La variable de ambiente PORT no está definida") |
| try: |
| PORT = int(PORT) |
| except ValueError: |
| raise Exception("La variable de ambiente PORT debe ser un número entero") |
|
|
| client = OpenAI() |
| |
| class Message(BaseModel): |
| role: str |
| content: Any |
|
|
| class ChatPayload(BaseModel): |
| messages: List[Message] |
|
|
| |
| auth_scheme = HTTPBearer() |
|
|
| def verify_token(credentials: HTTPAuthorizationCredentials = Depends(auth_scheme)): |
| if credentials.credentials != API_TOKEN: |
| raise HTTPException(status_code=401, detail="Token inválido") |
| return credentials.credentials |
|
|
| |
| app = FastAPI() |
|
|
| @app.post("/") |
| async def chat_endpoint(payload: ChatPayload, token: str = Depends(verify_token)): |
| try: |
| completion = client.chat.completions.create( |
| model=MODEL, |
| messages=payload.messages, |
| max_completion_tokens=500 |
| ) |
| return completion |
| except Exception as e: |
| raise HTTPException(status_code=500, detail=str(e)) |
|
|
| if __name__ == "__main__": |
| uvicorn.run(app, host="0.0.0.0", port=PORT) |