Aurele000 commited on
Commit
f4dc45b
·
1 Parent(s): db1212e

ajout de quelques agents / fonctions

Browse files
Files changed (3) hide show
  1. agent.py +37 -33
  2. app.py +7 -4
  3. fonctions.py +32 -11
agent.py CHANGED
@@ -24,12 +24,17 @@ llm_4o = ChatOpenAI(
24
  model_name="gpt-4o",
25
  openai_api_key=api_open_ai_agent_key, # ou variable d’environnement
26
  )
 
 
 
 
27
  llm_reasoning = ChatOpenAI(
28
  model_name = "o3-2025-04-16",
29
  openai_api_key=api_open_ai_agent_key, # ou variable d’environnement
30
  )
31
 
32
 
 
33
  llm_reasoning_small = ChatOpenAI(
34
  model_name = "o4-mini-2025-04-16",
35
  openai_api_key=api_open_ai_agent_key, # ou variable d’environnement
@@ -133,18 +138,17 @@ def divide(a: float, b: float):
133
  return a / b
134
 
135
 
136
-
137
  @tool
138
- def create_agent_and_answer(input: ToolInput) -> str:
139
  """ From a dataframe, can anwser any question
140
- The input should be like : input_data = ToolInput(
141
- question="Quel est l'âge moyen ?",
142
- data= 'ouput of the open_xlsx_doc tool'
 
143
  """
144
- df = pd.DataFrame(input.data)
145
- question = input.question
146
- agent_excel_inter = create_pandas_dataframe_agent(llm_4o, df, verbose=True, allow_dangerous_code=True)
147
- text = agent_excel_inter.run(question)
148
 
149
  return text
150
 
@@ -199,24 +203,9 @@ math_agent = create_react_agent(
199
 
200
  name="math_agent")
201
 
202
- agent_excel = create_pandas_dataframe_agent(
203
- model=llm_4o,
204
-
205
- tools=[create_agent_and_answer],
206
- prompt=(
207
- "You are an agent specialized with Excel files.\n\n"
208
- "INSTRUCTIONS:\n"
209
- "- Assist ONLY when an Excel file is mentionned \n"
210
- "- You will receive the path of a dataframe. '\n"
211
- "- The output of the first tool is a part of the input of the second tool\n"
212
-
213
- "- Once you have got a response from the 'create_agent_and_answer_tool', transmit it to your supervisor \n"
214
- ),
215
- name="agent_excel",
216
- )
217
 
218
  reflexion_agent = create_react_agent(
219
- model=llm_reasoning,
220
 
221
  tools=[],
222
  prompt=(
@@ -229,22 +218,37 @@ reflexion_agent = create_react_agent(
229
  ),
230
  name="reflexion_agent",
231
  )
 
 
232
 
 
 
 
 
 
 
 
 
 
 
 
233
  supervisor = create_supervisor(
234
  model=init_chat_model("openai:gpt-4.1", api_key = api_open_ai_agent_key),
235
- agents=[research_agent, web_search_openai_agent, agent_excel, reflexion_agent],
236
  prompt=(
237
- "You are a supervisor managing four agents:\n"
238
  "- research_agent: Specialised in ArXiv and Wikipedia. Assign research-related tasks to this agent.\n"
 
239
  "- web_search_openai_agent: Can browse the web to find up-to-date and relevant information. Assign web-related tasks to this agent.\n"
240
- "- agent_excel: Can exploit Excel file. You have to give him an Excel path file with a question, and wait for his response.\n"
241
- "- reflexion_agent: This agent uses a powerful model. It is your most intelligent agent. Useful for reflexion tasks. It can solve math problems also.\n"
242
  "Assign work to one agent at a time. Do not call agents in parallel.\n"
243
- "When a new question arises, always first consult the research_agent it may provide useful information.\n"
 
 
244
  "If research_agent yields no results, then delegate the task to web_search_openai_agent.\n"
245
- "Each time you receive information from an agent, you have to analyze, process it then decide what to do (call an agent or give your final answer)."
246
- "When you consider it pertinent, give your thought to the reflexion agent. He will advise you. "
247
- "Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string. If no punctuation is precised, don't add any. Respect the requested format"
248
 
249
  ),
250
  add_handoff_back_messages=True,
 
24
  model_name="gpt-4o",
25
  openai_api_key=api_open_ai_agent_key, # ou variable d’environnement
26
  )
27
+ llm_4_1 = ChatOpenAI(
28
+ model_name='gpt-4.1',
29
+ openai_api_key=api_open_ai_agent_key, # ou variable d’environnement
30
+ )
31
  llm_reasoning = ChatOpenAI(
32
  model_name = "o3-2025-04-16",
33
  openai_api_key=api_open_ai_agent_key, # ou variable d’environnement
34
  )
35
 
36
 
37
+
38
  llm_reasoning_small = ChatOpenAI(
39
  model_name = "o4-mini-2025-04-16",
40
  openai_api_key=api_open_ai_agent_key, # ou variable d’environnement
 
138
  return a / b
139
 
140
 
 
141
  @tool
142
+ def create_agent_and_answer(dict_data, question) -> str:
143
  """ From a dataframe, can anwser any question
144
+ The input should be like :
145
+ - dict_data= a dict
146
+ - question= a str. Exemple : "Quel est l'âge moyen ?",
147
+
148
  """
149
+ df = pd.DataFrame(dict_data)
150
+ agent_excel = create_pandas_dataframe_agent(llm_4_1, df, verbose=True, allow_dangerous_code=True)
151
+ text = agent_excel.run(question)
 
152
 
153
  return text
154
 
 
203
 
204
  name="math_agent")
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
  reflexion_agent = create_react_agent(
208
+ model=llm_reasoning_small,
209
 
210
  tools=[],
211
  prompt=(
 
218
  ),
219
  name="reflexion_agent",
220
  )
221
+ agent_excel_new = create_react_agent(
222
+ model=llm_4o,
223
 
224
+ tools=[create_agent_and_answer],
225
+ prompt=(
226
+ "You are an agent psecialized with Excel files.\n\n"
227
+ "INSTRUCTIONS:\n"
228
+ "- Assist ONLY when an Excel file is mentionned \n"
229
+ "- First, you will receive a dict that you can give to the associated file. If you don't have one, ask it to the supervisor.\n"
230
+ "- Then you use the 'create_agent_and_answer' tool to answer the question. \n"
231
+ "- Once you have got a response from the 'create_agent_and_answer_tool', transmit it to your supervisor \n"
232
+ ),
233
+ name="agent_excel_new",
234
+ )
235
  supervisor = create_supervisor(
236
  model=init_chat_model("openai:gpt-4.1", api_key = api_open_ai_agent_key),
237
+ agents=[research_agent, web_search_openai_agent, agent_excel_new, reflexion_agent],
238
  prompt=(
239
+ "You are a supervisor managing three agents:\n"
240
  "- research_agent: Specialised in ArXiv and Wikipedia. Assign research-related tasks to this agent.\n"
241
+ "- reflexion: Called when the supervisor need a reflexion, not general knowledge. Can handle math-related tasks such as solving equations, performing calculations or working on abstract maths subject such as matrix or demonstrating subjects.\n"
242
  "- web_search_openai_agent: Can browse the web to find up-to-date and relevant information. Assign web-related tasks to this agent.\n"
243
+ "- agent_excel_new: Can understand tabular data. If an excel file is mentioned, call this agent. \n"
 
244
  "Assign work to one agent at a time. Do not call agents in parallel.\n"
245
+ "The reflexion agent is your best weapon when the is a complex question. Call him only one time maximum by question.\n"
246
+ " If there is an attached file, it will already loaded. Juste give the information to the agent. \n"
247
+ "When a new question arises, if it is about an information that you can find on Wikipedia, first consult the research_agent — it may provide useful information.\n"
248
  "If research_agent yields no results, then delegate the task to web_search_openai_agent.\n"
249
+ "Each time you receive information from an agent, you have to analyze, process it then decide what to do (call an agent or give your final answer).\n"
250
+ "As soon as you get a question, you have to analyze it and determine which agent is the most competent. Call at least one for each question.\n"
251
+ "IMPORTANT : Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number NEITHER use units such as $, percent sign, or the currency unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string. If no punctuation is precised, don't add any. If you are asked for a price, don't precise the format, only the number. Respect the requested format"
252
 
253
  ),
254
  add_handoff_back_messages=True,
app.py CHANGED
@@ -3,7 +3,7 @@ import gradio as gr
3
  import requests
4
  import pandas as pd
5
  from agent import response_from_agent, supervisor
6
-
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -76,9 +76,12 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
76
  continue
77
  try:
78
  print(f'la question est {question_text}')
79
- if filename :
80
- print('fichier attaché : ', filename)
81
- submitted_answer = response_from_agent(supervisor,question_text + 'The file_name (path) is : ' + filename)
 
 
 
82
  print('submitted_answer:', submitted_answer)
83
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
84
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
3
  import requests
4
  import pandas as pd
5
  from agent import response_from_agent, supervisor
6
+ from fonctions import load_data
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
76
  continue
77
  try:
78
  print(f'la question est {question_text}')
79
+
80
+ data = load_data(item)
81
+ print("data:", data)
82
+ #submitted_answer = response_from_agent(supervisor,question_text + 'The file_name (path) is : ' + filename)
83
+ submitted_answer = response_from_agent(f'the question is {question_text}. The attached file is {data}. If it is a .mp3, you have the transcripted text in the attached file. If it is an excel file, you have a dictionnary. If it is a png file, you will have the path to the file.')
84
+
85
  print('submitted_answer:', submitted_answer)
86
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
87
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
fonctions.py CHANGED
@@ -1,9 +1,11 @@
1
  from io import BytesIO
2
- from pydub import AudioSegment
3
  import requests
4
  import re
5
  import pandas as pd
 
6
 
 
 
7
  def clean_response(response):
8
  match = re.search(r'FINAL ANSWER:\s*(.+)', response['supervisor']['messages'][-1].content)
9
  answer = match.group(1).strip() if match else None
@@ -21,9 +23,11 @@ def response_from_agent(supervisor, question):
21
 
22
  response = clean_response(response)
23
  return response
 
 
24
  def load_data(question):
25
- task_id = question['task_id']
26
- file_name = question['file_name']
27
 
28
  if file_name == "":
29
  return 'There is no attached file'
@@ -33,17 +37,34 @@ def load_data(question):
33
  return 'Le lien ne fonctionne pas'
34
  if file_name.endswith('.xlsx'):
35
  excel_data = BytesIO(files_response.content)
36
- df = pd.read_excel(excel_data, engine='openpyxl')
37
- return df
 
38
 
39
  elif file_name.endswith('.png'):
40
- filename = f"fichier_{task_id}.png"
41
- with open(filename, "wb") as f:
42
- f.write(files_response.content)
43
- return filename
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  elif file_name.endswith('.mp3'):
46
  audio_bytes = BytesIO(files_response.content)
47
- audio = AudioSegment.from_file(audio_bytes, format="mp3")
 
 
 
 
 
48
 
49
- return audio
 
1
  from io import BytesIO
 
2
  import requests
3
  import re
4
  import pandas as pd
5
+ from openai import OpenAI
6
 
7
+ api_open_ai_agent_key=os.environ["OPENAI_API_KEY"]
8
+ client = OpenAI(api_key=api_open_ai_agent_key)
9
  def clean_response(response):
10
  match = re.search(r'FINAL ANSWER:\s*(.+)', response['supervisor']['messages'][-1].content)
11
  answer = match.group(1).strip() if match else None
 
23
 
24
  response = clean_response(response)
25
  return response
26
+
27
+
28
  def load_data(question):
29
+ task_id = question.get('task_id')
30
+ file_name = question.get('file_name')
31
 
32
  if file_name == "":
33
  return 'There is no attached file'
 
37
  return 'Le lien ne fonctionne pas'
38
  if file_name.endswith('.xlsx'):
39
  excel_data = BytesIO(files_response.content)
40
+ df = pd.read_excel(excel_data)
41
+ data_dict = df.to_dict(orient="list")
42
+ return data_dict
43
 
44
  elif file_name.endswith('.png'):
45
+ response = client.responses.create(
46
+ model="gpt-4.1-mini",
47
+ input=[{
48
+ "role": "user",
49
+ "content": [
50
+ {"type": "input_text", "text": "what's in this image? Please give as much details as possible"},
51
+ {
52
+ "type": "input_image",
53
+ "image_url": f"https://agents-course-unit4-scoring.hf.space/files/{task_id}",
54
+ },
55
+ ],
56
+ }],
57
+ )
58
+
59
+ return response.output_text
60
 
61
  elif file_name.endswith('.mp3'):
62
  audio_bytes = BytesIO(files_response.content)
63
+ audio_bytes.name = "audio.mp3"
64
+
65
+ transcription = client.audio.transcriptions.create(
66
+ model="whisper-1", # ou "whisper-1", mais "gpt-4o" est aussi correct
67
+ file=audio_bytes
68
+ )
69
 
70
+ return transcription.text