Mehedi2 commited on
Commit
a80fafc
·
verified ·
1 Parent(s): a55fd4b

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +118 -117
agent.py CHANGED
@@ -1,117 +1,118 @@
1
- import os
2
- from pathlib import Path
3
- from typing import Optional, Union
4
-
5
- import pandas as pd
6
- from dotenv import load_dotenv
7
- from smolagents import (CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool,
8
- LiteLLMModel, PythonInterpreterTool,
9
- WikipediaSearchTool)
10
- from smolagents.tools import Tool
11
- from tabulate import tabulate
12
-
13
- # Load environment variables
14
- load_dotenv()
15
-
16
- # Initialize the model
17
- model = LiteLLMModel(
18
- model_id=os.getenv("GEMINI_MODEL"), api_key=os.getenv("GEMINI_API_KEY")
19
- )
20
-
21
-
22
- class ExcelToTextTool(Tool):
23
- """Render an Excel worksheet as a Markdown table."""
24
-
25
- name = "excel_to_text"
26
- description = (
27
- "Read an Excel file and return a Markdown table of the requested sheet. "
28
- "Accepts either the sheet name or a zero-based index (as a string)."
29
- )
30
-
31
- inputs = {
32
- "excel_path": {
33
- "type": "string",
34
- "description": "Path to the Excel file (.xlsx or .xls).",
35
- },
36
- "sheet_name": {
37
- "type": "string",
38
- "description": (
39
- "Worksheet name or zero-based index (as a string). "
40
- "Optional; defaults to the first sheet."
41
- ),
42
- "nullable": True,
43
- },
44
- }
45
-
46
- output_type = "string"
47
-
48
- def forward(self, excel_path: str, sheet_name: Optional[str] = None) -> str:
49
- """Load the Excel file and return the sheet as a Markdown table.
50
-
51
- Args:
52
- excel_path: Path to the Excel file.
53
- sheet_name: Optional name or index of the sheet to read. If None, reads the first sheet.
54
-
55
- Returns:
56
- A Markdown table representing the Excel sheet, or an error message if the file is not found or cannot be read.
57
- """
58
-
59
- file_path = Path(excel_path).expanduser().resolve()
60
- if not file_path.is_file():
61
- return f"Error: Excel file not found at {file_path}"
62
-
63
- try:
64
- sheet: Union[str, int] = (
65
- int(sheet_name)
66
- if sheet_name and sheet_name.isdigit()
67
- else sheet_name or 0
68
- )
69
-
70
- df = pd.read_excel(file_path, sheet_name=sheet)
71
-
72
- if hasattr(df, "to_markdown"):
73
- return df.to_markdown(index=False)
74
-
75
- return tabulate(df, headers="keys", tablefmt="github", showindex=False)
76
-
77
- except Exception as e:
78
- return f"Error reading Excel file: {e}"
79
-
80
-
81
- class GaiaAgent:
82
- """An agent capable of using tools to answer general questions."""
83
-
84
- def __init__(self):
85
- """Initializes the GaiaAgent with a set of tools."""
86
-
87
- print("GaiaAgent initialized with tools.")
88
-
89
- tools = [
90
- DuckDuckGoSearchTool(),
91
- WikipediaSearchTool(),
92
- ExcelToTextTool(),
93
- PythonInterpreterTool(),
94
- FinalAnswerTool(),
95
- ]
96
-
97
- self.agent = CodeAgent(
98
- model=model,
99
- tools=tools,
100
- add_base_tools=True,
101
- additional_authorized_imports=["pandas", "numpy", "csv", "subprocess"],
102
- )
103
-
104
- def __call__(self, task_id: str, question: str) -> str:
105
- """Processes a question using the agent and its tools.
106
-
107
- Args:
108
- task_id: A unique identifier for the task.
109
- question: The question to be answered.
110
-
111
- Returns:
112
- The answer generated by the agent.
113
- """
114
- print(f"Agent received task_id='{task_id}' | question='{question[:50]}...'")
115
- answer = self.agent.run(question)
116
- print(f"Agent returning answer: {answer}")
117
- return answer
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Optional, Union
4
+ import smolagent
5
+
6
+ import pandas as pd
7
+ from dotenv import load_dotenv
8
+ from smolagents import (CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool,
9
+ LiteLLMModel, PythonInterpreterTool,
10
+ WikipediaSearchTool)
11
+ from smolagents.tools import Tool
12
+ from tabulate import tabulate
13
+
14
+ # Load environment variables
15
+ load_dotenv()
16
+
17
+ # Initialize the model
18
+ model = LiteLLMModel(
19
+ model_id=os.getenv("GEMINI_MODEL"), api_key=os.getenv("GEMINI_API_KEY")
20
+ )
21
+
22
+
23
+ class ExcelToTextTool(Tool):
24
+ """Render an Excel worksheet as a Markdown table."""
25
+
26
+ name = "excel_to_text"
27
+ description = (
28
+ "Read an Excel file and return a Markdown table of the requested sheet. "
29
+ "Accepts either the sheet name or a zero-based index (as a string)."
30
+ )
31
+
32
+ inputs = {
33
+ "excel_path": {
34
+ "type": "string",
35
+ "description": "Path to the Excel file (.xlsx or .xls).",
36
+ },
37
+ "sheet_name": {
38
+ "type": "string",
39
+ "description": (
40
+ "Worksheet name or zero-based index (as a string). "
41
+ "Optional; defaults to the first sheet."
42
+ ),
43
+ "nullable": True,
44
+ },
45
+ }
46
+
47
+ output_type = "string"
48
+
49
+ def forward(self, excel_path: str, sheet_name: Optional[str] = None) -> str:
50
+ """Load the Excel file and return the sheet as a Markdown table.
51
+
52
+ Args:
53
+ excel_path: Path to the Excel file.
54
+ sheet_name: Optional name or index of the sheet to read. If None, reads the first sheet.
55
+
56
+ Returns:
57
+ A Markdown table representing the Excel sheet, or an error message if the file is not found or cannot be read.
58
+ """
59
+
60
+ file_path = Path(excel_path).expanduser().resolve()
61
+ if not file_path.is_file():
62
+ return f"Error: Excel file not found at {file_path}"
63
+
64
+ try:
65
+ sheet: Union[str, int] = (
66
+ int(sheet_name)
67
+ if sheet_name and sheet_name.isdigit()
68
+ else sheet_name or 0
69
+ )
70
+
71
+ df = pd.read_excel(file_path, sheet_name=sheet)
72
+
73
+ if hasattr(df, "to_markdown"):
74
+ return df.to_markdown(index=False)
75
+
76
+ return tabulate(df, headers="keys", tablefmt="github", showindex=False)
77
+
78
+ except Exception as e:
79
+ return f"Error reading Excel file: {e}"
80
+
81
+
82
+ class GaiaAgent:
83
+ """An agent capable of using tools to answer general questions."""
84
+
85
+ def __init__(self):
86
+ """Initializes the GaiaAgent with a set of tools."""
87
+
88
+ print("GaiaAgent initialized with tools.")
89
+
90
+ tools = [
91
+ DuckDuckGoSearchTool(),
92
+ WikipediaSearchTool(),
93
+ ExcelToTextTool(),
94
+ PythonInterpreterTool(),
95
+ FinalAnswerTool(),
96
+ ]
97
+
98
+ self.agent = CodeAgent(
99
+ model=model,
100
+ tools=tools,
101
+ add_base_tools=True,
102
+ additional_authorized_imports=["pandas", "numpy", "csv", "subprocess"],
103
+ )
104
+
105
+ def __call__(self, task_id: str, question: str) -> str:
106
+ """Processes a question using the agent and its tools.
107
+
108
+ Args:
109
+ task_id: A unique identifier for the task.
110
+ question: The question to be answered.
111
+
112
+ Returns:
113
+ The answer generated by the agent.
114
+ """
115
+ print(f"Agent received task_id='{task_id}' | question='{question[:50]}...'")
116
+ answer = self.agent.run(question)
117
+ print(f"Agent returning answer: {answer}")
118
+ return answer