Scott Cogan commited on
Commit
dfde1fc
·
1 Parent(s): 4481e03

fix: simplify template handling by removing unnecessary processing

Browse files
Files changed (1) hide show
  1. app.py +32 -96
app.py CHANGED
@@ -74,6 +74,7 @@ model = OpenAIModel(
74
  # Import tool from Hub
75
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
76
 
 
77
  with open("prompts.yaml", 'r') as stream:
78
  yaml_content = yaml.safe_load(stream)
79
  if not isinstance(yaml_content, dict):
@@ -84,27 +85,10 @@ with open("prompts.yaml", 'r') as stream:
84
  if not isinstance(prompt_templates, dict):
85
  raise ValueError("prompt_templates must be a dictionary")
86
 
87
- # Process templates to ensure they are valid Jinja2 templates
88
- def process_template(template_content, is_system_prompt=False):
89
- """Process a template string to ensure it's properly formatted for Jinja2."""
90
- if not isinstance(template_content, str):
91
- return template_content
92
-
93
- # If it's already a template (contains {{ or {%), return as is
94
- if '{{' in template_content or '{%' in template_content:
95
- # Just ensure proper spacing in template expressions
96
- content = template_content
97
- content = re.sub(r'{{([^{}]+)}}', r'{{ \1 }}', content)
98
- content = re.sub(r'{%([^{}]+)%}', r'{% \1 %}', content)
99
- return content
100
-
101
- # For non-template strings, wrap in double curly braces
102
- return f"{{{{ {template_content} }}}}"
103
-
104
- logger.debug("Starting template processing...")
105
  try:
106
- # Log the original templates
107
- logger.debug("Original templates:")
108
  for key, value in prompt_templates.items():
109
  if isinstance(value, dict):
110
  logger.debug(f"{key}: {list(value.keys())}")
@@ -112,37 +96,25 @@ with open("prompts.yaml", 'r') as stream:
112
  logger.debug(f"{key}.{subkey}: {str(subvalue)[:200]}...")
113
  else:
114
  logger.debug(f"{key}: {str(value)[:200]}...")
115
-
116
- prompt_templates = process_template(prompt_templates)
117
- logger.debug("Template processing completed")
118
 
119
- # Log the final processed templates
120
- logger.debug("Final processed templates:")
121
- for key, value in prompt_templates.items():
122
- if isinstance(value, dict):
123
- logger.debug(f"{key}: {list(value.keys())}")
124
- for subkey, subvalue in value.items():
125
- logger.debug(f"{key}.{subkey}: {str(subvalue)[:200]}...")
126
- else:
127
- logger.debug(f"{key}: {str(value)[:200]}...")
128
- except Exception as e:
129
- logger.error(f"Error during template processing: {str(e)}")
130
- raise
131
-
132
- # Validate templates before creating agent
133
- logger.debug("Validating templates...")
134
- try:
135
  for key, value in prompt_templates.items():
136
  if isinstance(value, dict):
137
  for subkey, subvalue in value.items():
138
  if isinstance(subvalue, str):
139
  logger.debug(f"Validating template: {key}.{subkey}")
140
  logger.debug(f"Template content: {subvalue[:200]}...")
141
- # Test template compilation
142
- template = Template(subvalue, undefined=StrictUndefined)
143
- # Test template rendering with dummy data
144
  try:
145
- rendered = template.render(tools=[], task="test", name="test", final_answer="test", remaining_steps=1, answer_facts="test")
 
 
 
 
 
 
 
 
146
  logger.debug(f"Template render test successful for {key}.{subkey}")
147
  logger.debug(f"Rendered content: {rendered[:200]}...")
148
  except Exception as e:
@@ -151,75 +123,39 @@ with open("prompts.yaml", 'r') as stream:
151
  elif isinstance(value, str):
152
  logger.debug(f"Validating template: {key}")
153
  logger.debug(f"Template content: {value[:200]}...")
154
- template = Template(value, undefined=StrictUndefined)
155
  try:
156
- rendered = template.render(tools=[], task="test", name="test", final_answer="test", remaining_steps=1, answer_facts="test")
 
 
 
 
 
 
 
 
157
  logger.debug(f"Template render test successful for {key}")
158
  logger.debug(f"Rendered content: {rendered[:200]}...")
159
  except Exception as e:
160
  logger.error(f"Template render test failed for {key}: {str(e)}")
161
  raise
 
162
  logger.debug("Template validation completed successfully")
 
163
  except Exception as e:
164
- logger.error(f"Template validation failed: {str(e)}")
165
  raise
166
 
167
- # Pre-process the system prompt template
168
- if 'system_prompt' in prompt_templates and 'text' in prompt_templates['system_prompt']:
169
- system_prompt = prompt_templates['system_prompt']['text']
170
- logger.debug(f"Original system prompt: {system_prompt[:200]}...")
171
- # Only process template variables, leave other text unchanged
172
- system_prompt = re.sub(r'{{([^{}]+)}}', lambda m: '{{ ' + m.group(1).strip() + ' }}', system_prompt)
173
- system_prompt = re.sub(r'{%([^{}]+)%}', lambda m: '{% ' + m.group(1).strip() + ' %}', system_prompt)
174
- prompt_templates['system_prompt']['text'] = system_prompt
175
- logger.debug(f"Pre-processed system prompt: {system_prompt[:200]}...")
176
-
177
- # Log the final templates before creating the agent
178
- logger.debug("Final templates before creating agent:")
179
- for key, value in prompt_templates.items():
180
- if isinstance(value, dict):
181
- logger.debug(f"{key}:")
182
- for subkey, subvalue in value.items():
183
- logger.debug(f" {subkey}: {str(subvalue)[:200]}...")
184
- else:
185
- logger.debug(f"{key}: {str(value)[:200]}...")
186
-
187
- # Create a copy of the templates for the agent
188
- agent_templates = {}
189
- for key, value in prompt_templates.items():
190
- if isinstance(value, dict):
191
- agent_templates[key] = {}
192
- for subkey, subvalue in value.items():
193
- if isinstance(subvalue, str):
194
- # Process template with proper spacing
195
- content = process_template(subvalue, key == 'system_prompt')
196
- agent_templates[key][subkey] = content
197
- elif isinstance(value, str):
198
- # Process template with proper spacing
199
- content = process_template(value, key == 'system_prompt')
200
- agent_templates[key] = content
201
- else:
202
- agent_templates[key] = value
203
-
204
- logger.debug("Templates for agent:")
205
- for key, value in agent_templates.items():
206
- if isinstance(value, dict):
207
- logger.debug(f"{key}:")
208
- for subkey, subvalue in value.items():
209
- logger.debug(f" {subkey}: {str(subvalue)[:200]}...")
210
- else:
211
- logger.debug(f"{key}: {str(value)[:200]}...")
212
-
213
  agent = CodeAgent(
214
  model=model,
215
  tools=[final_answer, DuckDuckGoSearchTool(), calculate_min_price, extract_price_from_snippet, get_current_time_in_timezone],
216
- max_steps=15, # Increased max steps for more complex reasoning
217
- verbosity_level=2, # Increased verbosity for better debugging
218
  grammar=None,
219
- planning_interval=1, # Added planning interval to ensure proper planning
220
  name="question_answering_agent",
221
  description="An agent specialized in answering various types of questions using available tools. The agent must use the final_answer tool to submit its answer.",
222
- prompt_templates=agent_templates
223
  )
224
 
225
  # Configure Gradio UI with sharing enabled
 
74
  # Import tool from Hub
75
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
76
 
77
+ # Load and validate templates from prompts.yaml
78
  with open("prompts.yaml", 'r') as stream:
79
  yaml_content = yaml.safe_load(stream)
80
  if not isinstance(yaml_content, dict):
 
85
  if not isinstance(prompt_templates, dict):
86
  raise ValueError("prompt_templates must be a dictionary")
87
 
88
+ logger.debug("Starting template validation...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  try:
90
+ # Log the templates
91
+ logger.debug("Templates:")
92
  for key, value in prompt_templates.items():
93
  if isinstance(value, dict):
94
  logger.debug(f"{key}: {list(value.keys())}")
 
96
  logger.debug(f"{key}.{subkey}: {str(subvalue)[:200]}...")
97
  else:
98
  logger.debug(f"{key}: {str(value)[:200]}...")
 
 
 
99
 
100
+ # Validate templates
101
+ logger.debug("Validating templates...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  for key, value in prompt_templates.items():
103
  if isinstance(value, dict):
104
  for subkey, subvalue in value.items():
105
  if isinstance(subvalue, str):
106
  logger.debug(f"Validating template: {key}.{subkey}")
107
  logger.debug(f"Template content: {subvalue[:200]}...")
 
 
 
108
  try:
109
+ template = Template(subvalue, undefined=StrictUndefined)
110
+ rendered = template.render(
111
+ tools=[],
112
+ task="test",
113
+ name="test",
114
+ final_answer="test",
115
+ remaining_steps=1,
116
+ answer_facts="test"
117
+ )
118
  logger.debug(f"Template render test successful for {key}.{subkey}")
119
  logger.debug(f"Rendered content: {rendered[:200]}...")
120
  except Exception as e:
 
123
  elif isinstance(value, str):
124
  logger.debug(f"Validating template: {key}")
125
  logger.debug(f"Template content: {value[:200]}...")
 
126
  try:
127
+ template = Template(value, undefined=StrictUndefined)
128
+ rendered = template.render(
129
+ tools=[],
130
+ task="test",
131
+ name="test",
132
+ final_answer="test",
133
+ remaining_steps=1,
134
+ answer_facts="test"
135
+ )
136
  logger.debug(f"Template render test successful for {key}")
137
  logger.debug(f"Rendered content: {rendered[:200]}...")
138
  except Exception as e:
139
  logger.error(f"Template render test failed for {key}: {str(e)}")
140
  raise
141
+
142
  logger.debug("Template validation completed successfully")
143
+
144
  except Exception as e:
145
+ logger.error(f"Error during template validation: {str(e)}")
146
  raise
147
 
148
+ # Create the agent with the templates
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  agent = CodeAgent(
150
  model=model,
151
  tools=[final_answer, DuckDuckGoSearchTool(), calculate_min_price, extract_price_from_snippet, get_current_time_in_timezone],
152
+ max_steps=15,
153
+ verbosity_level=2,
154
  grammar=None,
155
+ planning_interval=1,
156
  name="question_answering_agent",
157
  description="An agent specialized in answering various types of questions using available tools. The agent must use the final_answer tool to submit its answer.",
158
+ prompt_templates=prompt_templates
159
  )
160
 
161
  # Configure Gradio UI with sharing enabled