Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 4 |
from datetime import datetime
|
| 5 |
import os
|
| 6 |
import json
|
|
@@ -10,6 +10,7 @@ import requests
|
|
| 10 |
from bs4 import BeautifulSoup
|
| 11 |
from concurrent.futures import ThreadPoolExecutor
|
| 12 |
import re
|
|
|
|
| 13 |
|
| 14 |
# --- Configuration du logger ---
|
| 15 |
logging.basicConfig(
|
|
@@ -22,11 +23,9 @@ logging.basicConfig(
|
|
| 22 |
)
|
| 23 |
|
| 24 |
# --- Authentification Hugging Face ---
|
| 25 |
-
# Assurez-vous que la variable d'environnement HF_TOKEN est définie avec votre token Hugging Face
|
| 26 |
-
# Sinon, vous pouvez la définir directement ici
|
| 27 |
-
# os.environ["HF_TOKEN"] = "votre_token_huggingface"
|
| 28 |
|
| 29 |
-
login(token=os.environ["HF_TOKEN"])
|
|
|
|
| 30 |
# Variables globales
|
| 31 |
project_state = {
|
| 32 |
"AgentManager": {"structured_summary": None},
|
|
@@ -36,11 +35,11 @@ project_state = {
|
|
| 36 |
}
|
| 37 |
|
| 38 |
# Chargement du modèle
|
| 39 |
-
manager_model_name = "meta-llama/Llama-3.
|
| 40 |
manager_model = AutoModelForCausalLM.from_pretrained(
|
| 41 |
manager_model_name,
|
| 42 |
device_map="auto",
|
| 43 |
-
torch_dtype=
|
| 44 |
)
|
| 45 |
manager_tokenizer = AutoTokenizer.from_pretrained(manager_model_name)
|
| 46 |
|
|
@@ -98,8 +97,9 @@ def clean_output(response, system_prompt, conversation_context):
|
|
| 98 |
response = response.replace(system_prompt, "").replace(conversation_context, "").strip()
|
| 99 |
return response
|
| 100 |
|
|
|
|
| 101 |
def agent_manager(chat_history, user_input):
|
| 102 |
-
"""Gère les interactions utilisateur et assistant."""
|
| 103 |
# Préparer le contexte des variables
|
| 104 |
variables_context = get_variables_context()
|
| 105 |
|
|
@@ -117,35 +117,41 @@ def agent_manager(chat_history, user_input):
|
|
| 117 |
# Ajouter l'entrée utilisateur actuelle
|
| 118 |
chat_history.append({"user": user_input, "assistant": ""})
|
| 119 |
|
| 120 |
-
#
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
max_new_tokens=MAX_NEW_TOKENS,
|
| 125 |
temperature=TEMPERATURE,
|
| 126 |
top_p=TOP_P,
|
| 127 |
eos_token_id=manager_tokenizer.eos_token_id,
|
| 128 |
-
pad_token_id=manager_tokenizer.pad_token_id
|
|
|
|
| 129 |
)
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
# Nettoyer la sortie
|
| 133 |
-
response = clean_output(response, system_prompt, conversation_context)
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
# Interface Gradio
|
| 141 |
def gradio_interface(user_input, chat_history):
|
| 142 |
chat_history = json.loads(chat_history) if chat_history else []
|
| 143 |
-
|
| 144 |
-
variables_context
|
| 145 |
-
|
| 146 |
|
| 147 |
with gr.Blocks() as demo:
|
| 148 |
-
gr.Markdown("## AgentManager - Test d'Interactions Collaboratives")
|
| 149 |
with gr.Row():
|
| 150 |
with gr.Column():
|
| 151 |
user_input = gr.Textbox(label="Entrée utilisateur", placeholder="Entrez une requête ou une instruction.")
|
|
@@ -159,4 +165,4 @@ with gr.Blocks() as demo:
|
|
| 159 |
|
| 160 |
# Lancer l'interface
|
| 161 |
if __name__ == "__main__":
|
| 162 |
-
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 4 |
from datetime import datetime
|
| 5 |
import os
|
| 6 |
import json
|
|
|
|
| 10 |
from bs4 import BeautifulSoup
|
| 11 |
from concurrent.futures import ThreadPoolExecutor
|
| 12 |
import re
|
| 13 |
+
from threading import Thread
|
| 14 |
|
| 15 |
# --- Configuration du logger ---
|
| 16 |
logging.basicConfig(
|
|
|
|
| 23 |
)
|
| 24 |
|
| 25 |
# --- Authentification Hugging Face ---
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
login(token=os.environ["HF_TOKEN"]))
|
| 28 |
+
|
| 29 |
# Variables globales
|
| 30 |
project_state = {
|
| 31 |
"AgentManager": {"structured_summary": None},
|
|
|
|
| 35 |
}
|
| 36 |
|
| 37 |
# Chargement du modèle
|
| 38 |
+
manager_model_name = "meta-llama/Llama-3.2-3B-Instruct"
|
| 39 |
manager_model = AutoModelForCausalLM.from_pretrained(
|
| 40 |
manager_model_name,
|
| 41 |
device_map="auto",
|
| 42 |
+
torch_dtype=torch.bfloat16
|
| 43 |
)
|
| 44 |
manager_tokenizer = AutoTokenizer.from_pretrained(manager_model_name)
|
| 45 |
|
|
|
|
| 97 |
response = response.replace(system_prompt, "").replace(conversation_context, "").strip()
|
| 98 |
return response
|
| 99 |
|
| 100 |
+
# Fonction principale avec streaming
|
| 101 |
def agent_manager(chat_history, user_input):
|
| 102 |
+
"""Gère les interactions utilisateur et assistant avec streaming."""
|
| 103 |
# Préparer le contexte des variables
|
| 104 |
variables_context = get_variables_context()
|
| 105 |
|
|
|
|
| 117 |
# Ajouter l'entrée utilisateur actuelle
|
| 118 |
chat_history.append({"user": user_input, "assistant": ""})
|
| 119 |
|
| 120 |
+
# Préparation des tokens et du streamer
|
| 121 |
+
inputs = manager_tokenizer(system_prompt + "\nUtilisateur : " + user_input, return_tensors="pt").to(manager_model.device)
|
| 122 |
+
attention_mask = inputs.attention_mask
|
| 123 |
+
streamer = TextIteratorStreamer(manager_tokenizer, skip_special_tokens=True)
|
| 124 |
+
|
| 125 |
+
# Thread pour la génération
|
| 126 |
+
generation_kwargs = dict(
|
| 127 |
+
inputs=inputs.input_ids,
|
| 128 |
+
attention_mask=attention_mask,
|
| 129 |
max_new_tokens=MAX_NEW_TOKENS,
|
| 130 |
temperature=TEMPERATURE,
|
| 131 |
top_p=TOP_P,
|
| 132 |
eos_token_id=manager_tokenizer.eos_token_id,
|
| 133 |
+
pad_token_id=manager_tokenizer.pad_token_id,
|
| 134 |
+
streamer=streamer
|
| 135 |
)
|
| 136 |
+
generation_thread = Thread(target=manager_model.generate, kwargs=generation_kwargs)
|
| 137 |
+
generation_thread.start()
|
|
|
|
|
|
|
| 138 |
|
| 139 |
+
partial_response = ""
|
| 140 |
+
for new_text in streamer:
|
| 141 |
+
partial_response += new_text
|
| 142 |
+
clean_partial_response = clean_output(partial_response, system_prompt, conversation_context)
|
| 143 |
+
chat_history[-1]["assistant"] = clean_partial_response
|
| 144 |
+
yield clean_partial_response, json.dumps(chat_history), get_variables_context()
|
| 145 |
|
| 146 |
+
# Interface Gradio avec Streaming
|
|
|
|
|
|
|
| 147 |
def gradio_interface(user_input, chat_history):
|
| 148 |
chat_history = json.loads(chat_history) if chat_history else []
|
| 149 |
+
response_generator = agent_manager(chat_history, user_input)
|
| 150 |
+
for response, updated_chat_history, variables_context in response_generator:
|
| 151 |
+
yield response, updated_chat_history, variables_context
|
| 152 |
|
| 153 |
with gr.Blocks() as demo:
|
| 154 |
+
gr.Markdown("## AgentManager - Test d'Interactions Collaboratives avec Streaming")
|
| 155 |
with gr.Row():
|
| 156 |
with gr.Column():
|
| 157 |
user_input = gr.Textbox(label="Entrée utilisateur", placeholder="Entrez une requête ou une instruction.")
|
|
|
|
| 165 |
|
| 166 |
# Lancer l'interface
|
| 167 |
if __name__ == "__main__":
|
| 168 |
+
demo.queue().launch()
|