Scott Cogan commited on
Commit
0d53251
·
1 Parent(s): 40dd326

Refactor: Move prompt templates to separate Python file and update app.py

Browse files
Files changed (2) hide show
  1. app.py +112 -123
  2. prompt_templates.py +127 -0
app.py CHANGED
@@ -7,6 +7,31 @@ import yaml
7
  from tools.final_answer import FinalAnswerTool
8
  import re
9
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  from Gradio_UI import GradioUI
12
 
@@ -68,129 +93,93 @@ model = OpenAIModel(
68
  # Import tool from Hub
69
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
70
 
71
- # Define prompt templates directly as a Python dictionary
72
- prompt_templates = {
73
- "system_prompt": """You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
74
- To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
75
- To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
76
- At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
77
- Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
78
- During each intermediate step, you can use 'print()' to save whatever important information you will then need.
79
- These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
80
-
81
- IMPORTANT RULES:
82
- 1. You MUST use the final_answer tool to submit your answer. Never return a default answer.
83
- 2. If you're unsure about an answer, use the search tool to find information.
84
- 3. Always try to find the answer rather than returning a default response.
85
- 4. If you can't find a definitive answer, provide your best reasoning based on available information.
86
- 5. Never return "This is a default answer" - always provide your best attempt at answering the question.
87
- 6. For each question, you must:
88
- a. Analyze what information is needed
89
- b. Use appropriate tools to gather that information
90
- c. Process the information to form an answer
91
- d. Use final_answer to submit your response""",
92
-
93
- "final_answer": """You have reached the final step of your task. Use the final_answer tool to submit your answer.
94
- The answer should be clear, concise, and directly address the original question.
95
- Format: final_answer(your_answer)""",
96
-
97
- "planning": {
98
- "initial_facts": """Below I will present you a task.
99
- You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
100
- To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
101
- Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
102
-
103
- ---
104
- ### 1. Facts given in the task
105
- List here the specific facts given in the task that could help you (there might be nothing here).
106
-
107
- ### 2. Facts to look up
108
- List here any facts that we may need to look up.
109
- Also list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.
110
-
111
- ### 3. Facts to derive
112
- List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.""",
113
-
114
- "initial_plan": """You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
115
- Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
116
- This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
117
- Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
118
- After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.""",
119
-
120
- "update_facts_pre_messages": """You are a world expert at gathering known and unknown facts based on a conversation.
121
- Below you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:
122
- ### 1. Facts given in the task
123
- ### 2. Facts that we have learned
124
- ### 3. Facts still to look up
125
- ### 4. Facts still to derive
126
- Find the task and history below:""",
127
-
128
- "update_facts_post_messages": """Earlier we've built a list of facts.
129
- But since in your previous steps you may have learned useful new facts or invalidated some false ones.
130
- Please update your list of facts based on the previous history, and provide these headings:
131
- ### 1. Facts given in the task
132
- ### 2. Facts that we have learned
133
- ### 3. Facts still to look up
134
- ### 4. Facts still to derive
135
-
136
- Now write your new list of facts below.""",
137
-
138
- "update_plan_pre_messages": """You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
139
- You have been given a task:
140
- ```
141
- {{task}}
142
- ```
143
-
144
- Find below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.
145
- If the previous tries so far have met some success, you can make an updated plan based on these actions.
146
- If you are stalled, you can make a completely new plan starting from scratch.""",
147
-
148
- "update_plan_post_messages": """You're still working towards solving this task:
149
- ```
150
- {{task}}
151
- ```
152
-
153
- Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
154
- This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
155
- Beware that you have {remaining_steps} steps remaining.
156
- Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
157
- After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
158
-
159
- Now write your new plan below."""
160
- },
161
-
162
- "managed_agent": {
163
- "task": """You're a helpful agent named '{{name}}'.
164
- You have been submitted this task by your manager.
165
- ---
166
- Task:
167
- {{task}}
168
- ---
169
- You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible to give them a clear understanding of the answer.
170
- Your final_answer WILL HAVE to contain these parts:
171
- ### 1. Task outcome (short version):
172
- ### 2. Task outcome (extremely detailed version):
173
- ### 3. Additional context (if relevant):
174
-
175
- Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
176
- And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.""",
177
-
178
- "report": """Here is the final answer from your managed agent '{{name}}':
179
- {{final_answer}}"""
180
- }
181
- }
182
 
183
- agent = CodeAgent(
184
- model=model,
185
- tools=[final_answer, DuckDuckGoSearchTool(), calculate_min_price, extract_price_from_snippet, get_current_time_in_timezone],
186
- max_steps=15, # Increased max steps for more complex reasoning
187
- verbosity_level=2, # Increased verbosity for better debugging
188
- grammar=None,
189
- planning_interval=1, # Added planning interval to ensure proper planning
190
- name="Question Answering Agent",
191
- 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.",
192
- prompt_templates=prompt_templates
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  )
194
 
195
- # Configure Gradio UI with sharing enabled
196
- GradioUI(agent).launch(share=True)
 
 
7
  from tools.final_answer import FinalAnswerTool
8
  import re
9
  import os
10
+ import gradio as gr
11
+ from smolagents import Agent, Tool
12
+ from smolagents.tools import (
13
+ SearchTool,
14
+ CalculatorTool,
15
+ WikipediaTool,
16
+ FileSystemTool,
17
+ CodeInterpreterTool,
18
+ WebScrapingTool,
19
+ WeatherTool,
20
+ NewsTool,
21
+ ImageGenerationTool,
22
+ TextToSpeechTool,
23
+ TranslationTool,
24
+ EmailTool,
25
+ CalendarTool,
26
+ MapTool,
27
+ MusicTool,
28
+ VideoTool,
29
+ DatabaseTool,
30
+ APITool,
31
+ BrowserTool,
32
+ TerminalTool
33
+ )
34
+ from prompt_templates import PROMPT_TEMPLATES
35
 
36
  from Gradio_UI import GradioUI
37
 
 
93
  # Import tool from Hub
94
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
95
 
96
+ # Initialize tools
97
+ tools = [
98
+ SearchTool(),
99
+ CalculatorTool(),
100
+ WikipediaTool(),
101
+ FileSystemTool(),
102
+ CodeInterpreterTool(),
103
+ WebScrapingTool(),
104
+ WeatherTool(),
105
+ NewsTool(),
106
+ ImageGenerationTool(),
107
+ TextToSpeechTool(),
108
+ TranslationTool(),
109
+ EmailTool(),
110
+ CalendarTool(),
111
+ MapTool(),
112
+ MusicTool(),
113
+ VideoTool(),
114
+ DatabaseTool(),
115
+ APITool(),
116
+ BrowserTool(),
117
+ TerminalTool()
118
+ ]
119
+
120
+ # Initialize agents
121
+ managed_agent = Agent(
122
+ tools=tools,
123
+ prompt_template=PROMPT_TEMPLATES["managed_agent"]
124
+ )
125
+
126
+ tool_agent = Agent(
127
+ tools=tools,
128
+ prompt_template=PROMPT_TEMPLATES["tool_agent"]
129
+ )
130
+
131
+ tool_agent_with_memory = Agent(
132
+ tools=tools,
133
+ prompt_template=PROMPT_TEMPLATES["tool_agent_with_memory"],
134
+ memory=True
135
+ )
136
+
137
+ tool_agent_with_memory_and_planning = Agent(
138
+ tools=tools,
139
+ prompt_template=PROMPT_TEMPLATES["tool_agent_with_memory_and_planning"],
140
+ memory=True,
141
+ planning=True
142
+ )
143
+
144
+ # Create Gradio interface
145
+ def chat(message, history, agent_type):
146
+ # Select agent based on type
147
+ if agent_type == "Managed Agent":
148
+ agent = managed_agent
149
+ elif agent_type == "Tool Agent":
150
+ agent = tool_agent
151
+ elif agent_type == "Tool Agent with Memory":
152
+ agent = tool_agent_with_memory
153
+ else: # Tool Agent with Memory and Planning
154
+ agent = tool_agent_with_memory_and_planning
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
 
156
+ # Get response from agent
157
+ response = agent.chat(message)
158
+ return response
159
+
160
+ # Create the interface
161
+ iface = gr.Interface(
162
+ fn=chat,
163
+ inputs=[
164
+ gr.Textbox(label="Message", placeholder="Type your message here..."),
165
+ gr.State([]), # For chat history
166
+ gr.Radio(
167
+ choices=[
168
+ "Managed Agent",
169
+ "Tool Agent",
170
+ "Tool Agent with Memory",
171
+ "Tool Agent with Memory and Planning"
172
+ ],
173
+ label="Agent Type",
174
+ value="Managed Agent"
175
+ )
176
+ ],
177
+ outputs=gr.Textbox(label="Response"),
178
+ title="AI Assistant",
179
+ description="Choose an agent type and start chatting!",
180
+ theme=gr.themes.Soft()
181
  )
182
 
183
+ # Launch the app
184
+ if __name__ == "__main__":
185
+ iface.launch()
prompt_templates.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PROMPT_TEMPLATES = {
2
+ "managed_agent": """You are a helpful AI assistant that helps users with their tasks. You have access to the following tools:
3
+
4
+ {tools}
5
+
6
+ To use a tool, please use the following format:
7
+
8
+ ```
9
+ Thought: I need to use a tool to help the user
10
+ Action: the_tool_name
11
+ Action Input: {{"input": "the input to the tool"}}
12
+ ```
13
+
14
+ The user will then respond with the output of the tool. After using a tool, you should analyze the output and either:
15
+ 1. Use another tool if needed
16
+ 2. Provide a final answer to the user
17
+
18
+ If you don't need to use any tools, you can respond directly to the user.
19
+
20
+ Remember to:
21
+ - Always think about what tool would be most helpful
22
+ - Format your responses clearly
23
+ - Be helpful and friendly
24
+ - If you're not sure what to do, ask the user for clarification
25
+
26
+ Human: {input}
27
+
28
+ Assistant: Let me help you with that. First, I'll analyze what tools might be useful for your request.
29
+
30
+ {agent_scratchpad}""",
31
+
32
+ "tool_agent": """You are a helpful AI assistant that helps users with their tasks. You have access to the following tools:
33
+
34
+ {tools}
35
+
36
+ To use a tool, please use the following format:
37
+
38
+ ```
39
+ Thought: I need to use a tool to help the user
40
+ Action: the_tool_name
41
+ Action Input: {{"input": "the input to the tool"}}
42
+ ```
43
+
44
+ The user will then respond with the output of the tool. After using a tool, you should analyze the output and either:
45
+ 1. Use another tool if needed
46
+ 2. Provide a final answer to the user
47
+
48
+ If you don't need to use any tools, you can respond directly to the user.
49
+
50
+ Remember to:
51
+ - Always think about what tool would be most helpful
52
+ - Format your responses clearly
53
+ - Be helpful and friendly
54
+ - If you're not sure what to do, ask the user for clarification
55
+
56
+ Human: {input}
57
+
58
+ Assistant: Let me help you with that. First, I'll analyze what tools might be useful for your request.
59
+
60
+ {agent_scratchpad}""",
61
+
62
+ "tool_agent_with_memory": """You are a helpful AI assistant that helps users with their tasks. You have access to the following tools:
63
+
64
+ {tools}
65
+
66
+ To use a tool, please use the following format:
67
+
68
+ ```
69
+ Thought: I need to use a tool to help the user
70
+ Action: the_tool_name
71
+ Action Input: {{"input": "the input to the tool"}}
72
+ ```
73
+
74
+ The user will then respond with the output of the tool. After using a tool, you should analyze the output and either:
75
+ 1. Use another tool if needed
76
+ 2. Provide a final answer to the user
77
+
78
+ If you don't need to use any tools, you can respond directly to the user.
79
+
80
+ Remember to:
81
+ - Always think about what tool would be most helpful
82
+ - Format your responses clearly
83
+ - Be helpful and friendly
84
+ - If you're not sure what to do, ask the user for clarification
85
+
86
+ Previous conversation:
87
+ {chat_history}
88
+
89
+ Human: {input}
90
+
91
+ Assistant: Let me help you with that. First, I'll analyze what tools might be useful for your request.
92
+
93
+ {agent_scratchpad}""",
94
+
95
+ "tool_agent_with_memory_and_planning": """You are a helpful AI assistant that helps users with their tasks. You have access to the following tools:
96
+
97
+ {tools}
98
+
99
+ To use a tool, please use the following format:
100
+
101
+ ```
102
+ Thought: I need to use a tool to help the user
103
+ Action: the_tool_name
104
+ Action Input: {{"input": "the input to the tool"}}
105
+ ```
106
+
107
+ The user will then respond with the output of the tool. After using a tool, you should analyze the output and either:
108
+ 1. Use another tool if needed
109
+ 2. Provide a final answer to the user
110
+
111
+ If you don't need to use any tools, you can respond directly to the user.
112
+
113
+ Remember to:
114
+ - Always think about what tool would be most helpful
115
+ - Format your responses clearly
116
+ - Be helpful and friendly
117
+ - If you're not sure what to do, ask the user for clarification
118
+
119
+ Previous conversation:
120
+ {chat_history}
121
+
122
+ Human: {input}
123
+
124
+ Assistant: Let me help you with that. First, I'll analyze what tools might be useful for your request.
125
+
126
+ {agent_scratchpad}"""
127
+ }