Lulube commited on
Commit
5549315
·
verified ·
1 Parent(s): 5651cfd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -9
app.py CHANGED
@@ -1,8 +1,17 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
 
 
 
 
 
 
 
 
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
@@ -12,13 +21,87 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
  # --- Basic Agent Definition ---
13
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
14
  import os
15
- from smolagents import CodeAgent, LiteLLMModel, DuckDuckGoSearchTool, VisitWebpageTool, PythonInterpreterTool, SpeechToTextTool #, ImageCaptioningTool
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  class BasicAgent():
18
  def __init__(self):
19
  print("MyCustomAgent with SmolaAgent initialized.")
20
 
21
- # Configuration du modèle Azure GPT-4o-mini
22
  self.model = LiteLLMModel(
23
  model_id="azure/gpt-4o",
24
  api_key=os.getenv("api_key_4o"),
@@ -26,19 +109,23 @@ class BasicAgent():
26
  api_version="2025-01-01-preview"
27
  )
28
 
 
29
  # Outils disponibles
30
  tools = [
31
  DuckDuckGoSearchTool(), # Recherche web (Wikipedia)
32
  VisitWebpageTool(), # Visite de pages web
33
  PythonInterpreterTool(), # Calculs, Excel, traitement de données
34
  SpeechToTextTool(), # Speech to text
35
- #ImageCaptioningTool(), # Reconnaissance d'image
 
36
  ]
37
 
38
  # Créer l'agent Alfred avec les outils
39
  self.alfred = CodeAgent(
40
  tools=tools,
41
- model=self.model
 
 
42
  )
43
 
44
  print("Alfred agent ready with tools!")
@@ -69,8 +156,7 @@ class BasicAgent():
69
  2. USE the appropriate tool:
70
  - For mathematical calculations: use PythonCodeTool
71
  - To read Excel/CSV files: use PythonCodeTool with pandas
72
- - For information retrieval: use DuckDuckGoSearchTool, then VisitWebpageTool if needed
73
- - To analyze images: use ImageCaptioningTool
74
  - For speech-to-text: use SpeechToTextTool
75
  - For data processing: use PythonCodeTool
76
  - RETURN only the final answer, clearly and concisely.
@@ -78,12 +164,18 @@ class BasicAgent():
78
  If you cannot answer, simply say: "I cannot answer this question."
79
 
80
  Example answers:
81
- - For a calculation: "42"
82
  - For a date: "March 15, 2023"
83
  - For a name: "Albert Einstein"
84
- - For a number: "1,234,567"
85
  - For a list: "b, e"
