GPT_3.5_API_KEY / app.py
JairoDanielMT's picture
Create app.py
9c07fea verified
raw
history blame
2.24 kB
from fastapi import FastAPI, HTTPException, Depends
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel
import openai
import uvicorn
from dotenv import load_dotenv
import os
import secrets
from starlette.status import HTTP_401_UNAUTHORIZED
# Cargar las credenciales de OpenAI desde un archivo .env
load_dotenv()
# Configura la clave API de OpenAI
openai.api_key = os.getenv("OPENAI_API_KEY")
# Variables de entorno para autenticación básica
BASIC_AUTH_USERNAME = os.getenv("BASIC_AUTH_USERNAME")
BASIC_AUTH_PASSWORD = os.getenv("BASIC_AUTH_PASSWORD")
app = FastAPI()
security = HTTPBasic()
class MessageRequest(BaseModel):
user_name: str
text: str
class MessageResponse(BaseModel):
response: str
def chatgpt(message: str) -> str:
model_engine = "gpt-3.5-turbo"
response = openai.ChatCompletion.create(
model=model_engine,
messages=[{"role": "user", "content": message}],
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
)
return response.choices[0].message["content"].strip()
def verify_credentials(credentials: HTTPBasicCredentials = Depends(security)):
correct_username = secrets.compare_digest(credentials.username, BASIC_AUTH_USERNAME)
correct_password = secrets.compare_digest(credentials.password, BASIC_AUTH_PASSWORD)
if not (correct_username and correct_password):
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials
@app.post("/send_message", response_model=MessageResponse)
async def send_message(
request: MessageRequest,
credentials: HTTPBasicCredentials = Depends(verify_credentials),
):
try:
response_text = chatgpt(request.text)
return MessageResponse(response=response_text)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/")
def read_root(credentials: HTTPBasicCredentials = Depends(verify_credentials)):
return {"message": "Bienvenido a la API de ChatGPT."}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)