chatbotComo / app.py
kadsai's picture
Update app.py
826ec8a verified
Raw History Blame Contribute Delete
5.93 kB
from fastapi import FastAPI, HTTPException,Security
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.security.api_key import APIKeyHeader
import gradio as gr
from multiagent_core import respond
import os
import threading
import uvicorn
EXCELIS_USER = os.getenv("EXCELIS_USER")
EXCELIS_MDP = os.getenv("EXCELIS_MDP")
API_KEY = os.getenv("APIKEY")
api_key_header = APIKeyHeader(name="X-API-Key",auto_error=False)
#os = load.dotenv()
# FastAPI Setup
def validate_api_key(api_key: str = Security(api_key_header)):
if api_key != API_KEY:
raise HTTPException(status_code=403, detail="Clé API invalide")
app = FastAPI()
# Autoriser tous les domaines (à restreindre en prod)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Schéma de la requête POST pour le chatbot
class ChatRequest(BaseModel):
message: str
history: list
domain: str = "corismoney"
model_name: str = "gpt-3.5-turbo"
max_tokens: int = 500
temperature: float = 0.1
top_p: float = 1.0
@app.post("/chat")
async def chat_endpoint(req: ChatRequest,api_key: str = Security(validate_api_key)):
try:
updated_history = respond(
message=req.message,
history=req.history,
system_message="",
domain=req.domain,
model_name=req.model_name,
max_tokens=req.max_tokens,
temperature=req.temperature,
top_p=req.top_p
)
return {"history": updated_history}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Gradio UI personnalisé
initial_history = [{"role": "assistant", "content": "👋 Bonjour, je suis AxelIA, votre assistant. Que puis-je faire pour vous aujourd’hui ?"}]
with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color: #b8c2d3;}") as gradio_app:
with gr.Column(visible=True, elem_id="login-block") as login_block:
gr.Markdown("""
<div style="text-align: center; font-size: 24px; font-weight: bold; margin-bottom: 10px;">
🔐 Bienvenue sur le Portail IA Excelis
</div>
<p style="text-align:center;">Veuillez vous connecter pour accéder au chatbot intelligent.</p>
""", elem_id="login-title")
user_input = gr.Textbox(label="👤 Nom d'utilisateur", placeholder="Entrez votre identifiant")
pass_input = gr.Textbox(label="🔒 Mot de passe", type="password", placeholder="Entrez votre mot de passe")
login_button = gr.Button("✅ Se connecter", variant="primary")
error_box = gr.Textbox(visible=False, interactive=False, label="", elem_id="error-message")
with gr.Column(visible=False, elem_id="chatbot-block") as chatbot_block:
gr.Markdown("""
<div style="text-align:center; font-size: 22px; font-weight: bold; margin-bottom: 10px;">
🤖 Assistant IA Excelis
</div>
""")
mode_selector = gr.Dropdown(
choices=["chatbotAssistance"],
label="🎛️ Choisissez un mode", value="chatbotAssistance"
)
with gr.Column(visible=True) as chatbot_mode_block:
with gr.Row():
domain = gr.Dropdown(
choices=["corismoney", "ptibank", "cmf", "cma-bf", "assurance", "expertise"],
label="🌐 Domaine d'application", value="corismoney"
)
model_name = gr.Dropdown(
choices=["gpt-3.5-turbo", "gpt-4", "gpt-4o-mini"],
label="🧠 Modèle OpenAI", value="gpt-3.5-turbo"
)
with gr.Row():
max_tokens = gr.Slider(1, 2048, value=800, label="🧠 Max tokens")
temperature = gr.Slider(0.1, 2.0, value=0.1, label="🌡️ Température")
top_p = gr.Slider(0.1, 1.0, value=0.95, label="🎯 Top-p")
chatbot = gr.Chatbot(value=initial_history,label="💬 Chat", type="messages", elem_id="chat-display")
message_input = gr.Textbox(label="✉️ Votre message", placeholder="Tapez votre question ici...")
send_button = gr.Button("🚀 Envoyer", variant="primary")
def chat_submit(msg, history, domain, model_name, max_tokens, temperature, top_p):
if not msg or not msg.strip():
return history, gr.update(value=msg)
new_history = respond(msg, history, "", domain, model_name, max_tokens, temperature, top_p)
return new_history, gr.update(value="")
send_button.click(
fn=chat_submit,
inputs=[message_input, chatbot, domain, model_name, max_tokens, temperature, top_p],
outputs=[chatbot, message_input],
)
message_input.submit(
fn=chat_submit,
inputs=[message_input, chatbot, domain, model_name, max_tokens, temperature, top_p],
outputs=[chatbot, message_input],
)
def verify_login(username, password):
if username == EXCELIS_USER and password == EXCELIS_MDP:
return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
else:
return gr.update(visible=True, value="❌ Identifiant ou mot de passe incorrect"), gr.update(visible=False), gr.update(visible=False)
login_button.click(
fn=verify_login,
inputs=[user_input, pass_input],
outputs=[error_box, login_block, chatbot_block],
)
if __name__ == "__main__":
#def launch_gradio():
# gradio_app.launch(server_name="0.0.0.0", server_port=7860, share=False)
#threading.Thread(target=launch_gradio).start()
uvicorn.run("app:app", host="0.0.0.0", port=7860)
#uvicorn.run("app:app", host="0.0.0.0", port=8000)