86
 
 
 
 
 
 
 
 
87
  Here is the question to process: {question}"""
88
 
89
  # Utiliser Alfred pour traiter la question
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+ import requests
6
+ import openai
7
+ from smolagents.tools import Tool
8
+ import pathlib
9
+ from typing import Union, Optional
10
+ import pandas as pd
11
+ from dotenv import load_dotenv
12
+ # Load environment variables from .env file
13
+ load_dotenv()
14
+
15
 
16
  # (Keep Constants as is)
17
  # --- Constants ---
 
21
  # --- Basic Agent Definition ---
22
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
23
  import os
24
+
25
+ from smolagents import (
26
+ CodeAgent,
27
+ DuckDuckGoSearchTool,
28
+ VisitWebpageTool,
29
+ PythonInterpreterTool,
30
+ SpeechToTextTool,
31
+ WikipediaSearchTool,
32
+ Tool,
33
+ LiteLLMModel
34
+ )
35
+
36
+ class ExcelToTextTool(Tool):
37
+ """Render an Excel worksheet as Markdown text."""
38
+
39
+ # ------------------------------------------------------------------
40
+ # Required smol‑agents metadata
41
+ # ------------------------------------------------------------------
42
+ name = "excel_to_text"
43
+ description = (
44
+ "Read an Excel file and return a Markdown table of the requested sheet. "
45
+ "Accepts either the sheet name or the zero-based index."
46
+ )
47
+
48
+ inputs = {
49
+ "excel_path": {
50
+ "type": "string",
51
+ "description": "Path to the Excel file (.xlsx / .xls).",
52
+ },
53
+ "sheet_name": {
54
+ "type": "string",
55
+ "description": (
56
+ "Worksheet name or zero‑based index *as a string* (optional; default first sheet)."
57
+ ),
58
+ "nullable": True,
59
+ },
60
+ }
61
+
62
+ output_type = "string"
63
+
64
+ # ------------------------------------------------------------------
65
+ # Core logic
66
+ # ------------------------------------------------------------------
67
+ def forward(
68
+ self,
69
+ excel_path: str,
70
+ sheet_name: Optional[str] = None,
71
+ ) -> str:
72
+ """Load *excel_path* and return the sheet as a Markdown table."""
73
+
74
+ path = pathlib.Path(excel_path).expanduser().resolve()
75
+ if not path.exists():
76
+ return f"Error: Excel file not found at {path}"
77
+
78
+ try:
79
+ # Interpret sheet identifier -----------------------------------
80
+ sheet: Union[str, int]
81
+ if sheet_name is None or sheet_name == "":
82
+ sheet = 0 # first sheet
83
+ else:
84
+ # If the user passed a numeric string (e.g. "1"), cast to int
85
+ sheet = int(sheet_name) if sheet_name.isdigit() else sheet_name
86
+
87
+ # Load worksheet ----------------------------------------------
88
+ df = pd.read_excel(path, sheet_name=sheet)
89
+
90
+ # Render to Markdown; fall back to tabulate if needed ---------
91
+ if hasattr(pd.DataFrame, "to_markdown"):
92
+ return df.to_markdown(index=False)
93
+ from tabulate import tabulate # pragma: no cover – fallback path
94
+
95
+ return tabulate(df, headers="keys", tablefmt="github", showindex=False)
96
+
97
+ except Exception as exc: # broad catch keeps the agent chat‑friendly
98
+ return f"Error reading Excel file: {exc}"
99
+
100
 
101
  class BasicAgent():
102
  def __init__(self):
103
  print("MyCustomAgent with SmolaAgent initialized.")
104
 
 
105
  self.model = LiteLLMModel(
106
  model_id="azure/gpt-4o",
107
  api_key=os.getenv("api_key_4o"),
 
109
  api_version="2025-01-01-preview"
110
  )
111
 
112
+
113
  # Outils disponibles
114
  tools = [
115
  DuckDuckGoSearchTool(), # Recherche web (Wikipedia)
116
  VisitWebpageTool(), # Visite de pages web
117
  PythonInterpreterTool(), # Calculs, Excel, traitement de données
118
  SpeechToTextTool(), # Speech to text
119
+ WikipediaSearchTool(), # Recherche sur Wikipedia
120
+ ExcelToTextTool(), # Outil pour lire des fichiers Excel
121
  ]
122
 
123
  # Créer l'agent Alfred avec les outils
124
  self.alfred = CodeAgent(
125
  tools=tools,
126
+ model=self.model,
127
+ add_base_tools=True,
128
+ additional_authorized_imports=['pandas','numpy','csv','subprocess']
129
  )
130
 
131
  print("Alfred agent ready with tools!")
 
156
  2. USE the appropriate tool:
157
  - For mathematical calculations: use PythonCodeTool
158
  - To read Excel/CSV files: use PythonCodeTool with pandas
159
+ - For information retrieval: use DuckDuckGoSearchTool, then VisitWebpageTool if needed or WikipediaSearchTool
 
160
  - For speech-to-text: use SpeechToTextTool
161
  - For data processing: use PythonCodeTool
162
  - RETURN only the final answer, clearly and concisely.
 
164
  If you cannot answer, simply say: "I cannot answer this question."
165
 
166
  Example answers:
167
+ - For a calculation or number : "42"
168
  - For a date: "March 15, 2023"
169
  - For a name: "Albert Einstein"
 
170
  - For a list: "b, e"
171
 
172
+ Formatting rules:
173
+ - If it's a number, do not use commas or units unless explicitly required.
174
+ - If it's a string, do not use articles or abbreviations unless they are part of the correct literal.
175
+ - If it's a comma-separated list, return items in correct order like: a, b, c
176
+ - Do not add any quotation marks, punctuation, or extra text.
177
+ - Do not start your answer with any words. Just give the result.
178
+
179
  Here is the question to process: {question}"""
180
 
181
  # Utiliser Alfred pour traiter la question