Projet_chatbot / app.py
Foccuus's picture
Update app.py
77a5ceb verified
Raw
History Blame Contribute Delete
5.95 kB
import gradio as gr
from openai import OpenAI
import os
from datetime import datetime
import uuid
api_key = os.environ.get("KEY_SECRET")
if not api_key:
raise ValueError("Variable d'environnement KEY_SECRET introuvable.")
client = OpenAI(
api_key=api_key,
base_url="https://api.together.xyz/v1",
)
conversation_history = {}
current_conversation_id = None
def generate_conversation_title(message):
return message[:50] + "..." if len(message) > 50 else message
def create_new_conversation():
global current_conversation_id
current_conversation_id = str(uuid.uuid4())
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
conversation_history[current_conversation_id] = {
"title": "Nouvelle conversation",
"timestamp": timestamp,
"messages": [],
"system_prompt": "Tu es un assistant IA utile, honnête et inoffensif."
}
return current_conversation_id
# --- AJOUT DU PARAMÈTRE TEMPERATURE ICI ---
def chat(message, history, system_prompt, temperature):
api_messages = [{"role": "system", "content": system_prompt}]
for entry in history:
api_messages.append({"role": entry["role"], "content": entry["content"]})
api_messages.append({"role": "user", "content": message})
try:
stream = client.chat.completions.create(
model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
messages=api_messages,
stream=True,
temperature=temperature, # Utilise maintenant la valeur du slider
max_tokens=1024
)
partial_text = ""
for chunk in stream:
if chunk.choices[0].delta.content:
partial_text += chunk.choices[0].delta.content
yield partial_text
except Exception as e:
yield f"❌ Erreur: {str(e)}"
# --- AJOUT DU PARAMÈTRE TEMPERATURE ICI ---
def respond(message, history, system_prompt, temperature):
global current_conversation_id
if not current_conversation_id:
current_conversation_id = create_new_conversation()
if not conversation_history[current_conversation_id]["messages"]:
conversation_history[current_conversation_id]["title"] = generate_conversation_title(message)
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": ""})
# On passe la température à la fonction chat
for partial_response in chat(message, history[:-2], system_prompt, temperature):
history[-1]["content"] = partial_response
yield "", history
conversation_history[current_conversation_id]["messages"] = history
conversation_history[current_conversation_id]["system_prompt"] = system_prompt
def get_conversation_list():
if not conversation_history:
return "Aucune conversation"
items = []
for conv_id, conv_data in sorted(
conversation_history.items(),
key=lambda x: x[1]["timestamp"],
reverse=True
):
items.append(f"{conv_data['title']}\n{conv_data['timestamp']}")
return "\n\n".join(items)
def new_conversation():
create_new_conversation()
return (
[],
"Tu es un assistant IA utile et honnête. Réponds de manière claire et concise.",
get_conversation_list()
)
def delete_conv():
global current_conversation_id
if current_conversation_id and current_conversation_id in conversation_history:
del conversation_history[current_conversation_id]
current_conversation_id = None
return [], "Tu es un assistant IA utile.", get_conversation_list()
with gr.Blocks(title="Chatbot Mentorat") as demo:
gr.Markdown("# 🤖 Chatbot Mentorat")
gr.Markdown("Votre assistant IA personnel avec historique et personnalisation")
with gr.Row():
with gr.Column(scale=1, min_width=280):
gr.Markdown("### Historique")
history_display = gr.Textbox(
label="Conversations",
interactive=False,
lines=15,
placeholder="Aucune conversation"
)
with gr.Row():
btn_new = gr.Button("Nouvelle Conversation", size="sm")
btn_delete = gr.Button("Supprimer", size="sm")
gr.Markdown("### Configuration")
system_prompt = gr.Textbox(
value="Tu es un assistant IA utile et honnête. Répondsmanière claire et concise.",
label="Prompt système",
lines=4
)
# --- ON ASSIGNE LE SLIDER À UNE VARIABLE ---
temp_slider = gr.Slider(
minimum=0.0, maximum=1.0, value=0.6, step=0.1,
label="Température (créativité)",
info="Plus bas = plus précis, plus haut = plus créatif"
)
with gr.Column(scale=3):
gr.Markdown("### Conversation")
chatbot = gr.Chatbot(height=600, show_label=False, avatar_images=("👤", "🤖"))
with gr.Row():
msg = gr.Textbox(label="Votre message", scale=5)
btn_send = gr.Button("Envoyer", scale=1)
# --- MISE À JOUR DES INPUTS POUR INCLURE LE SLIDER ---
btn_new.click(new_conversation, outputs=[chatbot, system_prompt, history_display])
btn_delete.click(delete_conv, outputs=[chatbot, system_prompt, history_display])
msg.submit(
respond,
[msg, chatbot, system_prompt, temp_slider], # Slider ajouté ici
[msg, chatbot]
).then(lambda: get_conversation_list(), outputs=[history_display])
btn_send.click(
respond,
[msg, chatbot, system_prompt, temp_slider], # Slider ajouté ici
[msg, chatbot]
).then(lambda: get_conversation_list(), outputs=[history_display])
demo.load(lambda: get_conversation_list(), outputs=[history_display])
if __name__ == "__main__":
demo.launch(share=False, theme=gr.themes.Soft())