Woziii commited on
Commit
ac49c2f
·
verified ·
1 Parent(s): ca7f399

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -0
app.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ import logging
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ import gradio as gr
6
+
7
+ # Configuration du logger
8
+ logging.basicConfig(
9
+ level=logging.INFO,
10
+ format="%(asctime)s - %(levelname)s - %(message)s",
11
+ handlers=[
12
+ logging.StreamHandler()
13
+ ]
14
+ )
15
+
16
+ # Variables globales simulées
17
+ project_state = {
18
+ "AgentManager": {"structured_summary": None},
19
+ "AgentResearcher": {"search_results": None},
20
+ "AgentAnalyzer": {"analysis_report": None, "instruction_for_coder": None},
21
+ "AgentCoder": {"final_code": None}
22
+ }
23
+
24
+ # Chargement du modèle pour l'AgentManager
25
+ manager_model_name = "meta-llama/Llama-3.1-8B-Instruct"
26
+ manager_model = AutoModelForCausalLM.from_pretrained(
27
+ manager_model_name,
28
+ device_map="auto",
29
+ torch_dtype=torch.bfloat16 # Utilisation de bfloat16 comme recommandé
30
+ )
31
+ manager_tokenizer = AutoTokenizer.from_pretrained(manager_model_name)
32
+
33
+ # Prompt prédéfini
34
+ manager_prompt_template = """
35
+ Vous êtes l'AgentManager d'un système multi-agent.
36
+
37
+ - Votre rôle est d'interagir avec l'utilisateur pour comprendre sa demande.
38
+ - Vous devez poser des questions pertinentes pour obtenir toutes les informations nécessaires.
39
+ - Une fois que vous estimez avoir suffisamment d'informations, vous générez un résumé structuré du projet.
40
+ - Vous incluez les informations des variables du projet si elles ne sont pas vides.
41
+ - Vous demandez une validation explicite à l'utilisateur pour le résumé généré.
42
+ - Vous pouvez modifier les variables du projet si l'utilisateur en fait la demande.
43
+
44
+ Variables du projet :
45
+ {variables_context}
46
+ """
47
+
48
+ # Fonctions utilitaires
49
+ def get_variables_context():
50
+ variables = {}
51
+ for agent, data in project_state.items():
52
+ variables[agent] = {}
53
+ for key, value in data.items():
54
+ variables[agent][key] = value if value else "N/A"
55
+ variables_context = json.dumps(variables, indent=2, ensure_ascii=False)
56
+ return variables_context
57
+
58
+ def update_project_state(modifications):
59
+ for var, value in modifications.items():
60
+ keys = var.split('.')
61
+ target = project_state
62
+ for key in keys[:-1]:
63
+ target = target.get(key, {})
64
+ target[keys[-1]] = value
65
+
66
+ def extract_modifications(user_input):
67
+ modifications = {}
68
+ if "modifie" in user_input.lower():
69
+ matches = re.findall(r"modifie la variable (\w+(?:\.\w+)*) à (.+)", user_input, re.IGNORECASE)
70
+ for match in matches:
71
+ var_name, var_value = match
72
+ modifications[var_name.strip()] = var_value.strip()
73
+ return modifications
74
+
75
+ def extract_structured_summary(response):
76
+ start_token = "Résumé Structuré :"
77
+ end_token = "Fin du Résumé"
78
+ start_index = response.find(start_token)
79
+ end_index = response.find(end_token, start_index)
80
+ if start_index != -1 and end_index != -1:
81
+ summary = response[start_index + len(start_token):end_index].strip()
82
+ return summary
83
+ else:
84
+ logging.warning("Le résumé structuré n'a pas pu être extrait.")
85
+ return None
86
+
87
+ # Fonction principale de l'AgentManager
88
+ def agent_manager(chat_history, user_input):
89
+ variables_context = get_variables_context()
90
+ system_prompt = manager_prompt_template.format(variables_context=variables_context)
91
+
92
+ conversation = [{"role": "system", "content": system_prompt}]
93
+
94
+ # Ajouter l'historique
95
+ for turn in chat_history:
96
+ conversation.append({"role": "user", "content": turn['user']})
97
+ conversation.append({"role": "assistant", "content": turn['assistant']})
98
+
99
+ # Ajouter l'entrée utilisateur actuelle
100
+ conversation.append({"role": "user", "content": user_input})
101
+
102
+ # Vérifier si l'utilisateur souhaite modifier des variables
103
+ modifications = extract_modifications(user_input)
104
+ if modifications:
105
+ update_project_state(modifications)
106
+ response = "Les variables ont été mises à jour selon votre demande."
107
+ chat_history.append({'user': user_input, 'assistant': response})
108
+ return response, chat_history, False
109
+
110
+ # Générer la réponse
111
+ prompt = manager_tokenizer.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
112
+
113
+ input_ids = manager_tokenizer(prompt, return_tensors="pt").to(manager_model.device)
114
+ output_ids = manager_model.generate(
115
+ input_ids["input_ids"],
116
+ max_new_tokens=256,
117
+ eos_token_id=manager_tokenizer.eos_token_id,
118
+ pad_token_id=manager_tokenizer.pad_token_id,
119
+ attention_mask=input_ids["attention_mask"]
120
+ )
121
+ response = manager_tokenizer.decode(output_ids[0], skip_special_tokens=True)
122
+
123
+ chat_history.append({'user': user_input, 'assistant': response})
124
+
125
+ # Vérifier si un résumé a été généré pour validation
126
+ if "Validez-vous ce résumé" in response:
127
+ structured_summary = extract_structured_summary(response)
128
+ project_state["AgentManager"]["structured_summary"] = structured_summary
129
+ return response, chat_history, True # Indique que le résumé est prêt pour validation
130
+ else:
131
+ return response, chat_history, False
132
+
133
+ # Interface Gradio avec modification des variables
134
+ def gradio_interface(user_input, chat_history, variables_input):
135
+ chat_history = json.loads(chat_history) if chat_history else []
136
+ # Mettre à jour les variables du project_state si l'utilisateur les a modifiées
137
+ if variables_input:
138
+ try:
139
+ updated_variables = json.loads(variables_input)
140
+ global project_state
141
+ project_state = updated_variables
142
+ except json.JSONDecodeError:
143
+ return "Erreur : Le format des variables est invalide.", chat_history, json.dumps(project_state, indent=2, ensure_ascii=False), variables_input
144
+
145
+ response, updated_chat_history, _ = agent_manager(chat_history, user_input)
146
+ return response, json.dumps(updated_chat_history), json.dumps(project_state, indent=2, ensure_ascii=False), json.dumps(project_state, indent=2, ensure_ascii=False)
147
+
148
+ with gr.Blocks() as demo:
149
+ gr.Markdown("## Simulation de l'AgentManager avec modification des variables")
150
+ with gr.Row():
151
+ with gr.Column():
152
+ user_input = gr.Textbox(label="Entrée utilisateur", placeholder="Entrez une requête ou une instruction.")
153
+ variables_input = gr.Textbox(label="Modifier les variables du projet (JSON)", placeholder="Entrez un JSON valide pour modifier les variables.", lines=10)
154
+ chat_history = gr.Textbox(label="Historique de conversation", value="[]", visible=False)
155
+ submit = gr.Button("Envoyer")
156
+ with gr.Column():
157
+ output = gr.Textbox(label="Réponse de l'AgentManager", interactive=False)
158
+ variables_output = gr.Textbox(label="Variables globales actuelles", interactive=False, lines=20)
159
+
160
+ submit.click(gradio_interface, inputs=[user_input, chat_history, variables_input], outputs=[output, chat_history, variables_output, variables_input])
161
+
162
+ # Lancer l'interface
163
+ if __name__ == "__main__":
164
+ demo.launch()