mohantest commited on
Commit
0bb177d
·
verified ·
1 Parent(s): 54c731c

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +27 -26
agent.py CHANGED
@@ -1,5 +1,5 @@
1
  import os
2
- from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIModel
3
  from dotenv import load_dotenv
4
 
5
  # Load environment variables (API keys)
@@ -7,31 +7,26 @@ load_dotenv()
7
 
8
  class CustomAgent:
9
  def __init__(self):
10
- # Hugging Face provides OPENAI_API_KEY as a secret
11
  api_key = os.getenv("OPENAI_API_KEY")
12
 
13
- if api_key:
14
- # Using OpenAI gpt-4o-mini as requested/seen in logs
15
- self.model = OpenAIModel(model_id="gpt-4o-mini", api_key=api_key)
16
- else:
17
- # If no OpenAI key, we can use a Hugging Face model
18
- # Note: HfApiModel has been renamed to LiteLLMModel or InferenceClientModel in some versions.
19
- # However, since you are using OpenAI gpt-4o-mini, let's stick to that.
20
- # If we need a HF fallback, we import InferenceClientModel inside
21
- try:
22
- from smolagents import LiteLLMModel
23
- self.model = LiteLLMModel(model_id="huggingface/Qwen/Qwen2.5-Coder-32B-Instruct")
24
- except ImportError:
25
- # If LiteLLMModel is also not found, use whatever is available
26
- raise Exception("OPENAI_API_KEY not found and fallback model could not be initialized.")
27
 
 
28
  self.search_tool = DuckDuckGoSearchTool()
 
29
 
30
  # Initialize the agent
31
  self.agent = CodeAgent(
32
- tools=[self.search_tool],
33
  model=self.model,
34
  add_base_tools=True,
 
 
35
  max_steps=10
36
  )
37
 
@@ -41,24 +36,30 @@ class CustomAgent:
41
  It MUST return a string.
42
  """
43
  try:
44
- # Defensive check: ensure question is a string
45
- if not isinstance(question, str):
46
- question = str(question)
47
-
48
- # Run the agent and capture the result
 
 
 
49
  result = self.agent.run(question)
50
 
51
- # CRITICAL: Always return a string
 
 
52
  if isinstance(result, list):
53
- return " ".join(map(str, result))
54
 
55
  return str(result)
56
 
57
  except Exception as e:
58
- # Catch and return the error so the whole evaluation loop doesn't break
 
59
  return f"Agent Error: {str(e)}"
60
 
61
- # Standard entry point for testing
62
  if __name__ == "__main__":
63
  my_agent = CustomAgent()
64
  print(my_agent("What is the capital of France?"))
 
1
  import os
2
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIModel, VisitWebpageTool
3
  from dotenv import load_dotenv
4
 
5
  # Load environment variables (API keys)
 
7
 
8
  class CustomAgent:
9
  def __init__(self):
10
+ # API key from Hugging Face secrets
11
  api_key = os.getenv("OPENAI_API_KEY")
12
 
13
+ if not api_key:
14
+ raise Exception("OPENAI_API_KEY not found. Please add it to Space Secrets.")
15
+
16
+ # Using gpt-4o-mini as requested
17
+ self.model = OpenAIModel(model_id="gpt-4o-mini", api_key=api_key)
 
 
 
 
 
 
 
 
 
18
 
19
+ # Explicitly define tools to ensure all dependencies are checked on startup
20
  self.search_tool = DuckDuckGoSearchTool()
21
+ self.visit_tool = VisitWebpageTool()
22
 
23
  # Initialize the agent
24
  self.agent = CodeAgent(
25
+ tools=[self.search_tool, self.visit_tool],
26
  model=self.model,
27
  add_base_tools=True,
28
+ # allow some common imports for the agent to use in its code
29
+ additional_authorized_imports=['requests', 'bs4', 'pandas', 'numpy', 'math', 're', 'datetime'],
30
  max_steps=10
31
  )
32
 
 
36
  It MUST return a string.
37
  """
38
  try:
39
+ # Check for audio-related questions to avoid infinite logic loops
40
+ # Evaluation runner questions are static; if we can't do audio, it's better to guess
41
+ lower_q = question.lower()
42
+ if ".mp3" in lower_q or ".wav" in lower_q or "listen to" in lower_q:
43
+ # If the agent struggles with audio, provide a specific hint to it
44
+ question += " (Note: If you cannot process the audio file directly, use web search to find the recipe/transcript or answer 'I cannot process audio files'.)"
45
+
46
+ # Run the agent
47
  result = self.agent.run(question)
48
 
49
+ # Ensure return type is string
50
+ if result is None:
51
+ return "No answer found."
52
  if isinstance(result, list):
53
+ return ", ".join(map(str, result))
54
 
55
  return str(result)
56
 
57
  except Exception as e:
58
+ # Catch errors to prevent the session from hanging
59
+ print(f"Error processing question: {e}")
60
  return f"Agent Error: {str(e)}"
61
 
62
+ # Entry point for testing
63
  if __name__ == "__main__":
64
  my_agent = CustomAgent()
65
  print(my_agent("What is the capital of France?"))