darsoarafa commited on
Commit
1d95290
·
verified ·
1 Parent(s): 29ae008

Upload 5 files

Browse files
Files changed (5) hide show
  1. Gradio_UI.py +296 -0
  2. agent.json +55 -0
  3. app.py +271 -0
  4. prompts.yaml +488 -0
  5. requirements.txt +6 -0
Gradio_UI.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import mimetypes
17
+ import os
18
+ import re
19
+ import shutil
20
+ from typing import Optional
21
+
22
+ from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types
23
+ from smolagents.agents import ActionStep, MultiStepAgent
24
+ from smolagents.memory import MemoryStep
25
+ from smolagents.utils import _is_package_available
26
+
27
+
28
+ def pull_messages_from_step(
29
+ step_log: MemoryStep,
30
+ ):
31
+ """Extract ChatMessage objects from agent steps with proper nesting"""
32
+ import gradio as gr
33
+
34
+ if isinstance(step_log, ActionStep):
35
+ # Output the step number
36
+ step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
37
+ yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
38
+
39
+ # First yield the thought/reasoning from the LLM
40
+ if hasattr(step_log, "model_output") and step_log.model_output is not None:
41
+ # Clean up the LLM output
42
+ model_output = step_log.model_output.strip()
43
+ # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
44
+ model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>
45
+ model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```
46
+ model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>
47
+ model_output = model_output.strip()
48
+ yield gr.ChatMessage(role="assistant", content=model_output)
49
+
50
+ # For tool calls, create a parent message
51
+ if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
52
+ first_tool_call = step_log.tool_calls[0]
53
+ used_code = first_tool_call.name == "python_interpreter"
54
+ parent_id = f"call_{len(step_log.tool_calls)}"
55
+
56
+ # Tool call becomes the parent message with timing info
57
+ # First we will handle arguments based on type
58
+ args = first_tool_call.arguments
59
+ if isinstance(args, dict):
60
+ content = str(args.get("answer", str(args)))
61
+ else:
62
+ content = str(args).strip()
63
+
64
+ if used_code:
65
+ # Clean up the content by removing any end code tags
66
+ content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks
67
+ content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags
68
+ content = content.strip()
69
+ if not content.startswith("```python"):
70
+ content = f"```python\n{content}\n```"
71
+
72
+ parent_message_tool = gr.ChatMessage(
73
+ role="assistant",
74
+ content=content,
75
+ metadata={
76
+ "title": f"🛠️ Used tool {first_tool_call.name}",
77
+ "id": parent_id,
78
+ "status": "pending",
79
+ },
80
+ )
81
+ yield parent_message_tool
82
+
83
+ # Nesting execution logs under the tool call if they exist
84
+ if hasattr(step_log, "observations") and (
85
+ step_log.observations is not None and step_log.observations.strip()
86
+ ): # Only yield execution logs if there's actual content
87
+ log_content = step_log.observations.strip()
88
+ if log_content:
89
+ log_content = re.sub(r"^Execution logs:\s*", "", log_content)
90
+ yield gr.ChatMessage(
91
+ role="assistant",
92
+ content=f"{log_content}",
93
+ metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
94
+ )
95
+
96
+ # Nesting any errors under the tool call
97
+ if hasattr(step_log, "error") and step_log.error is not None:
98
+ yield gr.ChatMessage(
99
+ role="assistant",
100
+ content=str(step_log.error),
101
+ metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
102
+ )
103
+
104
+ # Update parent message metadata to done status without yielding a new message
105
+ parent_message_tool.metadata["status"] = "done"
106
+
107
+ # Handle standalone errors but not from tool calls
108
+ elif hasattr(step_log, "error") and step_log.error is not None:
109
+ yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
110
+
111
+ # Calculate duration and token information
112
+ step_footnote = f"{step_number}"
113
+ if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
114
+ token_str = (
115
+ f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
116
+ )
117
+ step_footnote += token_str
118
+ if hasattr(step_log, "duration"):
119
+ step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
120
+ step_footnote += step_duration
121
+ step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
122
+ yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
123
+ yield gr.ChatMessage(role="assistant", content="-----")
124
+
125
+
126
+ def stream_to_gradio(
127
+ agent,
128
+ task: str,
129
+ reset_agent_memory: bool = False,
130
+ additional_args: Optional[dict] = None,
131
+ ):
132
+ """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
133
+ if not _is_package_available("gradio"):
134
+ raise ModuleNotFoundError(
135
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
136
+ )
137
+ import gradio as gr
138
+
139
+ total_input_tokens = 0
140
+ total_output_tokens = 0
141
+
142
+ for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
143
+ # Track tokens if model provides them
144
+ if hasattr(agent.model, "last_input_token_count"):
145
+ total_input_tokens += agent.model.last_input_token_count or 0
146
+ total_output_tokens += agent.model.last_output_token_count or 0
147
+ if isinstance(step_log, ActionStep):
148
+ step_log.input_token_count = agent.model.last_input_token_count
149
+ step_log.output_token_count = agent.model.last_output_token_count
150
+
151
+ for message in pull_messages_from_step(
152
+ step_log,
153
+ ):
154
+ yield message
155
+
156
+ final_answer = step_log # Last log is the run's final_answer
157
+ final_answer = handle_agent_output_types(final_answer)
158
+
159
+ if isinstance(final_answer, AgentText):
160
+ yield gr.ChatMessage(
161
+ role="assistant",
162
+ content=f"**Final answer:**\n{final_answer.to_string()}\n",
163
+ )
164
+ elif isinstance(final_answer, AgentImage):
165
+ yield gr.ChatMessage(
166
+ role="assistant",
167
+ content={"path": final_answer.to_string(), "mime_type": "image/png"},
168
+ )
169
+ elif isinstance(final_answer, AgentAudio):
170
+ yield gr.ChatMessage(
171
+ role="assistant",
172
+ content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
173
+ )
174
+ else:
175
+ yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
176
+
177
+
178
+ class GradioUI:
179
+ """A one-line interface to launch your agent in Gradio"""
180
+
181
+ def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
182
+ if not _is_package_available("gradio"):
183
+ raise ModuleNotFoundError(
184
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
185
+ )
186
+ self.agent = agent
187
+ self.file_upload_folder = file_upload_folder
188
+ if self.file_upload_folder is not None:
189
+ if not os.path.exists(file_upload_folder):
190
+ os.mkdir(file_upload_folder)
191
+
192
+ def interact_with_agent(self, prompt, messages):
193
+ import gradio as gr
194
+
195
+ messages.append(gr.ChatMessage(role="user", content=prompt))
196
+ yield messages
197
+ for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
198
+ messages.append(msg)
199
+ yield messages
200
+ yield messages
201
+
202
+ def upload_file(
203
+ self,
204
+ file,
205
+ file_uploads_log,
206
+ allowed_file_types=[
207
+ "application/pdf",
208
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
209
+ "text/plain",
210
+ ],
211
+ ):
212
+ """
213
+ Handle file uploads, default allowed types are .pdf, .docx, and .txt
214
+ """
215
+ import gradio as gr
216
+
217
+ if file is None:
218
+ return gr.Textbox("No file uploaded", visible=True), file_uploads_log
219
+
220
+ try:
221
+ mime_type, _ = mimetypes.guess_type(file.name)
222
+ except Exception as e:
223
+ return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log
224
+
225
+ if mime_type not in allowed_file_types:
226
+ return gr.Textbox("File type disallowed", visible=True), file_uploads_log
227
+
228
+ # Sanitize file name
229
+ original_name = os.path.basename(file.name)
230
+ sanitized_name = re.sub(
231
+ r"[^\w\-.]", "_", original_name
232
+ ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
233
+
234
+ type_to_ext = {}
235
+ for ext, t in mimetypes.types_map.items():
236
+ if t not in type_to_ext:
237
+ type_to_ext[t] = ext
238
+
239
+ # Ensure the extension correlates to the mime type
240
+ sanitized_name = sanitized_name.split(".")[:-1]
241
+ sanitized_name.append("" + type_to_ext[mime_type])
242
+ sanitized_name = "".join(sanitized_name)
243
+
244
+ # Save the uploaded file to the specified folder
245
+ file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
246
+ shutil.copy(file.name, file_path)
247
+
248
+ return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]
249
+
250
+ def log_user_message(self, text_input, file_uploads_log):
251
+ return (
252
+ text_input
253
+ + (
254
+ f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
255
+ if len(file_uploads_log) > 0
256
+ else ""
257
+ ),
258
+ "",
259
+ )
260
+
261
+ def launch(self, **kwargs):
262
+ import gradio as gr
263
+
264
+ with gr.Blocks(fill_height=True) as demo:
265
+ stored_messages = gr.State([])
266
+ file_uploads_log = gr.State([])
267
+ chatbot = gr.Chatbot(
268
+ label="Agent",
269
+ type="messages",
270
+ avatar_images=(
271
+ None,
272
+ "https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",
273
+ ),
274
+ resizeable=True,
275
+ scale=1,
276
+ )
277
+ # If an upload folder is provided, enable the upload feature
278
+ if self.file_upload_folder is not None:
279
+ upload_file = gr.File(label="Upload a file")
280
+ upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
281
+ upload_file.change(
282
+ self.upload_file,
283
+ [upload_file, file_uploads_log],
284
+ [upload_status, file_uploads_log],
285
+ )
286
+ text_input = gr.Textbox(lines=1, label="Chat Message")
287
+ text_input.submit(
288
+ self.log_user_message,
289
+ [text_input, file_uploads_log],
290
+ [stored_messages, text_input],
291
+ ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
292
+
293
+ demo.launch(debug=True, share=True, **kwargs)
294
+
295
+
296
+ __all__ = ["stream_to_gradio", "GradioUI"]
agent.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "tools": [
3
+ "web_search",
4
+ "visit_webpage",
5
+ "final_answer"
6
+ ],
7
+ "model": {
8
+ "class": "HfApiModel",
9
+ "data": {
10
+ "max_tokens": 2096,
11
+ "temperature": 0.5,
12
+ "last_input_token_count": null,
13
+ "last_output_token_count": null,
14
+ "model_id": "Qwen/Qwen2.5-Coder-32B-Instruct",
15
+ "custom_role_conversions": null
16
+ }
17
+ },
18
+ "prompt_templates": {
19
+ "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.\nTo do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.\nTo solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.\n\nAt each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.\nThen in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.\nDuring each intermediate step, you can use 'print()' to save whatever important information you will then need.\nThese print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.\nIn the end you have to return a final answer using the `final_answer` tool.\n\nHere are a few examples using notional tools:\n---\nTask: \"Generate an image of the oldest person in this document.\"\n\nThought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.\nCode:\n```py\nanswer = document_qa(document=document, question=\"Who is the oldest person mentioned?\")\nprint(answer)\n```<end_code>\nObservation: \"The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland.\"\n\nThought: I will now generate an image showcasing the oldest person.\nCode:\n```py\nimage = image_generator(\"A portrait of John Doe, a 55-year-old man living in Canada.\")\nfinal_answer(image)\n```<end_code>\n\n---\nTask: \"What is the result of the following operation: 5 + 3 + 1294.678?\"\n\nThought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool\nCode:\n```py\nresult = 5 + 3 + 1294.678\nfinal_answer(result)\n```<end_code>\n\n---\nTask:\n\"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.\nYou have been provided with these additional arguments, that you can access using the keys as variables in your python code:\n{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}\"\n\nThought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.\nCode:\n```py\ntranslated_question = translator(question=question, src_lang=\"French\", tgt_lang=\"English\")\nprint(f\"The translated question is {translated_question}.\")\nanswer = image_qa(image=image, question=translated_question)\nfinal_answer(f\"The answer is {answer}\")\n```<end_code>\n\n---\nTask:\nIn a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.\nWhat does he say was the consequence of Einstein learning too much math on his creativity, in one word?\n\nThought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.\nCode:\n```py\npages = search(query=\"1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein\")\nprint(pages)\n```<end_code>\nObservation:\nNo result found for query \"1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein\".\n\nThought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.\nCode:\n```py\npages = search(query=\"1979 interview Stanislaus Ulam\")\nprint(pages)\n```<end_code>\nObservation:\nFound 6 pages:\n[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)\n\n[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)\n\n(truncated)\n\nThought: I will read the first 2 pages to know more.\nCode:\n```py\nfor url in [\"https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/\", \"https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/\"]:\n whole_page = visit_webpage(url)\n print(whole_page)\n print(\"\\n\" + \"=\"*80 + \"\\n\") # Print separator between pages\n```<end_code>\nObservation:\nManhattan Project Locations:\nLos Alamos, NM\nStanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at\n(truncated)\n\nThought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: \"He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity.\" Let's answer in one word.\nCode:\n```py\nfinal_answer(\"diminished\")\n```<end_code>\n\n---\nTask: \"Which city has the highest population: Guangzhou or Shanghai?\"\n\nThought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.\nCode:\n```py\nfor city in [\"Guangzhou\", \"Shanghai\"]:\n print(f\"Population {city}:\", search(f\"{city} population\")\n```<end_code>\nObservation:\nPopulation Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']\nPopulation Shanghai: '26 million (2019)'\n\nThought: Now I know that Shanghai has the highest population.\nCode:\n```py\nfinal_answer(\"Shanghai\")\n```<end_code>\n\n---\nTask: \"What is the current age of the pope, raised to the power 0.36?\"\n\nThought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.\nCode:\n```py\npope_age_wiki = wiki(query=\"current pope age\")\nprint(\"Pope age as per wikipedia:\", pope_age_wiki)\npope_age_search = web_search(query=\"current pope age\")\nprint(\"Pope age as per google search:\", pope_age_search)\n```<end_code>\nObservation:\nPope age: \"The pope Francis is currently 88 years old.\"\n\nThought: I know that the pope is 88 years old. Let's compute the result using python code.\nCode:\n```py\npope_current_age = 88 ** 0.36\nfinal_answer(pope_current_age)\n```<end_code>\n\nAbove example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools:\n{%- for tool in tools.values() %}\n- {{ tool.name }}: {{ tool.description }}\n Takes inputs: {{tool.inputs}}\n Returns an output of type: {{tool.output_type}}\n{%- endfor %}\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task', a long string explaining your task.\nGiven that this team member is a real human, you should be very verbose in your task.\nHere is a list of the team members that you can call:\n{%- for agent in managed_agents.values() %}\n- {{ agent.name }}: {{ agent.description }}\n{%- endfor %}\n{%- else %}\n{%- endif %}\n\nHere are the rules you should always follow to solve your task:\n1. Always provide a 'Thought:' sequence, and a 'Code:\\n```py' sequence ending with '```<end_code>' sequence, else you will fail.\n2. Use only variables that you have defined!\n3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': \"What is the place where James Bond lives?\"})', but use the arguments directly as in 'answer = wiki(query=\"What is the place where James Bond lives?\")'.\n4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.\n5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.\n6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.\n7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.\n8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}\n9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.\n10. Don't give up! You're in charge of solving the task, not providing directions to solve it.\n\nNow Begin! If you solve the task correctly, you will receive a reward of $1,000,000.",
20
+ "planning": {
21
+ "initial_facts": "Below I will present you a task.\n\nYou will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.\nTo do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.\nDon't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:\n\n---\n### 1. Facts given in the task\nList here the specific facts given in the task that could help you (there might be nothing here).\n\n### 2. Facts to look up\nList here any facts that we may need to look up.\nAlso 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.\n\n### 3. Facts to derive\nList here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.\n\nKeep in mind that \"facts\" will typically be specific names, dates, values, etc. Your answer should use the below headings:\n### 1. Facts given in the task\n### 2. Facts to look up\n### 3. Facts to derive\nDo not add anything else.",
22
+ "initial_plan": "You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.\n\nNow for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.\nThis plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.\nDo not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.\nAfter writing the final step of the plan, write the '\\n<end_plan>' tag and stop there.\n\nHere is your task:\n\nTask:\n```\n{{task}}\n```\nYou can leverage these tools:\n{%- for tool in tools.values() %}\n- {{ tool.name }}: {{ tool.description }}\n Takes inputs: {{tool.inputs}}\n Returns an output of type: {{tool.output_type}}\n{%- endfor %}\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.\nGiven that this team member is a real human, you should be very verbose in your request.\nHere is a list of the team members that you can call:\n{%- for agent in managed_agents.values() %}\n- {{ agent.name }}: {{ agent.description }}\n{%- endfor %}\n{%- else %}\n{%- endif %}\n\nList of facts that you know:\n```\n{{answer_facts}}\n```\n\nNow begin! Write your plan below.",
23
+ "update_facts_pre_messages": "You are a world expert at gathering known and unknown facts based on a conversation.\nBelow you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:\n### 1. Facts given in the task\n### 2. Facts that we have learned\n### 3. Facts still to look up\n### 4. Facts still to derive\nFind the task and history below:",
24
+ "update_facts_post_messages": "Earlier we've built a list of facts.\nBut since in your previous steps you may have learned useful new facts or invalidated some false ones.\nPlease update your list of facts based on the previous history, and provide these headings:\n### 1. Facts given in the task\n### 2. Facts that we have learned\n### 3. Facts still to look up\n### 4. Facts still to derive\n\nNow write your new list of facts below.",
25
+ "update_plan_pre_messages": "You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.\n\nYou have been given a task:\n```\n{{task}}\n```\n\nFind 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.\nIf the previous tries so far have met some success, you can make an updated plan based on these actions.\nIf you are stalled, you can make a completely new plan starting from scratch.",
26
+ "update_plan_post_messages": "You're still working towards solving this task:\n```\n{{task}}\n```\n\nYou can leverage these tools:\n{%- for tool in tools.values() %}\n- {{ tool.name }}: {{ tool.description }}\n Takes inputs: {{tool.inputs}}\n Returns an output of type: {{tool.output_type}}\n{%- endfor %}\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.\nGiven that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.\nHere is a list of the team members that you can call:\n{%- for agent in managed_agents.values() %}\n- {{ agent.name }}: {{ agent.description }}\n{%- endfor %}\n{%- else %}\n{%- endif %}\n\nHere is the up to date list of facts that you know:\n```\n{{facts_update}}\n```\n\nNow for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.\nThis plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.\nBeware that you have {remaining_steps} steps remaining.\nDo not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.\nAfter writing the final step of the plan, write the '\\n<end_plan>' tag and stop there.\n\nNow write your new plan below."
27
+ },
28
+ "managed_agent": {
29
+ "task": "You're a helpful agent named '{{name}}'.\nYou have been submitted this task by your manager.\n---\nTask:\n{{task}}\n---\nYou'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.\n\nYour final_answer WILL HAVE to contain these parts:\n### 1. Task outcome (short version):\n### 2. Task outcome (extremely detailed version):\n### 3. Additional context (if relevant):\n\nPut all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.\nAnd even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.",
30
+ "report": "Here is the final answer from your managed agent '{{name}}':\n{{final_answer}}"
31
+ }
32
+ },
33
+ "max_steps": 6,
34
+ "verbosity_level": 1,
35
+ "grammar": null,
36
+ "planning_interval": null,
37
+ "name": null,
38
+ "description": null,
39
+ "authorized_imports": [
40
+ "unicodedata",
41
+ "stat",
42
+ "datetime",
43
+ "random",
44
+ "pandas",
45
+ "itertools",
46
+ "math",
47
+ "statistics",
48
+ "queue",
49
+ "time",
50
+ "collections",
51
+ "re",
52
+ "base64",
53
+ "typing"
54
+ ]
55
+ }
app.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool, OpenAIServerModel
2
+ import datetime
3
+ import requests
4
+ import pytz
5
+ import base64
6
+ import yaml
7
+ from tools.final_answer import FinalAnswerTool
8
+ from Gradio_UI import GradioUI
9
+ from typing import List, Tuple
10
+ import os
11
+
12
+ momo_key = os.getenv("MomoKey")
13
+ # Below is an example of a tool that does nothing. Amaze us with your creativity !
14
+ @tool
15
+ def my_custom_tool(arg1:str, arg2:int)-> str:
16
+ """A tool that does nothing yet.
17
+ Args:
18
+ arg1: the first argument
19
+ arg2: the second argument
20
+ """
21
+ return "What magic will you build ?"
22
+
23
+ @tool
24
+ def get_sura(sura_number: int) -> str:
25
+ """A tool that gets the text of a sura based on its sura number
26
+ Args:
27
+ sura_number: The sura number of the sura.
28
+ """
29
+ url = f"https://quran-challenge.com/app/php/getverses.php?sura_number={sura_number}"
30
+ response = requests.get(url)
31
+
32
+ if response.status_code == 200:
33
+ data = response.json()
34
+ result = ""
35
+
36
+ for verse in data:
37
+ nr = verse['nr']
38
+ text = verse['tanzil_text']
39
+ result += f"{nr}: {text}\n"
40
+ return f"The text of the sura {sura_number} is:\n {result}"
41
+ else:
42
+ return "Error: Could not fetch the sura data."
43
+ @tool
44
+ def search_quran(search_type: str, search_value: str) -> str:
45
+ """A tool that searches for a given term in the Quran based on the specified search type. The spellingspecial search type indicates the othmani original spelling of the text.
46
+
47
+ Args:
48
+ search_type: The type of search (e.g., 'word', 'root', 'spellingspecial', 'verbvorm').
49
+ search_value: The term to be searched for in the Quran.
50
+
51
+ Returns:
52
+ a complete list of the verses found. Each line starts with sura number followed by : followed by verse number followed by a space and then finally the verse text.
53
+ """
54
+ valid_search_types = {"word", "root", "spellingspecial", "verb_form"}
55
+
56
+ if search_type not in valid_search_types:
57
+ return f"Error: Invalid search type '{search_type}'. Valid options are: {', '.join(valid_search_types)}."
58
+
59
+ url = f"https://quran-challenge.com/app/php/search.php?query={search_type}:{search_value}"
60
+ response = requests.get(url)
61
+
62
+ if response.status_code == 200:
63
+ data = response.json()
64
+ result = ""
65
+
66
+ if "result" in data:
67
+ for verse in data["result"]:
68
+ sura = verse['sura']
69
+ nr = verse["nr"]
70
+ text = verse["tanzil_text"]
71
+ result += f"{sura}:{nr} {text}\n"
72
+
73
+ return f"The term '{search_value}' under search type '{search_type}' is found in the following verses:\n{result}"
74
+ else:
75
+ return f"No results found for '{search_value}' under search type '{search_type}'."
76
+ else:
77
+ return "Error: Could not fetch data from the Quran API."
78
+
79
+ @tool
80
+ def search_quran_advanced(search_terms: list, operator: str = "VAND") -> str:
81
+ """A tool that searches for multiple terms in the same verse in the Quran using AND/OR conditions.
82
+ The AND condition is named: VAND and the OR condition is named VOR. The prefix V stands for "Verse", where the search happens on verse level.
83
+
84
+ Args:
85
+ search_terms: A list of tuples where each tuple contains a search type (e.g., 'word', 'root') and the corresponding term to search.
86
+ operator: The logical operator to combine conditions ('VAND' or 'VOR').
87
+ Returns:
88
+ A complete list of the verses found. Each line starts with sura number followed by : followed by verse number followed by a space and then finally the verse text.
89
+
90
+ Example:
91
+ search_quran_advanced([('word', 'مجمع'), ('word', 'البحرين')], 'VAND')
92
+ """
93
+ valid_search_types = {"word", "root", "spellingspecial", "verb_form"}
94
+ valid_operators = {"VAND", "VOR"}
95
+
96
+ if operator not in valid_operators:
97
+ return f"Error: Invalid operator '{operator}'. Valid options are: {', '.join(valid_operators)}."
98
+
99
+ # Validate search terms
100
+ filters = []
101
+ for search_type, search_value in search_terms:
102
+ if search_type not in valid_search_types:
103
+ return f"Error: Invalid search type '{search_type}'. Valid options are: {', '.join(valid_search_types)}."
104
+ filters.append(f"{search_type}:{search_value}")
105
+
106
+ query_string = f"{operator}".join(filters)
107
+ url = f"https://quran-challenge.com/app/php/search.php?query={query_string}"
108
+ response = requests.get(url)
109
+
110
+ if response.status_code == 200:
111
+ data = response.json()
112
+ result = ""
113
+
114
+ if "result" in data:
115
+ for verse in data["result"]:
116
+ sura = verse['sura']
117
+ nr = verse["nr"]
118
+ text = verse["tanzil_text"]
119
+ result += f"{sura}:{nr} {text}\n"
120
+
121
+ return f"Search results for {query_string}:\n{result}"
122
+ else:
123
+ return f"No results found for '{query_string}'."
124
+ else:
125
+ return "Error: Could not fetch data from the Quran API."
126
+ from typing import List, Tuple
127
+
128
+ @tool
129
+ def abjad_value(sura: int, verse: int) -> Tuple[List[int], int]:
130
+ """A tool that calculates the Abjad values (Gematrical values) of Arabic letters in a given text and returns a tuple containing:
131
+ - A list of individual Abjad values for each letter in the text.
132
+ - The total Abjad value for the entire text.
133
+
134
+ Args:
135
+ sura: The number of the Sura in the Quran.
136
+ verse: The number of the verse in the given Sura.
137
+
138
+ Returns:
139
+ tuple: A tuple containing two elements:
140
+ 1. A list of integers representing the Abjad value for each letter in the text.
141
+ 2. An integer representing the total Abjad value of the entire text.
142
+
143
+ Example:
144
+ abjad_value(1, 1)
145
+ Returns:
146
+ ([2, 60, 40, 1, 30, 30, 5, 1, 30, 200, 8, 40, 50, 1, 30, 200, 8, 10, 40], 786)
147
+ """
148
+ abjad_dict = {
149
+ 'ا': 1, 'أ': 1, 'إ': 1, 'آ': 1, 'ء': 1,
150
+ 'ب': 2, 'ت': 400, 'ث': 500, 'ج': 3, 'ح': 8, 'خ': 600,
151
+ 'د': 4, 'ذ': 700, 'ر': 200, 'ز': 7, 'س': 60, 'ش': 300,
152
+ 'ص': 90, 'ض': 800, 'ط': 9, 'ظ': 900, 'ع': 70, 'غ': 1000,
153
+ 'ف': 80, 'ق': 100, 'ك': 20, 'ل': 30, 'م': 40, 'ن': 50,
154
+ 'ه': 5, 'و': 6, 'ى': 10, 'ي': 10, 'ئ': 10, 'ؤ': 6, 'ة': 5
155
+ }
156
+
157
+ expression = ''
158
+ url = f"https://quran-challenge.com/app/php/getverse.php?sura_number={sura}&verse_number={verse}"
159
+ response = requests.get(url)
160
+
161
+ if response.status_code == 200:
162
+ data = response.json()
163
+ result = ""
164
+
165
+ for verse in data:
166
+ nr = verse['nr']
167
+ text = verse['text']
168
+ expression = f"{text}"
169
+
170
+ expression = expression.replace(" ", "") # Remove spaces from the expression
171
+ individual_values = []
172
+ total_value = 0
173
+
174
+ for letter in expression:
175
+ if letter in abjad_dict:
176
+ value = abjad_dict[letter]
177
+ individual_values.append(value)
178
+ total_value += value
179
+
180
+ return individual_values, total_value
181
+
182
+ @tool
183
+ def calculate_expenses(sallery: int) -> str:
184
+ """A tool that calculate the expenses of a given sallery.
185
+ Args:
186
+ sallery: The given sallery.
187
+ """
188
+ return f"the expenses of the sallery {sallery} are: {sallery * 0.82 + (sallery * (0.03))} CHF."
189
+
190
+ @tool
191
+ def encode_text(text: str) -> str:
192
+ """Encodes text using XOR with a key and Base64 encoding.
193
+
194
+ Args:
195
+ text: The text to encode.
196
+
197
+ Returns:
198
+ Encoded Base64 string.
199
+ """
200
+ key_cycle = (ord(k) for k in momo_key) # Cycle through key chars
201
+ encoded_bytes = bytes([ord(c) ^ next(key_cycle) for c in text]) # XOR each char
202
+ return base64.b64encode(encoded_bytes).decode()
203
+
204
+ @tool
205
+ def decode_text(encoded_text: str) -> str:
206
+ """Decodes a Base64-encoded XOR encrypted text using the given key.
207
+
208
+ Args:
209
+ encoded_text: The encoded Base64 string.
210
+
211
+ Returns:
212
+ Decoded plain text.
213
+ """
214
+ key_cycle = (ord(k) for k in momo_key)
215
+ decoded_bytes = base64.b64decode(encoded_text) # Decode Base64
216
+ return ''.join(chr(b ^ next(key_cycle)) for b in decoded_bytes)
217
+
218
+ @tool
219
+ def get_current_time_in_timezone(timezone: str) -> str:
220
+ """A tool that fetches the current local time in a specified timezone.
221
+ Args:
222
+ timezone: A string representing a valid timezone (e.g., 'America/New_York').
223
+ """
224
+ try:
225
+ # Create timezone object
226
+ tz = pytz.timezone(timezone)
227
+ # Get current time in that timezone
228
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
229
+ return f"The current local time in {timezone} is: {local_time}"
230
+ except Exception as e:
231
+ return f"Error fetching time for timezone '{timezone}': {str(e)}"
232
+
233
+
234
+ final_answer = FinalAnswerTool()
235
+
236
+ model = HfApiModel(
237
+ max_tokens=2096,
238
+ temperature=0.5,
239
+ model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud', #meta-llama/Meta-Llama-3-8B-Instruct
240
+ custom_role_conversions=None,
241
+ )
242
+ """
243
+ model = OpenAIServerModel(
244
+ max_tokens=2096,
245
+ temperature=0.5,
246
+ model_id="gpt-4o-mini",
247
+ api_key= api_key,
248
+ custom_role_conversions=None,
249
+ )
250
+ """
251
+
252
+ # Import tool from Hub
253
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
254
+
255
+ with open("prompts.yaml", 'r') as stream:
256
+ prompt_templates = yaml.safe_load(stream)
257
+
258
+ agent = CodeAgent(
259
+ model=model,
260
+ tools=[final_answer, calculate_expenses, image_generation_tool, encode_text, decode_text, get_sura, search_quran, search_quran_advanced, abjad_value],
261
+ max_steps=6,
262
+ verbosity_level=1,
263
+ grammar=None,
264
+ planning_interval=None,
265
+ name=None,
266
+ description=None,
267
+ prompt_templates=prompt_templates
268
+ )
269
+
270
+
271
+ GradioUI(agent).launch()
prompts.yaml ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "system_prompt": |-
2
+ You are an expert assistant who can solve any task related to the Noble Quran and encoding/decoding text using code blobs. You will be given a task to solve as best you can.
3
+ 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.
4
+ To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
5
+
6
+ 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.
7
+ Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
8
+ During each intermediate step, you can use 'print()' to save whatever important information you will then need.
9
+ These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
10
+ In the end you have to return a final answer using the `final_answer` tool.
11
+ Whenever you get a seach query about the Quran, stick with the examples provided and use the templates given there for thought and Observation.
12
+ You have always to be respectful and call it "the Noble Quran" please.
13
+ If you get any other query that is not related to the Quran or to encoding/decoding text, then please apologize politely in the language of the query and say that you can only provide assistance for searching the Noble Quran using tools provided by quran-challenge.com.
14
+ If asked about the abjad value or gematrical value of a verse, the you have to use the abjad_value tool provided to you. Never calculate it on your own.
15
+
16
+ If asked about your name, say that your name is Quranium AI or in Arabic قرآنيوم إيه آي.
17
+ If asked who programmed you or who made you or who created you then your answer will be Mohammad Almalt. In arabic it would be "محمد الملط".
18
+ When asked about your name or who created you, then ignore the thought, code and observation sequences and go to final answer directly.
19
+ Always try to phrase the final answer in the language of the query that you receive.
20
+
21
+ Here are a few examples using notional tools:
22
+ ---
23
+ Task: What is your name?
24
+ final_answer("Quranium AI")
25
+ ---
26
+ Task: who created you?
27
+ final_answer("Mohammad Almalt")
28
+ ---
29
+ Task: "calculate the gematrical value of the verse 1:1"
30
+
31
+ Thought: I can get the abjad value of this verse using the abjad_value tool.
32
+ Code:
33
+ ```py
34
+ result = abjad_value(1, 1)
35
+ individual_values, total_value = result
36
+ print("Individual letter values:", individual_values)
37
+ ```<end_code
38
+ Observation:
39
+ Individual letter values: 2, 60, 40, 1, 30, 30, 5, 1, 30, 200, 8, 40, 50, 1, 30, 200, 8, 10, 40
40
+
41
+ Thought: I have now the individual Abjad values for each letter in the text.
42
+ Code:
43
+ ```py
44
+ print("Total value:", total_value)
45
+ ```<end_code>
46
+ Observation: Total value: 786
47
+
48
+ Thought: I will inform the user about the results, which consists of the individual Abjad values for each letter in the text and the total Abjad value for the entire text.
49
+ Code:
50
+ ```py
51
+ final_answer(result)
52
+ ```<end_code>
53
+ ---
54
+ Task: "get the abjad value of verse 1:1"
55
+
56
+ Thought: I can get the abjad value of this verse using the abjad_value tool.
57
+ Code:
58
+ ```py
59
+ result = abjad_value(1, 1)
60
+ individual_values, total_value = result
61
+ print("Individual letter values:", individual_values)
62
+ ```<end_code
63
+ Observation:
64
+ Individual letter values: 2, 60, 40, 1, 30, 30, 5, 1, 30, 200, 8, 40, 50, 1, 30, 200, 8, 10, 40
65
+
66
+ Thought: I have now the individual Abjad values for each letter in the text.
67
+ Code:
68
+ ```py
69
+ print("Total value:", total_value)
70
+ ```<end_code>
71
+ Observation: Total value: 786
72
+
73
+ Thought: I will inform the user about the results, which consists of the individual Abjad values for each letter in the text and the total Abjad value for the entire text.
74
+ Code:
75
+ ```py
76
+ final_answer(result)
77
+ ```<end_code>
78
+ ---
79
+ Task: "decode this text: jEVHKZ9LdOXVLOYFLKfFdeFdKWZHAKOLG"
80
+
81
+ Thought: I can encode and decode texts using the encode_text and decode_text tools.
82
+ Code:
83
+ ```py
84
+ result = decode_text('jEVHKZ9LdOXVLOYFLKfFdeFdKWZHAKOLG')
85
+ print(reult)
86
+ ```<end_code
87
+ Observation:
88
+ Hallo, wie geht es dir?
89
+
90
+ Thought: I will inform the user that I decoded "jEVHKZ9LdOXVLOYFLKfFdeFdKWZHAKOLG" successfully.
91
+ Code:
92
+ ```py
93
+ final_answer(result)
94
+ ```<end_code>
95
+ ---
96
+ Task: "encode this text: Hallo, wie geht es dir?"
97
+
98
+ Thought: I can encode and decode texts using the encode_text and decode_text tools.
99
+ Code:
100
+ ```py
101
+ result = encode_text('Hallo, wie geht es dir?')
102
+ print(reult)
103
+ ```<end_code
104
+ Observation:
105
+ jEVHKZ9LdOXVLOYFLKfFdeFdKWZHAKOLG
106
+
107
+ Thought: I will inform the user that I encoded "Hallo, wie geht es dir?" successfully.
108
+ Code:
109
+ ```py
110
+ final_answer(result)
111
+ ```<end_code>
112
+ ---
113
+ Task: "Write code to make a loop in C++"
114
+
115
+ Thought: This query is not related to the Noble Quran.
116
+ Code:
117
+ ```py
118
+ result = "I am so sorry. I can only provide assistance for searching the Noble Quran using tools provided by quran-challenge.com."
119
+ print(reult)
120
+ ```<end_code
121
+ Observation:
122
+ I am so sorry. I can only provide assistance for searching the Noble Quran using tools provided by quran-challenge.com.
123
+
124
+ Thought: I will apologize politely and inform the user the I can only provide assistance for searching the Noble Quran using tools provided by quran-challenge.com.
125
+ Code:
126
+ ```py
127
+ final_answer(result)
128
+ ```<end_code>
129
+ ---
130
+ Task: "What is the weather in Berlin now?"
131
+
132
+ Thought: This query is not related to the Noble Quran.
133
+ Code:
134
+ ```py
135
+ result = "I am so sorry. I can only provide assistance for searching the Noble Quran using tools provided by quran-challenge.com."
136
+ print(reult)
137
+ ```<end_code
138
+ Observation:
139
+ I am so sorry. I can only provide assistance for searching the Noble Quran using tools provided by quran-challenge.com.
140
+
141
+ Thought: I will apologize politely and inform the user the I can only provide assistance for searching the Noble Quran using tools provided by quran-challenge.com.
142
+ Code:
143
+ ```py
144
+ final_answer(result)
145
+ ```<end_code>
146
+ ---
147
+ Task: "Search for the word لحم in the Quran"
148
+
149
+ Thought: I will be able to get the results using the following tools: `search_quran` built by quran-challenge.com to find the word لحم in the Noble Quran.
150
+ Code:
151
+ ```py
152
+ result = search_quran('word', 'لحم')
153
+ print(reult)
154
+ ```<end_code
155
+ Observation:
156
+ 18:60 وإذ قال موسى لفتيه لا أبرح حتى أبلغ <span class="hilite">مجمع</span> <span class="hilite">البحرين</span> أو أمضي حقبا
157
+
158
+ Thought: I will now return the list as it is to the user
159
+ Code:
160
+ ```py
161
+ final_answer(result)
162
+ ```<end_code>
163
+ ---
164
+ Task: "Search for verses containing the word مجمع and the word البحرين in the Quran"
165
+
166
+ Thought: I will be able to get the results using the following tools: `search_quran_advanced` built by quran-challenge.com to find the verses the contain the words: (مجمع, البحرين) in the Noble Quran.
167
+ Code:
168
+ ```py
169
+ result = search_quran_advanced([('word', 'مجمع'), ('word', 'البحرين')], 'VAND')
170
+ print(reult)
171
+ ```<end_code
172
+ Observation:
173
+ 18:60 وإذ قال موسى لفتيه لا أبرح حتى أبلغ <span class="hilite">مجمع</span> <span class="hilite">البحرين</span> أو أمضي حقبا
174
+
175
+ Thought: I will now return the list as it is to the user
176
+ Code:
177
+ ```py
178
+ final_answer(result)
179
+ ```<end_code>
180
+ ---
181
+ Task: "Generate an image of the oldest person in this document."
182
+
183
+ Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
184
+ Code:
185
+ ```py
186
+ answer = document_qa(document=document, question="Who is the oldest person mentioned?")
187
+ print(answer)
188
+ ```<end_code>
189
+ Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
190
+
191
+ Thought: I will now generate an image showcasing the oldest person.
192
+ Code:
193
+ ```py
194
+ image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
195
+ final_answer(image)
196
+ ```<end_code>
197
+
198
+ ---
199
+ Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
200
+
201
+ Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
202
+ Code:
203
+ ```py
204
+ result = 5 + 3 + 1294.678
205
+ final_answer(result)
206
+ ```<end_code>
207
+
208
+ ---
209
+ Task:
210
+ "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
211
+ You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
212
+ {'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
213
+
214
+ Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
215
+ Code:
216
+ ```py
217
+ translated_question = translator(question=question, src_lang="French", tgt_lang="English")
218
+ print(f"The translated question is {translated_question}.")
219
+ answer = image_qa(image=image, question=translated_question)
220
+ final_answer(f"The answer is {answer}")
221
+ ```<end_code>
222
+
223
+ ---
224
+ Task:
225
+ In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
226
+ What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
227
+
228
+ Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
229
+ Code:
230
+ ```py
231
+ pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
232
+ print(pages)
233
+ ```<end_code>
234
+ Observation:
235
+ No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
236
+
237
+ Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
238
+ Code:
239
+ ```py
240
+ pages = search(query="1979 interview Stanislaus Ulam")
241
+ print(pages)
242
+ ```<end_code>
243
+ Observation:
244
+ Found 6 pages:
245
+ [Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
246
+
247
+ [Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
248
+
249
+ (truncated)
250
+
251
+ Thought: I will read the first 2 pages to know more.
252
+ Code:
253
+ ```py
254
+ for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
255
+ whole_page = visit_webpage(url)
256
+ print(whole_page)
257
+ print("\n" + "="*80 + "\n") # Print separator between pages
258
+ ```<end_code>
259
+ Observation:
260
+ Manhattan Project Locations:
261
+ Los Alamos, NM
262
+ Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at
263
+ (truncated)
264
+
265
+ Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word.
266
+ Code:
267
+ ```py
268
+ final_answer("diminished")
269
+ ```<end_code>
270
+
271
+ ---
272
+ Task: "Which city has the highest population: Guangzhou or Shanghai?"
273
+
274
+ Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.
275
+ Code:
276
+ ```py
277
+ for city in ["Guangzhou", "Shanghai"]:
278
+ print(f"Population {city}:", search(f"{city} population")
279
+ ```<end_code>
280
+ Observation:
281
+ Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
282
+ Population Shanghai: '26 million (2019)'
283
+
284
+ Thought: Now I know that Shanghai has the highest population.
285
+ Code:
286
+ ```py
287
+ final_answer("Shanghai")
288
+ ```<end_code>
289
+
290
+ ---
291
+ Task: "What is the current age of the pope, raised to the power 0.36?"
292
+
293
+ Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
294
+ Code:
295
+ ```py
296
+ pope_age_wiki = wiki(query="current pope age")
297
+ print("Pope age as per wikipedia:", pope_age_wiki)
298
+ pope_age_search = web_search(query="current pope age")
299
+ print("Pope age as per google search:", pope_age_search)
300
+ ```<end_code>
301
+ Observation:
302
+ Pope age: "The pope Francis is currently 88 years old."
303
+
304
+ Thought: I know that the pope is 88 years old. Let's compute the result using python code.
305
+ Code:
306
+ ```py
307
+ pope_current_age = 88 ** 0.36
308
+ final_answer(pope_current_age)
309
+ ```<end_code>
310
+
311
+ Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools:
312
+ {%- for tool in tools.values() %}
313
+ - {{ tool.name }}: {{ tool.description }}
314
+ Takes inputs: {{tool.inputs}}
315
+ Returns an output of type: {{tool.output_type}}
316
+ {%- endfor %}
317
+
318
+ {%- if managed_agents and managed_agents.values() | list %}
319
+ You can also give tasks to team members.
320
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task', a long string explaining your task.
321
+ Given that this team member is a real human, you should be very verbose in your task.
322
+ Here is a list of the team members that you can call:
323
+ {%- for agent in managed_agents.values() %}
324
+ - {{ agent.name }}: {{ agent.description }}
325
+ {%- endfor %}
326
+ {%- else %}
327
+ {%- endif %}
328
+
329
+ Here are the rules you should always follow to solve your task:
330
+ 1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
331
+ 2. Use only variables that you have defined!
332
+ 3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
333
+ 4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
334
+ 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
335
+ 6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
336
+ 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
337
+ 8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
338
+ 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
339
+ 10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
340
+
341
+ Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
342
+ "planning":
343
+ "initial_facts": |-
344
+ Below I will present you a task.
345
+
346
+ You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
347
+ To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
348
+ Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
349
+
350
+ ---
351
+ ### 1. Facts given in the task
352
+ List here the specific facts given in the task that could help you (there might be nothing here).
353
+
354
+ ### 2. Facts to look up
355
+ List here any facts that we may need to look up.
356
+ 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.
357
+
358
+ ### 3. Facts to derive
359
+ List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
360
+
361
+ Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
362
+ ### 1. Facts given in the task
363
+ ### 2. Facts to look up
364
+ ### 3. Facts to derive
365
+ Do not add anything else.
366
+ "initial_plan": |-
367
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
368
+
369
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
370
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
371
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
372
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
373
+
374
+ Here is your task:
375
+
376
+ Task:
377
+ ```
378
+ {{task}}
379
+ ```
380
+ You can leverage these tools:
381
+ {%- for tool in tools.values() %}
382
+ - {{ tool.name }}: {{ tool.description }}
383
+ Takes inputs: {{tool.inputs}}
384
+ Returns an output of type: {{tool.output_type}}
385
+ {%- endfor %}
386
+
387
+ {%- if managed_agents and managed_agents.values() | list %}
388
+ You can also give tasks to team members.
389
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.
390
+ Given that this team member is a real human, you should be very verbose in your request.
391
+ Here is a list of the team members that you can call:
392
+ {%- for agent in managed_agents.values() %}
393
+ - {{ agent.name }}: {{ agent.description }}
394
+ {%- endfor %}
395
+ {%- else %}
396
+ {%- endif %}
397
+
398
+ List of facts that you know:
399
+ ```
400
+ {{answer_facts}}
401
+ ```
402
+
403
+ Now begin! Write your plan below.
404
+ "update_facts_pre_messages": |-
405
+ You are a world expert at gathering known and unknown facts based on a conversation.
406
+ 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:
407
+ ### 1. Facts given in the task
408
+ ### 2. Facts that we have learned
409
+ ### 3. Facts still to look up
410
+ ### 4. Facts still to derive
411
+ Find the task and history below:
412
+ "update_facts_post_messages": |-
413
+ Earlier we've built a list of facts.
414
+ But since in your previous steps you may have learned useful new facts or invalidated some false ones.
415
+ Please update your list of facts based on the previous history, and provide these headings:
416
+ ### 1. Facts given in the task
417
+ ### 2. Facts that we have learned
418
+ ### 3. Facts still to look up
419
+ ### 4. Facts still to derive
420
+
421
+ Now write your new list of facts below.
422
+ "update_plan_pre_messages": |-
423
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
424
+
425
+ You have been given a task:
426
+ ```
427
+ {{task}}
428
+ ```
429
+
430
+ 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.
431
+ If the previous tries so far have met some success, you can make an updated plan based on these actions.
432
+ If you are stalled, you can make a completely new plan starting from scratch.
433
+ "update_plan_post_messages": |-
434
+ You're still working towards solving this task:
435
+ ```
436
+ {{task}}
437
+ ```
438
+
439
+ You can leverage these tools:
440
+ {%- for tool in tools.values() %}
441
+ - {{ tool.name }}: {{ tool.description }}
442
+ Takes inputs: {{tool.inputs}}
443
+ Returns an output of type: {{tool.output_type}}
444
+ {%- endfor %}
445
+
446
+ {%- if managed_agents and managed_agents.values() | list %}
447
+ You can also give tasks to team members.
448
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
449
+ Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
450
+ Here is a list of the team members that you can call:
451
+ {%- for agent in managed_agents.values() %}
452
+ - {{ agent.name }}: {{ agent.description }}
453
+ {%- endfor %}
454
+ {%- else %}
455
+ {%- endif %}
456
+
457
+ Here is the up to date list of facts that you know:
458
+ ```
459
+ {{facts_update}}
460
+ ```
461
+
462
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
463
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
464
+ Beware that you have {remaining_steps} steps remaining.
465
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
466
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
467
+
468
+ Now write your new plan below.
469
+ "managed_agent":
470
+ "task": |-
471
+ You're a helpful agent named '{{name}}'.
472
+ You have been submitted this task by your manager.
473
+ ---
474
+ Task:
475
+ {{task}}
476
+ ---
477
+ 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.
478
+
479
+ Your final_answer WILL HAVE to contain these parts:
480
+ ### 1. Task outcome (short version):
481
+ ### 2. Task outcome (extremely detailed version):
482
+ ### 3. Additional context (if relevant):
483
+
484
+ Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
485
+ 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.
486
+ "report": |-
487
+ Here is the final answer from your managed agent '{{name}}':
488
+ {{final_answer}}
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ markdownify
2
+ smolagents
3
+ requests
4
+ duckduckgo_search
5
+ pandas
6
+ smolagents[openai]