stivenDR14 commited on
Commit
97e737a
·
1 Parent(s): 89e5d16

agent file cleaned

Browse files
Files changed (2) hide show
  1. agent.py +4 -94
  2. app.py +4 -0
agent.py CHANGED
@@ -1,5 +1,5 @@
1
  """
2
- Intelligent AI Agent using LlamaIndex with CodeAct capabilities
3
  This module contains the agent class with advanced tools and reasoning.
4
  """
5
 
@@ -23,17 +23,14 @@ except Exception as e:
23
 
24
  # LlamaIndex imports
25
  try:
26
- from llama_index.core.agent.workflow import CodeActAgent
27
- from llama_index.core.workflow import Context
28
  from llama_index.core.agent.workflow import (
29
  ToolCall,
30
  ToolCallResult,
31
  FunctionAgent,
32
  AgentStream,
33
  )
34
- from llama_index.llms.huggingface import HuggingFaceLLM
35
  from llama_index.core.tools import FunctionTool
36
- from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec
37
  from llama_index.tools.wikipedia import WikipediaToolSpec
38
  from llama_index.tools.tavily_research.base import TavilyToolSpec
39
  #from llama_index.llms.ollama import Ollama
@@ -44,59 +41,7 @@ except ImportError as e:
44
  print(f"LlamaIndex imports not available: {e}")
45
  LLAMA_INDEX_AVAILABLE = False
46
 
47
- MODEL = "microsoft/Phi-3.5-mini-instruct"
48
-
49
- class SimpleCodeExecutor:
50
- """
51
- A simple code executor that runs Python code with state persistence.
52
- NOTE: not safe for production use! Use with caution.
53
- """
54
-
55
- def __init__(self, locals_dict: Dict[str, Any], globals_dict: Dict[str, Any]):
56
- """Initialize the code executor."""
57
- self.globals = globals_dict
58
- self.locals = locals_dict
59
-
60
- def execute(self, code: str) -> Tuple[bool, str, Any]:
61
- """Execute Python code and capture output and return values."""
62
- stdout = io.StringIO()
63
- stderr = io.StringIO()
64
-
65
- output = ""
66
- return_value = None
67
- try:
68
- with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
69
- try:
70
- tree = ast.parse(code)
71
- last_node = tree.body[-1] if tree.body else None
72
-
73
- if isinstance(last_node, ast.Expr):
74
- last_line = code.rstrip().split("\n")[-1]
75
- exec_code = (
76
- code[: -len(last_line)]
77
- + "\n__result__ = "
78
- + last_line
79
- )
80
- exec(exec_code, self.globals, self.locals)
81
- return_value = self.locals.get("__result__")
82
- else:
83
- exec(code, self.globals, self.locals)
84
- except:
85
- exec(code, self.globals, self.locals)
86
-
87
- output = stdout.getvalue()
88
- if stderr.getvalue():
89
- output += "\n" + stderr.getvalue()
90
-
91
- except Exception as e:
92
- output = f"Error: {type(e).__name__}: {str(e)}\n"
93
- output += traceback.format_exc()
94
-
95
- if return_value is not None:
96
- output += "\n\n" + str(return_value)
97
-
98
- return output
99
-
100
 
101
  class BasicAgent:
102
  """
@@ -248,41 +193,6 @@ class BasicAgent:
248
 
249
  print(f"✅ Total {len(self.tools)} tools initialized")
250
 
251
- def _initialize_code_executor(self):
252
- """Initialize the code executor with necessary imports and functions."""
253
- # Prepare locals with math functions
254
- code_locals = {
255
- "add_numbers": lambda a, b: a + b,
256
- "subtract_numbers": lambda a, b: a - b,
257
- "multiply_numbers": lambda a, b: a * b,
258
- "divide_numbers": lambda a, b: a / b if b != 0 else "Error: Division by zero",
259
- "power_numbers": lambda a, b: a ** b,
260
- "calculate_percentage": lambda v, p: (v * p) / 100,
261
- }
262
-
263
- # Prepare globals with common imports
264
- code_globals = {
265
- "__builtins__": __builtins__,
266
- "math": __import__("math"),
267
- "datetime": __import__("datetime"),
268
- "json": __import__("json"),
269
- "re": __import__("re"),
270
- }
271
-
272
- try:
273
- code_globals["numpy"] = __import__("numpy")
274
- code_globals["np"] = code_globals["numpy"]
275
- except ImportError:
276
- pass
277
-
278
- try:
279
- code_globals["pandas"] = __import__("pandas")
280
- code_globals["pd"] = code_globals["pandas"]
281
- except ImportError:
282
- pass
283
-
284
- self.code_executor = SimpleCodeExecutor(code_locals, code_globals)
285
- print("✅ Code executor initialized")
286
 
287
  def _initialize_agent(self):
288
  """Initialize the CodeAct Agent (deferred initialization)."""
@@ -354,7 +264,7 @@ class BasicAgent:
354
  response = await self._async_agent_run(question)
355
  return response
356
  except Exception as e:
357
- print(f"Error with CodeAct agent: {e}")
358
  return f"FINAL ANSWER: Error processing question - {str(e)}"
359
  else:
360
  return "FINAL ANSWER: Agent not properly initialized"
 
1
  """
2
+ Intelligent AI Agent using LlamaIndex with websearch capabilities
3
  This module contains the agent class with advanced tools and reasoning.
4
  """
5
 
 
23
 
24
  # LlamaIndex imports
25
  try:
 
 
26
  from llama_index.core.agent.workflow import (
27
  ToolCall,
28
  ToolCallResult,
29
  FunctionAgent,
30
  AgentStream,
31
  )
32
+ #from llama_index.llms.huggingface import HuggingFaceLLM
33
  from llama_index.core.tools import FunctionTool
 
34
  from llama_index.tools.wikipedia import WikipediaToolSpec
35
  from llama_index.tools.tavily_research.base import TavilyToolSpec
36
  #from llama_index.llms.ollama import Ollama
 
41
  print(f"LlamaIndex imports not available: {e}")
42
  LLAMA_INDEX_AVAILABLE = False
43
 
44
+ #MODEL = "microsoft/Phi-3.5-mini-instruct"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  class BasicAgent:
47
  """
 
193
 
194
  print(f"✅ Total {len(self.tools)} tools initialized")
195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
  def _initialize_agent(self):
198
  """Initialize the CodeAct Agent (deferred initialization)."""
 
264
  response = await self._async_agent_run(question)
265
  return response
266
  except Exception as e:
267
+ print(f"Error with agent: {e}")
268
  return f"FINAL ANSWER: Error processing question - {str(e)}"
269
  else:
270
  return "FINAL ANSWER: Agent not properly initialized"
app.py CHANGED
@@ -162,6 +162,10 @@ with gr.Blocks() as demo:
162
  **Disclaimers:**
163
  Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
164
  This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
 
 
 
 
165
  """
166
  )
167
 
 
162
  **Disclaimers:**
163
  Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
164
  This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
165
+
166
+ ---
167
+ My certificate of completion: [![Certificate](https://huggingface.co/datasets/agents-course/final-certificates/resolve/main/certificates/stiv14/2025-06-27.png)](https://huggingface.co/datasets/agents-course/final-certificates/resolve/main/certificates/stiv14/2025-06-27.png)
168
+
169
  """
170
  )
171