Chris4K commited on
Commit
5ae0277
·
verified ·
1 Parent(s): 5f3ea76

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -41
app.py CHANGED
@@ -1,9 +1,11 @@
1
- """Run hf agent."""
2
  # pylint: disable=line-too-long, broad-exception-caught
3
  import datetime
4
  import pytz
5
  import yaml
6
  import re
 
 
7
  from Gradio_UI import GradioUI
8
  from loguru import logger
9
  from smolagents import (
@@ -15,16 +17,45 @@ from smolagents import (
15
  from tools.final_answer import FinalAnswerTool
16
  from tools.visit_webpage import VisitWebpageTool
17
 
18
- # Custom tool example
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  @tool
20
- def my_custom_tool(arg1: str, arg2: int) -> str: # it's important to specify the return type
21
  """
22
- Run a tool that does nothing yet.
23
  Args:
24
- arg1: the first argument
25
- arg2: the second argument
26
  """
27
- return f"What magic will you build? {arg1=}, {arg2=}"
 
 
 
 
 
 
28
 
29
  @tool
30
  def get_current_time_in_timezone(timezone: str) -> str:
@@ -40,49 +71,126 @@ def get_current_time_in_timezone(timezone: str) -> str:
40
  # Get current time in that timezone
41
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
42
  return f"The current local time in {timezone} is: {local_time}"
 
 
 
43
  except Exception as e:
44
- logger.error(e)
45
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
46
 
47
- # Initialize tools
48
- final_answer = FinalAnswerTool()
49
- visit_webpage = VisitWebpageTool()
50
- model = HfApiModel()
51
 
52
- # Import tool from Hub
53
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
- # Load prompt templates
56
- with open("prompts.yaml", "r", encoding="utf8") as stream:
57
- prompt_templates = yaml.safe_load(stream)
58
 
59
- # Add the missing 'final_answer' template if it doesn't exist
60
- if 'final_answer' not in prompt_templates:
61
- prompt_templates['final_answer'] = "{{final_answer}}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- # Create the agent
64
- agent = CodeAgent(
65
- model=model,
66
- tools=[
67
  my_custom_tool,
68
  get_current_time_in_timezone,
69
  final_answer,
70
  visit_webpage,
71
- image_generation_tool, # Added the image generation tool
72
- ], # add your tools here
73
- max_steps=6,
74
- verbosity_level=1,
75
- grammar=None,
76
- planning_interval=None,
77
- name=None,
78
- description=None,
79
- prompt_templates=prompt_templates,
80
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- # Launch the Gradio UI
83
- ssr = True
84
- GradioUI(agent).launch(
85
- # debug=True,
86
- # share=True,
87
- ssr=ssr,
88
- )
 
1
+ """Run enhanced hf agent with improved capabilities."""
2
  # pylint: disable=line-too-long, broad-exception-caught
3
  import datetime
4
  import pytz
5
  import yaml
6
  import re
7
+ import os
8
+ from pathlib import Path
9
  from Gradio_UI import GradioUI
10
  from loguru import logger
11
  from smolagents import (
 
17
  from tools.final_answer import FinalAnswerTool
18
  from tools.visit_webpage import VisitWebpageTool
19
 
20
+
21
+ # Enhanced configuration with environment variables and defaults
22
+ class AgentConfig:
23
+ def __init__(self):
24
+ self.max_steps = int(os.environ.get("AGENT_MAX_STEPS", "8"))
25
+ self.verbosity_level = int(os.environ.get("AGENT_VERBOSITY", "1"))
26
+ self.planning_interval = int(os.environ.get("AGENT_PLANNING_INTERVAL", "3"))
27
+ self.model_name = os.environ.get("AGENT_MODEL", "default")
28
+ self.debug = os.environ.get("AGENT_DEBUG", "false").lower() == "true"
29
+ self.share = os.environ.get("AGENT_SHARE", "false").lower() == "true"
30
+ self.ssr = os.environ.get("AGENT_SSR", "true").lower() == "true"
31
+
32
+ # Create log directory
33
+ log_dir = Path("logs")
34
+ log_dir.mkdir(exist_ok=True)
35
+ now = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
36
+ self.log_file = log_dir / f"agent_run_{now}.log"
37
+
38
+ # Setup logging
39
+ logger.add(self.log_file, rotation="100 MB")
40
+ logger.info(f"Agent configuration initialized: {self.__dict__}")
41
+
42
+
43
+ # Custom tool example with better error handling
44
  @tool
45
+ def my_custom_tool(arg1: str, arg2: int) -> str:
46
  """
47
+ Run a tool that demonstrates custom functionality.
48
  Args:
49
+ arg1: the first argument (string)
50
+ arg2: the second argument (integer)
51
  """
52
+ logger.debug(f"my_custom_tool called with {arg1=}, {arg2=}")
53
+ try:
54
+ return f"Custom tool processed: {arg1} with value {arg2}"
55
+ except Exception as e:
56
+ logger.error(f"Error in my_custom_tool: {e}")
57
+ return f"Error processing request: {str(e)}"
58
+
59
 
60
  @tool
61
  def get_current_time_in_timezone(timezone: str) -> str:
 
71
  # Get current time in that timezone
72
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
73
  return f"The current local time in {timezone} is: {local_time}"
74
+ except pytz.exceptions.UnknownTimeZoneError:
75
+ logger.warning(f"Unknown timezone: {timezone}")
76
+ return f"Error: '{timezone}' is not a recognized timezone. Please use a valid timezone like 'America/New_York' or 'Asia/Tokyo'."
77
  except Exception as e:
78
+ logger.error(f"Error in get_current_time_in_timezone: {e}")
79
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
80
 
 
 
 
 
81
 
82
+ # Helper function to ensure all required templates exist
83
+ def ensure_complete_templates(templates):
84
+ """Ensure all required templates exist and provide defaults if needed."""
85
+ required_templates = [
86
+ "system_prompt", "final_answer",
87
+ "planning.initial_facts", "planning.initial_plan",
88
+ "planning.update_facts_pre_messages", "planning.update_facts_post_messages",
89
+ "planning.update_plan_pre_messages", "planning.update_plan_post_messages"
90
+ ]
91
+
92
+ # Check if nested keys exist and create them if not
93
+ for template in required_templates:
94
+ if "." in template:
95
+ parent, child = template.split(".", 1)
96
+ if parent not in templates:
97
+ templates[parent] = {}
98
+ if child not in templates[parent]:
99
+ logger.warning(f"Missing template {template}, using default")
100
+ # Set a minimal default
101
+ templates[parent][child] = f"{{{{ {child.replace('_', ' ')} }}}}"
102
+ elif template not in templates:
103
+ logger.warning(f"Missing template {template}, using default")
104
+ # Set a minimal default
105
+ templates[template] = f"{{{{ {template.replace('_', ' ')} }}}}"
106
+
107
+ return templates
108
 
 
 
 
109
 
110
+ def main():
111
+ """Main function to set up and run the agent."""
112
+ config = AgentConfig()
113
+
114
+ # Initialize tools with better error handling
115
+ final_answer = FinalAnswerTool()
116
+ visit_webpage = VisitWebpageTool()
117
+
118
+ # Use try-except for more resilient model loading
119
+ try:
120
+ model = HfApiModel(model_name=config.model_name)
121
+ logger.info(f"Successfully loaded model: {config.model_name}")
122
+ except Exception as e:
123
+ logger.error(f"Error loading model {config.model_name}: {e}")
124
+ logger.info("Falling back to default model")
125
+ model = HfApiModel()
126
+
127
+ # Import tool from Hub with error handling
128
+ try:
129
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
130
+ logger.info("Successfully loaded image generation tool")
131
+ except Exception as e:
132
+ logger.error(f"Error loading image generation tool: {e}")
133
+ image_generation_tool = None
134
+
135
+ # Load prompt templates with fallback
136
+ prompt_templates = {}
137
+ try:
138
+ with open("prompts.yaml", "r", encoding="utf8") as stream:
139
+ prompt_templates = yaml.safe_load(stream) or {}
140
+ logger.info("Successfully loaded prompts.yaml")
141
+ except Exception as e:
142
+ logger.error(f"Error loading prompts.yaml: {e}")
143
+ logger.info("Using default templates")
144
+
145
+ # Ensure all required templates exist
146
+ prompt_templates = ensure_complete_templates(prompt_templates)
147
 
148
+ # Prepare tools list with available tools
149
+ tools = [
 
 
150
  my_custom_tool,
151
  get_current_time_in_timezone,
152
  final_answer,
153
  visit_webpage,
154
+ ]
155
+
156
+ if image_generation_tool:
157
+ tools.append(image_generation_tool)
158
+
159
+ # Create the agent with enhanced configuration
160
+ agent = CodeAgent(
161
+ model=model,
162
+ tools=tools,
163
+ max_steps=config.max_steps,
164
+ verbosity_level=config.verbosity_level,
165
+ grammar=None,
166
+ planning_interval=config.planning_interval, # Enable periodic replanning
167
+ name="EnhancedAgent", # Give the agent a name
168
+ description="An enhanced CodeAgent with improved capabilities",
169
+ prompt_templates=prompt_templates,
170
+ )
171
+
172
+ # Add hooks for better monitoring (available in smolagents)
173
+ @agent.add_hook("before_step")
174
+ def log_step(agent, step_number):
175
+ logger.info(f"Starting step {step_number}/{agent.max_steps}")
176
+
177
+ @agent.add_hook("after_step")
178
+ def analyze_step(agent, step_number, thought, code, observation):
179
+ logger.info(f"Completed step {step_number}")
180
+ if "error" in observation.lower():
181
+ logger.warning(f"Potential error in step {step_number}: {observation[:100]}...")
182
+
183
+ # Launch the Gradio UI with configured settings
184
+ try:
185
+ GradioUI(agent).launch(
186
+ debug=config.debug,
187
+ share=config.share,
188
+ ssr=config.ssr,
189
+ )
190
+ except Exception as e:
191
+ logger.critical(f"Failed to launch UI: {e}")
192
+ print(f"Critical error: Failed to launch UI: {e}")
193
+
194
 
195
+ if __name__ == "__main__":
196
+ main()