Update app.py
Browse files
app.py
CHANGED
@@ -1,12 +1,9 @@
|
|
1 |
-
"""
|
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 (
|
12 |
CodeAgent,
|
@@ -18,43 +15,16 @@ from tools.final_answer import FinalAnswerTool
|
|
18 |
from tools.visit_webpage import VisitWebpageTool
|
19 |
|
20 |
|
21 |
-
#
|
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
|
48 |
Args:
|
49 |
-
arg1: the first argument
|
50 |
-
arg2: the second argument
|
51 |
"""
|
52 |
-
|
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
|
@@ -71,81 +41,83 @@ 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(
|
79 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
80 |
|
81 |
|
82 |
-
#
|
83 |
-
|
84 |
-
"""
|
85 |
-
|
86 |
-
"
|
87 |
-
"
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
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
|
111 |
-
"""
|
112 |
-
|
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
|
136 |
-
prompt_templates =
|
137 |
try:
|
138 |
with open("prompts.yaml", "r", encoding="utf8") as stream:
|
139 |
-
|
140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
141 |
except Exception as e:
|
142 |
logger.error(f"Error loading prompts.yaml: {e}")
|
143 |
logger.info("Using default templates")
|
144 |
|
145 |
-
#
|
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,
|
@@ -156,31 +128,80 @@ def main():
|
|
156 |
if image_generation_tool:
|
157 |
tools.append(image_generation_tool)
|
158 |
|
159 |
-
# Create the agent
|
160 |
-
|
161 |
model=model,
|
162 |
tools=tools,
|
163 |
-
max_steps=
|
164 |
-
verbosity_level=
|
165 |
grammar=None,
|
166 |
-
planning_interval=
|
167 |
-
name="
|
168 |
-
description="
|
169 |
prompt_templates=prompt_templates,
|
170 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
171 |
|
172 |
-
|
173 |
-
# Launch the Gradio UI with configured settings
|
174 |
try:
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
179 |
)
|
|
|
180 |
except Exception as e:
|
181 |
-
logger.
|
182 |
-
print(f"Critical error:
|
183 |
|
184 |
|
185 |
if __name__ == "__main__":
|
186 |
-
|
|
|
1 |
+
"""Modified Gradio UI integration to fix type errors."""
|
2 |
# pylint: disable=line-too-long, broad-exception-caught
|
3 |
import datetime
|
4 |
import pytz
|
5 |
import yaml
|
6 |
import re
|
|
|
|
|
|
|
7 |
from loguru import logger
|
8 |
from smolagents import (
|
9 |
CodeAgent,
|
|
|
15 |
from tools.visit_webpage import VisitWebpageTool
|
16 |
|
17 |
|
18 |
+
# Custom tools
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
@tool
|
20 |
def my_custom_tool(arg1: str, arg2: int) -> str:
|
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 |
|
30 |
@tool
|
|
|
41 |
# Get current time in that timezone
|
42 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
43 |
return f"The current local time in {timezone} is: {local_time}"
|
|
|
|
|
|
|
44 |
except Exception as e:
|
45 |
+
logger.error(e)
|
46 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
47 |
|
48 |
|
49 |
+
# Define our default prompt templates with the correct structure
|
50 |
+
DEFAULT_PROMPTS = {
|
51 |
+
"system_prompt": "You are an expert assistant who can solve any task using code blobs.",
|
52 |
+
"final_answer": {
|
53 |
+
"pre_messages": "Here is the final answer to your question:",
|
54 |
+
"post_messages": "Hope this helps!"
|
55 |
+
},
|
56 |
+
"planning": {
|
57 |
+
"initial_facts": "First, let's identify what we know and what we need to find out.",
|
58 |
+
"initial_plan": "Let's develop a step-by-step plan to solve this task.",
|
59 |
+
"update_facts_pre_messages": "Let's update what we know based on our progress.",
|
60 |
+
"update_facts_post_messages": "Here's our updated knowledge about the task.",
|
61 |
+
"update_plan_pre_messages": "Let's review our plan based on what we've learned.",
|
62 |
+
"update_plan_post_messages": "Here's our revised plan to complete the task."
|
63 |
+
}
|
64 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
|
67 |
+
def create_agent():
|
68 |
+
"""Create and configure the agent with proper error handling."""
|
69 |
+
# Initialize tools
|
|
|
|
|
70 |
final_answer = FinalAnswerTool()
|
71 |
visit_webpage = VisitWebpageTool()
|
72 |
|
|
|
73 |
try:
|
|
|
|
|
|
|
|
|
|
|
74 |
model = HfApiModel()
|
75 |
+
logger.info("Successfully loaded model")
|
76 |
+
except Exception as e:
|
77 |
+
logger.error(f"Error loading model: {e}")
|
78 |
+
raise RuntimeError(f"Failed to initialize model: {e}")
|
79 |
|
80 |
+
# Import tool from Hub with proper error handling
|
81 |
try:
|
82 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
83 |
logger.info("Successfully loaded image generation tool")
|
84 |
except Exception as e:
|
85 |
logger.error(f"Error loading image generation tool: {e}")
|
86 |
image_generation_tool = None
|
87 |
+
|
88 |
+
# Load prompt templates or use defaults
|
89 |
+
prompt_templates = DEFAULT_PROMPTS.copy()
|
90 |
try:
|
91 |
with open("prompts.yaml", "r", encoding="utf8") as stream:
|
92 |
+
loaded_prompts = yaml.safe_load(stream)
|
93 |
+
if loaded_prompts:
|
94 |
+
# Update system prompt if available
|
95 |
+
if "system_prompt" in loaded_prompts:
|
96 |
+
prompt_templates["system_prompt"] = loaded_prompts["system_prompt"]
|
97 |
+
|
98 |
+
# Handle final_answer format
|
99 |
+
if "final_answer" in loaded_prompts:
|
100 |
+
if isinstance(loaded_prompts["final_answer"], dict):
|
101 |
+
if "pre_messages" in loaded_prompts["final_answer"]:
|
102 |
+
prompt_templates["final_answer"]["pre_messages"] = loaded_prompts["final_answer"]["pre_messages"]
|
103 |
+
if "post_messages" in loaded_prompts["final_answer"]:
|
104 |
+
prompt_templates["final_answer"]["post_messages"] = loaded_prompts["final_answer"]["post_messages"]
|
105 |
+
else:
|
106 |
+
# String format, use as pre_messages
|
107 |
+
prompt_templates["final_answer"]["pre_messages"] = loaded_prompts["final_answer"]
|
108 |
+
|
109 |
+
# Handle planning section
|
110 |
+
if "planning" in loaded_prompts and isinstance(loaded_prompts["planning"], dict):
|
111 |
+
for key in prompt_templates["planning"]:
|
112 |
+
if key in loaded_prompts["planning"]:
|
113 |
+
prompt_templates["planning"][key] = loaded_prompts["planning"][key]
|
114 |
+
|
115 |
+
logger.info("Successfully merged prompt templates")
|
116 |
except Exception as e:
|
117 |
logger.error(f"Error loading prompts.yaml: {e}")
|
118 |
logger.info("Using default templates")
|
119 |
|
120 |
+
# Prepare tools list
|
|
|
|
|
|
|
121 |
tools = [
|
122 |
my_custom_tool,
|
123 |
get_current_time_in_timezone,
|
|
|
128 |
if image_generation_tool:
|
129 |
tools.append(image_generation_tool)
|
130 |
|
131 |
+
# Create and return the agent
|
132 |
+
return CodeAgent(
|
133 |
model=model,
|
134 |
tools=tools,
|
135 |
+
max_steps=6,
|
136 |
+
verbosity_level=1,
|
137 |
grammar=None,
|
138 |
+
planning_interval=None,
|
139 |
+
name="Agent",
|
140 |
+
description="A CodeAgent with improved capabilities",
|
141 |
prompt_templates=prompt_templates,
|
142 |
)
|
143 |
+
|
144 |
+
|
145 |
+
def run_app():
|
146 |
+
"""
|
147 |
+
Run the application with custom Gradio interface to avoid schema validation issues.
|
148 |
+
This circumvents the error in json_schema_to_python_type.
|
149 |
+
"""
|
150 |
+
# Import gradio only when needed to customize the interface
|
151 |
+
try:
|
152 |
+
import gradio as gr
|
153 |
+
from Gradio_UI import GradioUI
|
154 |
+
except ImportError as e:
|
155 |
+
logger.error(f"Error importing Gradio: {e}")
|
156 |
+
raise
|
157 |
|
|
|
|
|
158 |
try:
|
159 |
+
# Create the agent
|
160 |
+
agent = create_agent()
|
161 |
+
|
162 |
+
# Basic interface without relying on complex schema validation
|
163 |
+
with gr.Blocks() as demo:
|
164 |
+
gr.Markdown("# Code Agent Interface")
|
165 |
+
|
166 |
+
with gr.Row():
|
167 |
+
with gr.Column(scale=4):
|
168 |
+
input_text = gr.Textbox(
|
169 |
+
label="Your task",
|
170 |
+
placeholder="Describe your task here...",
|
171 |
+
lines=5
|
172 |
+
)
|
173 |
+
|
174 |
+
submit_btn = gr.Button("Submit")
|
175 |
+
|
176 |
+
with gr.Column(scale=6):
|
177 |
+
output_text = gr.Markdown(label="Agent Response")
|
178 |
+
|
179 |
+
# Handle submissions manually to avoid schema issues
|
180 |
+
def process_request(task):
|
181 |
+
try:
|
182 |
+
result = agent(task)
|
183 |
+
return result
|
184 |
+
except Exception as e:
|
185 |
+
logger.error(f"Error in agent processing: {e}")
|
186 |
+
return f"Error processing your request: {str(e)}"
|
187 |
+
|
188 |
+
submit_btn.click(
|
189 |
+
fn=process_request,
|
190 |
+
inputs=input_text,
|
191 |
+
outputs=output_text
|
192 |
+
)
|
193 |
+
|
194 |
+
# Launch with minimal options
|
195 |
+
demo.launch(
|
196 |
+
server_name="0.0.0.0",
|
197 |
+
share=False,
|
198 |
+
debug=False
|
199 |
)
|
200 |
+
|
201 |
except Exception as e:
|
202 |
+
logger.error(f"Failed to start application: {e}")
|
203 |
+
print(f"Critical error: {e}")
|
204 |
|
205 |
|
206 |
if __name__ == "__main__":
|
207 |
+
run_app()
|