duongtruongbinh commited on
Commit
414914f
·
1 Parent(s): 1205948

Update agent & app

Browse files
Files changed (7) hide show
  1. README.md +4 -4
  2. agent.json +6 -7
  3. app.py +33 -16
  4. gradio_ui.py +369 -0
  5. prompts.yaml +68 -80
  6. requirements.txt +2 -1
  7. static/aivn_logo.png +0 -0
README.md CHANGED
@@ -1,10 +1,10 @@
1
  ---
2
  title: Smolagents Vnexpress News Codeagent
3
- emoji: 😻
4
- colorFrom: gray
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 5.25.2
8
  app_file: app.py
9
  pinned: false
10
  tags:
 
1
  ---
2
  title: Smolagents Vnexpress News Codeagent
3
+ emoji: 🐢
4
+ colorFrom: indigo
5
+ colorTo: yellow
6
  sdk: gradio
7
+ sdk_version: 5.23.3
8
  app_file: app.py
9
  pinned: false
10
  tags:
agent.json CHANGED
@@ -1,5 +1,4 @@
1
  {
2
- "class": "CodeAgent",
3
  "tools": [
4
  "fetch_lastest_news_titles_and_urls",
5
  "summarize_news",
@@ -11,18 +10,18 @@
11
  "class": "TransformersModel",
12
  "data": {
13
  "max_new_tokens": 2000,
14
- "last_input_token_count": 2847,
15
- "last_output_token_count": 736,
16
  "model_id": "Qwen/Qwen2.5-Coder-3B-Instruct"
17
  }
18
  },
19
  "managed_agents": {},
20
  "prompt_templates": {
21
- "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, behaving like regular python functions:\n```python\n{%- for tool in tools.values() %}\ndef {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:\n \"\"\"{{ tool.description }}\n\n Args:\n {%- for arg_name, arg_info in tool.inputs.items() %}\n {{ arg_name }}: {{ arg_info.description }}\n {%- endfor %}\n \"\"\"\n{% endfor %}\n```\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```python\n{%- for agent in managed_agents.values() %}\ndef {{ agent.name }}(\"Your query goes here.\") -> str:\n \"\"\"{{ agent.description }}\"\"\"\n{% endfor %}\n```\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!",
22
  "planning": {
23
- "initial_plan": "You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.\nBelow I will present you a task. You will need to 1. build a survey of facts known or needed to solve the task, then 2. make a plan of action to solve the task.\n\n## 1. Facts survey\nYou will build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.\nThese \"facts\" will typically be specific names, dates, values, etc. Your answer should use the below headings:\n### 1.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### 1.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### 1.3. Facts to derive\nList here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.\n\nDon't make any assumptions. For each item, provide a thorough reasoning. Do not add anything else on top of three headings above.\n\n## 2. Plan\nThen 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\nYou can leverage these tools, behaving like regular python functions:\n```python\n{%- for tool in tools.values() %}\ndef {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:\n \"\"\"{{ tool.description }}\n\n Args:\n {%- for arg_name, arg_info in tool.inputs.items() %}\n {{ arg_name }}: {{ arg_info.description }}\n {%- endfor %}\n \"\"\"\n{% endfor %}\n```\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```python\n{%- for agent in managed_agents.values() %}\ndef {{ agent.name }}(\"Your query goes here.\") -> str:\n \"\"\"{{ agent.description }}\"\"\"\n{% endfor %}\n```\n{%- endif %}\n\n---\nNow begin! Here is your task:\n```\n{{task}}\n```\nFirst in part 1, write the facts survey, then in part 2, write your plan.",
24
- "update_plan_pre_messages": "You are a world expert at analyzing a situation, and plan accordingly towards solving a task.\nYou have been given the following task:\n```\n{{task}}\n```\n\nBelow you will find a history of attempts made to solve this task.\nYou will first have to produce a survey of known and unknown facts, then propose a step-by-step high-level plan to solve the task.\nIf the previous tries so far have met some success, your updated plan can build on these results.\nIf you are stalled, you can make a completely new plan starting from scratch.\n\nFind the task and history below:",
25
- "update_plan_post_messages": "Now write your updated facts below, taking into account the above history:\n## 1. Updated facts survey\n### 1.1. Facts given in the task\n### 1.2. Facts that we have learned\n### 1.3. Facts still to look up\n### 1.4. Facts still to derive\n\nThen write a step-by-step high-level plan to solve the task above.\n## 2. Plan\n### 2. 1. ...\nEtc.\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\nYou can leverage these tools, behaving like regular python functions:\n```python\n{%- for tool in tools.values() %}\ndef {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:\n \"\"\"{{ tool.description }}\n\n Args:\n {%- for arg_name, arg_info in tool.inputs.items() %}\n {{ arg_name }}: {{ arg_info.description }}\n {%- endfor %}\"\"\"\n{% endfor %}\n```\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```python\n{%- for agent in managed_agents.values() %}\ndef {{ agent.name }}(\"Your query goes here.\") -> str:\n \"\"\"{{ agent.description }}\"\"\"\n{% endfor %}\n```\n{%- endif %}\n\nNow write your updated facts survey below, then your new plan."
26
  },
27
  "managed_agent": {
28
  "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.",
 
1
  {
 
2
  "tools": [
3
  "fetch_lastest_news_titles_and_urls",
4
  "summarize_news",
 
10
  "class": "TransformersModel",
11
  "data": {
12
  "max_new_tokens": 2000,
13
+ "last_input_token_count": 2294,
14
+ "last_output_token_count": 358,
15
  "model_id": "Qwen/Qwen2.5-Coder-3B-Instruct"
16
  }
17
  },
18
  "managed_agents": {},
19
  "prompt_templates": {
20
+ "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{%- 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.",
21
  "planning": {
22
+ "initial_plan": "You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.\nBelow I will present you a task. You will need to 1. build a survey of facts known or needed to solve the task, then 2. make a plan of action to solve the task.\n\n1. You will 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## Facts survey\n### 1.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### 1.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### 1.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.1. Facts given in the task\n### 1.2. Facts to look up\n### 1.3. Facts to derive\nDo not add anything else.\n\n## Plan\nThen 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```\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', 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{%- endif %}\n\nNow begin! First in part 1, list the facts that you have at your disposal, then in part 2, make a plan to solve the task.",
23
+ "update_plan_pre_messages": "You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.\nYou have been given a task:\n```\n{{task}}\n```\nBelow you will find a history of attempts made to solve the task. You will first have to produce a survey of known and unknown facts:\n\n## Facts survey\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\nThen you will have to propose 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.\n\nFind the task and history below:",
24
+ "update_plan_post_messages": "Now write your updated facts below, taking into account the above history:\n\n## Updated facts survey\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\nThen write a step-by-step high-level plan to solve the task above.\n## Plan\n### 1. ...\nEtc\n\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\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{%- endif %}\n\nNow write your new plan below."
25
  },
26
  "managed_agent": {
27
  "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.",
app.py CHANGED
@@ -1,22 +1,27 @@
 
 
 
 
 
1
  import yaml
 
2
  import os
3
- from smolagents import GradioUI, CodeAgent, TransformersModel
 
 
4
 
5
- # Get current directory path
6
- CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
7
 
8
- from tools.fetch_lastest_news_titles_and_urls import SimpleTool as FetchLastestNewsTitlesAndUrls
9
- from tools.summarize_news import SimpleTool as SummarizeNews
10
- from tools.extract_news_article_content import SimpleTool as ExtractNewsArticleContent
11
- from tools.classify_topic import SimpleTool as ClassifyTopic
12
- from tools.final_answer import FinalAnswerTool as FinalAnswer
 
13
 
14
 
 
 
15
 
16
- model = TransformersModel(
17
- max_new_tokens=2000,
18
- model_id='Qwen/Qwen2.5-Coder-3B-Instruct',
19
- )
20
 
21
  fetch_lastest_news_titles_and_urls = FetchLastestNewsTitlesAndUrls()
22
  summarize_news = SummarizeNews()
@@ -24,25 +29,37 @@ extract_news_article_content = ExtractNewsArticleContent()
24
  classify_topic = ClassifyTopic()
25
  final_answer = FinalAnswer()
26
 
 
 
 
 
27
 
28
  with open(os.path.join(CURRENT_DIR, "prompts.yaml"), 'r') as stream:
29
  prompt_templates = yaml.safe_load(stream)
30
 
 
31
  agent_news_agent = CodeAgent(
32
  model=model,
33
- tools=[fetch_lastest_news_titles_and_urls, summarize_news, extract_news_article_content, classify_topic],
 
34
  managed_agents=[],
35
- class='CodeAgent',
36
  max_steps=20,
37
  verbosity_level=2,
38
  grammar=None,
39
  planning_interval=None,
40
  name='news_agent',
41
- description='This agent is a smart news aggregator that fetches, summarizes, and classifies real-time news updates.',
42
  executor_type='local',
43
  executor_kwargs={},
44
  max_print_outputs_length=None,
45
  prompt_templates=prompt_templates
46
  )
47
- if __name__ == "__main__":
 
 
 
48
  GradioUI(agent_news_agent).launch()
 
 
 
 
 
1
+ from tools.final_answer import FinalAnswerTool as FinalAnswer
2
+ from tools.classify_topic import SimpleTool as ClassifyTopic
3
+ from tools.extract_news_article_content import SimpleTool as ExtractNewsArticleContent
4
+ from tools.summarize_news import SimpleTool as SummarizeNews
5
+ from tools.fetch_lastest_news_titles_and_urls import SimpleTool as FetchLastestNewsTitlesAndUrls
6
  import yaml
7
+ import spaces
8
  import os
9
+ from smolagents import CodeAgent, TransformersModel
10
+ from gradio_ui import GradioUI
11
+ import torch
12
 
 
 
13
 
14
+ def set_seed(seed: int):
15
+ torch.manual_seed(seed)
16
+ torch.cuda.manual_seed_all(seed)
17
+ torch.cuda.manual_seed(seed)
18
+ torch.backends.cudnn.deterministic = True
19
+ torch.backends.cudnn.benchmark = False
20
 
21
 
22
+ set_seed(42)
23
+ CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
24
 
 
 
 
 
25
 
26
  fetch_lastest_news_titles_and_urls = FetchLastestNewsTitlesAndUrls()
27
  summarize_news = SummarizeNews()
 
29
  classify_topic = ClassifyTopic()
30
  final_answer = FinalAnswer()
31
 
32
+ model = TransformersModel(
33
+ max_new_tokens=2000,
34
+ model_id='Qwen/Qwen2.5-Coder-3B-Instruct',
35
+ )
36
 
37
  with open(os.path.join(CURRENT_DIR, "prompts.yaml"), 'r') as stream:
38
  prompt_templates = yaml.safe_load(stream)
39
 
40
+
41
  agent_news_agent = CodeAgent(
42
  model=model,
43
+ tools=[fetch_lastest_news_titles_and_urls, summarize_news,
44
+ extract_news_article_content, classify_topic],
45
  managed_agents=[],
 
46
  max_steps=20,
47
  verbosity_level=2,
48
  grammar=None,
49
  planning_interval=None,
50
  name='news_agent',
51
+ description="This agent is a smart news aggregator that fetches, summarizes, and classifies real-time news updates.",
52
  executor_type='local',
53
  executor_kwargs={},
54
  max_print_outputs_length=None,
55
  prompt_templates=prompt_templates
56
  )
57
+
58
+
59
+ @spaces.GPU
60
+ def run_agent():
61
  GradioUI(agent_news_agent).launch()
62
+
63
+
64
+ if __name__ == "__main__":
65
+ run_agent()
gradio_ui.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
17
+ import re
18
+ import shutil
19
+ from typing import Optional
20
+
21
+ from smolagents.agent_types import AgentAudio, AgentImage, AgentText
22
+ from smolagents.agents import MultiStepAgent, PlanningStep
23
+ from smolagents.memory import ActionStep, FinalAnswerStep, MemoryStep
24
+ from smolagents.utils import _is_package_available
25
+ import base64
26
+
27
+ def image_to_base64(image_path):
28
+ with open(image_path, "rb") as image_file:
29
+ return base64.b64encode(image_file.read()).decode('utf-8')
30
+
31
+ def get_step_footnote_content(step_log: MemoryStep, step_name: str) -> str:
32
+ """Get a footnote string for a step log with duration and token information"""
33
+ step_footnote = f"**{step_name}**"
34
+ if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
35
+ token_str = f" | Input tokens:{step_log.input_token_count:,} | Output tokens: {step_log.output_token_count:,}"
36
+ step_footnote += token_str
37
+ if hasattr(step_log, "duration"):
38
+ step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
39
+ step_footnote += step_duration
40
+ step_footnote_content = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
41
+ return step_footnote_content
42
+
43
+
44
+ def pull_messages_from_step(
45
+ step_log: MemoryStep,
46
+ ):
47
+ """Extract ChatMessage objects from agent steps with proper nesting"""
48
+ if not _is_package_available("gradio"):
49
+ raise ModuleNotFoundError(
50
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
51
+ )
52
+ import gradio as gr
53
+
54
+ if isinstance(step_log, ActionStep):
55
+ # Output the step number
56
+ step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else "Step"
57
+ yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
58
+
59
+ # First yield the thought/reasoning from the LLM
60
+ if hasattr(step_log, "model_output") and step_log.model_output is not None:
61
+ # Clean up the LLM output
62
+ model_output = step_log.model_output.strip()
63
+ # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
64
+ model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>
65
+ model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```
66
+ model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>
67
+ model_output = model_output.strip()
68
+ yield gr.ChatMessage(role="assistant", content=model_output)
69
+
70
+ # For tool calls, create a parent message
71
+ if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
72
+ first_tool_call = step_log.tool_calls[0]
73
+ used_code = first_tool_call.name == "python_interpreter"
74
+ parent_id = f"call_{len(step_log.tool_calls)}"
75
+
76
+ # Tool call becomes the parent message with timing info
77
+ # First we will handle arguments based on type
78
+ args = first_tool_call.arguments
79
+ if isinstance(args, dict):
80
+ content = str(args.get("answer", str(args)))
81
+ else:
82
+ content = str(args).strip()
83
+
84
+ if used_code:
85
+ # Clean up the content by removing any end code tags
86
+ content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks
87
+ content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags
88
+ content = content.strip()
89
+ if not content.startswith("```python"):
90
+ content = f"```python\n{content}\n```"
91
+
92
+ parent_message_tool = gr.ChatMessage(
93
+ role="assistant",
94
+ content=content,
95
+ metadata={
96
+ "title": f"🛠️ Used tool {first_tool_call.name}",
97
+ "id": parent_id,
98
+ "status": "done",
99
+ },
100
+ )
101
+ yield parent_message_tool
102
+
103
+ # Display execution logs if they exist
104
+ if hasattr(step_log, "observations") and (
105
+ step_log.observations is not None and step_log.observations.strip()
106
+ ): # Only yield execution logs if there's actual content
107
+ log_content = step_log.observations.strip()
108
+ if log_content:
109
+ log_content = re.sub(r"^Execution logs:\s*", "", log_content)
110
+ yield gr.ChatMessage(
111
+ role="assistant",
112
+ content=f"```bash\n{log_content}\n",
113
+ metadata={"title": "📝 Execution Logs", "status": "done"},
114
+ )
115
+
116
+ # Display any errors
117
+ if hasattr(step_log, "error") and step_log.error is not None:
118
+ yield gr.ChatMessage(
119
+ role="assistant",
120
+ content=str(step_log.error),
121
+ metadata={"title": "💥 Error", "status": "done"},
122
+ )
123
+
124
+ # Update parent message metadata to done status without yielding a new message
125
+ if getattr(step_log, "observations_images", []):
126
+ for image in step_log.observations_images:
127
+ path_image = AgentImage(image).to_string()
128
+ yield gr.ChatMessage(
129
+ role="assistant",
130
+ content={"path": path_image, "mime_type": f"image/{path_image.split('.')[-1]}"},
131
+ metadata={"title": "🖼️ Output Image", "status": "done"},
132
+ )
133
+
134
+ # Handle standalone errors but not from tool calls
135
+ if hasattr(step_log, "error") and step_log.error is not None:
136
+ yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
137
+
138
+ yield gr.ChatMessage(role="assistant", content=get_step_footnote_content(step_log, step_number))
139
+ yield gr.ChatMessage(role="assistant", content="-----", metadata={"status": "done"})
140
+
141
+ elif isinstance(step_log, PlanningStep):
142
+ yield gr.ChatMessage(role="assistant", content="**Planning step**")
143
+ yield gr.ChatMessage(role="assistant", content=step_log.plan)
144
+ yield gr.ChatMessage(role="assistant", content=get_step_footnote_content(step_log, "Planning step"))
145
+ yield gr.ChatMessage(role="assistant", content="-----", metadata={"status": "done"})
146
+
147
+ elif isinstance(step_log, FinalAnswerStep):
148
+ final_answer = step_log.final_answer
149
+ if isinstance(final_answer, AgentText):
150
+ yield gr.ChatMessage(
151
+ role="assistant",
152
+ content=f"**Final answer:**\n{final_answer.to_string()}\n",
153
+ )
154
+ elif isinstance(final_answer, AgentImage):
155
+ yield gr.ChatMessage(
156
+ role="assistant",
157
+ content={"path": final_answer.to_string(), "mime_type": "image/png"},
158
+ )
159
+ elif isinstance(final_answer, AgentAudio):
160
+ yield gr.ChatMessage(
161
+ role="assistant",
162
+ content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
163
+ )
164
+ else:
165
+ yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
166
+
167
+ else:
168
+ raise ValueError(f"Unsupported step type: {type(step_log)}")
169
+
170
+
171
+ def stream_to_gradio(
172
+ agent,
173
+ task: str,
174
+ reset_agent_memory: bool = False,
175
+ additional_args: Optional[dict] = None,
176
+ ):
177
+ """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
178
+ total_input_tokens = 0
179
+ total_output_tokens = 0
180
+
181
+ for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
182
+ # Track tokens if model provides them
183
+ if getattr(agent.model, "last_input_token_count", None) is not None:
184
+ total_input_tokens += agent.model.last_input_token_count
185
+ total_output_tokens += agent.model.last_output_token_count
186
+ if isinstance(step_log, (ActionStep, PlanningStep)):
187
+ step_log.input_token_count = agent.model.last_input_token_count
188
+ step_log.output_token_count = agent.model.last_output_token_count
189
+
190
+ for message in pull_messages_from_step(
191
+ step_log,
192
+ ):
193
+ yield message
194
+
195
+
196
+ class GradioUI:
197
+ """A one-line interface to launch your agent in Gradio"""
198
+
199
+ def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
200
+ if not _is_package_available("gradio"):
201
+ raise ModuleNotFoundError(
202
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
203
+ )
204
+ self.agent = agent
205
+ self.file_upload_folder = file_upload_folder
206
+ self.name = getattr(agent, "name") or "Agent interface"
207
+ self.description = getattr(agent, "description", None)
208
+ if self.file_upload_folder is not None:
209
+ if not os.path.exists(file_upload_folder):
210
+ os.mkdir(file_upload_folder)
211
+
212
+ def interact_with_agent(self, prompt, messages, session_state):
213
+ import gradio as gr
214
+
215
+ # Get the agent type from the template agent
216
+ if "agent" not in session_state:
217
+ session_state["agent"] = self.agent
218
+
219
+ try:
220
+ messages.append(gr.ChatMessage(role="user", content=prompt))
221
+ yield messages
222
+
223
+ for msg in stream_to_gradio(session_state["agent"], task=prompt, reset_agent_memory=False):
224
+ messages.append(msg)
225
+ yield messages
226
+
227
+ yield messages
228
+ except Exception as e:
229
+ print(f"Error in interaction: {str(e)}")
230
+ messages.append(gr.ChatMessage(role="assistant", content=f"Error: {str(e)}"))
231
+ yield messages
232
+
233
+ def upload_file(self, file, file_uploads_log, allowed_file_types=None):
234
+ """
235
+ Handle file uploads, default allowed types are .pdf, .docx, and .txt
236
+ """
237
+ import gradio as gr
238
+
239
+ if file is None:
240
+ return gr.Textbox(value="No file uploaded", visible=True), file_uploads_log
241
+
242
+ if allowed_file_types is None:
243
+ allowed_file_types = [".pdf", ".docx", ".txt"]
244
+
245
+ file_ext = os.path.splitext(file.name)[1].lower()
246
+ if file_ext not in allowed_file_types:
247
+ return gr.Textbox("File type disallowed", visible=True), file_uploads_log
248
+
249
+ # Sanitize file name
250
+ original_name = os.path.basename(file.name)
251
+ sanitized_name = re.sub(
252
+ r"[^\w\-.]", "_", original_name
253
+ ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
254
+
255
+ # Save the uploaded file to the specified folder
256
+ file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
257
+ shutil.copy(file.name, file_path)
258
+
259
+ return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]
260
+
261
+ def log_user_message(self, text_input, file_uploads_log):
262
+ import gradio as gr
263
+
264
+ return (
265
+ text_input
266
+ + (
267
+ f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
268
+ if len(file_uploads_log) > 0
269
+ else ""
270
+ ),
271
+ "",
272
+ gr.Button(interactive=False),
273
+ )
274
+
275
+ def launch(self, share: bool = True, **kwargs):
276
+ self.create_app().launch(debug=True, share=share, **kwargs)
277
+
278
+ def create_app(self):
279
+ import gradio as gr
280
+
281
+ with gr.Blocks(theme="ocean", fill_height=True) as demo:
282
+ # Add session state to store session-specific data
283
+ session_state = gr.State({})
284
+ stored_messages = gr.State([])
285
+ file_uploads_log = gr.State([])
286
+
287
+ with gr.Sidebar(width=400):
288
+ gr.Markdown(
289
+ f"# {self.name.replace('_', ' ').capitalize()}"
290
+ "\n### **AIO2024 Module 10**"
291
+ )
292
+
293
+ with gr.Row():
294
+ logo_base64 = image_to_base64("static/aivn_logo.png")
295
+ gr.HTML(f"""
296
+ <img src="data:image/png;base64,{logo_base64}"
297
+ alt="Logo"
298
+ style="display: block; margin: auto; height: 120px; width: auto; margin-bottom: 20px;">
299
+ """)
300
+ gr.Markdown(f"\n\n>{self.description}" if self.description else "")
301
+
302
+ with gr.Group():
303
+ gr.Markdown("**Your request**", container=True)
304
+ text_input = gr.Textbox(
305
+ lines=3,
306
+ label="Chat Message",
307
+ container=False,
308
+ placeholder="Enter your prompt here and press Shift+Enter or press the button",
309
+ )
310
+ submit_btn = gr.Button("Submit", variant="primary")
311
+
312
+ # If an upload folder is provided, enable the upload feature
313
+ if self.file_upload_folder is not None:
314
+ upload_file = gr.File(label="Upload a file")
315
+ upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
316
+ upload_file.change(
317
+ self.upload_file,
318
+ [upload_file, file_uploads_log],
319
+ [upload_status, file_uploads_log],
320
+ )
321
+
322
+
323
+ # Main chat interface
324
+ chatbot = gr.Chatbot(
325
+ label="Agent",
326
+ type="messages",
327
+ avatar_images=(
328
+ None,
329
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/mascot_smol.png",
330
+ ),
331
+ resizeable=True,
332
+ scale=1,
333
+ )
334
+
335
+ # Set up event handlers
336
+ text_input.submit(
337
+ self.log_user_message,
338
+ [text_input, file_uploads_log],
339
+ [stored_messages, text_input, submit_btn],
340
+ ).then(self.interact_with_agent, [stored_messages, chatbot, session_state], [chatbot]).then(
341
+ lambda: (
342
+ gr.Textbox(
343
+ interactive=True, placeholder="Enter your prompt here and press Shift+Enter or the button"
344
+ ),
345
+ gr.Button(interactive=True),
346
+ ),
347
+ None,
348
+ [text_input, submit_btn],
349
+ )
350
+
351
+ submit_btn.click(
352
+ self.log_user_message,
353
+ [text_input, file_uploads_log],
354
+ [stored_messages, text_input, submit_btn],
355
+ ).then(self.interact_with_agent, [stored_messages, chatbot, session_state], [chatbot]).then(
356
+ lambda: (
357
+ gr.Textbox(
358
+ interactive=True, placeholder="Enter your prompt here and press Shift+Enter or the button"
359
+ ),
360
+ gr.Button(interactive=True),
361
+ ),
362
+ None,
363
+ [text_input, submit_btn],
364
+ )
365
+
366
+ return demo
367
+
368
+
369
+ __all__ = ["stream_to_gradio", "GradioUI"]
prompts.yaml CHANGED
@@ -141,31 +141,21 @@
141
  final_answer(pope_current_age)
142
  ```<end_code>
143
 
144
- 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, behaving like regular python functions:
145
- ```python
146
  {%- for tool in tools.values() %}
147
- def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
148
- """{{ tool.description }}
149
-
150
- Args:
151
- {%- for arg_name, arg_info in tool.inputs.items() %}
152
- {{ arg_name }}: {{ arg_info.description }}
153
- {%- endfor %}
154
- """
155
- {% endfor %}
156
- ```
157
 
158
  {%- if managed_agents and managed_agents.values() | list %}
159
  You can also give tasks to team members.
160
- Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
161
- 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.
162
  Here is a list of the team members that you can call:
163
- ```python
164
  {%- for agent in managed_agents.values() %}
165
- def {{ agent.name }}("Your query goes here.") -> str:
166
- """{{ agent.description }}"""
167
- {% endfor %}
168
- ```
169
  {%- endif %}
170
 
171
  Here are the rules you should always follow to solve your task:
@@ -180,15 +170,18 @@
180
  9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
181
  10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
182
 
183
- Now Begin!
184
  "planning":
185
  "initial_plan": |-
186
  You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.
187
  Below I will present you a task. You will need to 1. build a survey of facts known or needed to solve the task, then 2. make a plan of action to solve the task.
188
 
189
- ## 1. Facts survey
190
- You will build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
191
- These "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
 
 
 
192
  ### 1.1. Facts given in the task
193
  List here the specific facts given in the task that could help you (there might be nothing here).
194
 
@@ -199,104 +192,99 @@
199
  ### 1.3. Facts to derive
200
  List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
201
 
202
- Don't make any assumptions. For each item, provide a thorough reasoning. Do not add anything else on top of three headings above.
 
 
 
 
203
 
204
- ## 2. Plan
205
  Then for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
206
  This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
207
  Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
208
  After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
209
 
210
- You can leverage these tools, behaving like regular python functions:
211
- ```python
212
- {%- for tool in tools.values() %}
213
- def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
214
- """{{ tool.description }}
215
-
216
- Args:
217
- {%- for arg_name, arg_info in tool.inputs.items() %}
218
- {{ arg_name }}: {{ arg_info.description }}
219
- {%- endfor %}
220
- """
221
- {% endfor %}
222
  ```
223
 
 
 
 
 
 
 
 
224
  {%- if managed_agents and managed_agents.values() | list %}
225
  You can also give tasks to team members.
226
- Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
227
- 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.
228
  Here is a list of the team members that you can call:
229
- ```python
230
  {%- for agent in managed_agents.values() %}
231
- def {{ agent.name }}("Your query goes here.") -> str:
232
- """{{ agent.description }}"""
233
- {% endfor %}
234
- ```
235
  {%- endif %}
236
 
237
- ---
238
- Now begin! Here is your task:
239
- ```
240
- {{task}}
241
- ```
242
- First in part 1, write the facts survey, then in part 2, write your plan.
243
  "update_plan_pre_messages": |-
244
- You are a world expert at analyzing a situation, and plan accordingly towards solving a task.
245
- You have been given the following task:
246
  ```
247
  {{task}}
248
  ```
 
249
 
250
- Below you will find a history of attempts made to solve this task.
251
- You will first have to produce a survey of known and unknown facts, then propose a step-by-step high-level plan to solve the task.
252
- If the previous tries so far have met some success, your updated plan can build on these results.
 
 
 
 
 
253
  If you are stalled, you can make a completely new plan starting from scratch.
254
 
255
  Find the task and history below:
256
  "update_plan_post_messages": |-
257
  Now write your updated facts below, taking into account the above history:
258
- ## 1. Updated facts survey
259
- ### 1.1. Facts given in the task
260
- ### 1.2. Facts that we have learned
261
- ### 1.3. Facts still to look up
262
- ### 1.4. Facts still to derive
 
263
 
264
  Then write a step-by-step high-level plan to solve the task above.
265
- ## 2. Plan
266
- ### 2. 1. ...
267
- Etc.
 
268
  This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
269
  Beware that you have {remaining_steps} steps remaining.
270
  Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
271
  After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
272
 
273
- You can leverage these tools, behaving like regular python functions:
274
- ```python
275
  {%- for tool in tools.values() %}
276
- def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
277
- """{{ tool.description }}
278
-
279
- Args:
280
- {%- for arg_name, arg_info in tool.inputs.items() %}
281
- {{ arg_name }}: {{ arg_info.description }}
282
- {%- endfor %}"""
283
- {% endfor %}
284
- ```
285
 
286
  {%- if managed_agents and managed_agents.values() | list %}
287
  You can also give tasks to team members.
288
  Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
289
  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.
290
  Here is a list of the team members that you can call:
291
- ```python
292
  {%- for agent in managed_agents.values() %}
293
- def {{ agent.name }}("Your query goes here.") -> str:
294
- """{{ agent.description }}"""
295
- {% endfor %}
296
- ```
297
  {%- endif %}
298
 
299
- Now write your updated facts survey below, then your new plan.
300
  "managed_agent":
301
  "task": |-
302
  You're a helpful agent named '{{name}}'.
 
141
  final_answer(pope_current_age)
142
  ```<end_code>
143
 
144
+ 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:
 
145
  {%- for tool in tools.values() %}
146
+ - {{ tool.name }}: {{ tool.description }}
147
+ Takes inputs: {{tool.inputs}}
148
+ Returns an output of type: {{tool.output_type}}
149
+ {%- endfor %}
 
 
 
 
 
 
150
 
151
  {%- if managed_agents and managed_agents.values() | list %}
152
  You can also give tasks to team members.
153
+ 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.
154
+ Given that this team member is a real human, you should be very verbose in your task.
155
  Here is a list of the team members that you can call:
 
156
  {%- for agent in managed_agents.values() %}
157
+ - {{ agent.name }}: {{ agent.description }}
158
+ {%- endfor %}
 
 
159
  {%- endif %}
160
 
161
  Here are the rules you should always follow to solve your task:
 
170
  9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
171
  10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
172
 
173
+ Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
174
  "planning":
175
  "initial_plan": |-
176
  You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.
177
  Below I will present you a task. You will need to 1. build a survey of facts known or needed to solve the task, then 2. make a plan of action to solve the task.
178
 
179
+ 1. You will build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
180
+ To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
181
+ Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
182
+
183
+ ---
184
+ ## Facts survey
185
  ### 1.1. Facts given in the task
186
  List here the specific facts given in the task that could help you (there might be nothing here).
187
 
 
192
  ### 1.3. Facts to derive
193
  List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
194
 
195
+ Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
196
+ ### 1.1. Facts given in the task
197
+ ### 1.2. Facts to look up
198
+ ### 1.3. Facts to derive
199
+ Do not add anything else.
200
 
201
+ ## Plan
202
  Then for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
203
  This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
204
  Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
205
  After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
206
 
207
+ Here is your task:
208
+
209
+ Task:
210
+ ```
211
+ {{task}}
 
 
 
 
 
 
 
212
  ```
213
 
214
+ You can leverage these tools:
215
+ {%- for tool in tools.values() %}
216
+ - {{ tool.name }}: {{ tool.description }}
217
+ Takes inputs: {{tool.inputs}}
218
+ Returns an output of type: {{tool.output_type}}
219
+ {%- endfor %}
220
+
221
  {%- if managed_agents and managed_agents.values() | list %}
222
  You can also give tasks to team members.
223
+ 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.
224
+ Given that this team member is a real human, you should be very verbose in your task.
225
  Here is a list of the team members that you can call:
 
226
  {%- for agent in managed_agents.values() %}
227
+ - {{ agent.name }}: {{ agent.description }}
228
+ {%- endfor %}
 
 
229
  {%- endif %}
230
 
231
+ Now begin! First in part 1, list the facts that you have at your disposal, then in part 2, make a plan to solve the task.
 
 
 
 
 
232
  "update_plan_pre_messages": |-
233
+ You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.
234
+ You have been given a task:
235
  ```
236
  {{task}}
237
  ```
238
+ Below you will find a history of attempts made to solve the task. You will first have to produce a survey of known and unknown facts:
239
 
240
+ ## Facts survey
241
+ ### 1. Facts given in the task
242
+ ### 2. Facts that we have learned
243
+ ### 3. Facts still to look up
244
+ ### 4. Facts still to derive
245
+
246
+ Then you will have to propose an updated plan to solve the task.
247
+ If the previous tries so far have met some success, you can make an updated plan based on these actions.
248
  If you are stalled, you can make a completely new plan starting from scratch.
249
 
250
  Find the task and history below:
251
  "update_plan_post_messages": |-
252
  Now write your updated facts below, taking into account the above history:
253
+
254
+ ## Updated facts survey
255
+ ### 1. Facts given in the task
256
+ ### 2. Facts that we have learned
257
+ ### 3. Facts still to look up
258
+ ### 4. Facts still to derive
259
 
260
  Then write a step-by-step high-level plan to solve the task above.
261
+ ## Plan
262
+ ### 1. ...
263
+ Etc
264
+
265
  This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
266
  Beware that you have {remaining_steps} steps remaining.
267
  Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
268
  After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
269
 
270
+ You can leverage these tools:
 
271
  {%- for tool in tools.values() %}
272
+ - {{ tool.name }}: {{ tool.description }}
273
+ Takes inputs: {{tool.inputs}}
274
+ Returns an output of type: {{tool.output_type}}
275
+ {%- endfor %}
 
 
 
 
 
276
 
277
  {%- if managed_agents and managed_agents.values() | list %}
278
  You can also give tasks to team members.
279
  Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
280
  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.
281
  Here is a list of the team members that you can call:
 
282
  {%- for agent in managed_agents.values() %}
283
+ - {{ agent.name }}: {{ agent.description }}
284
+ {%- endfor %}
 
 
285
  {%- endif %}
286
 
287
+ Now write your new plan below.
288
  "managed_agent":
289
  "task": |-
290
  You're a helpful agent named '{{name}}'.
requirements.txt CHANGED
@@ -2,4 +2,5 @@ bs4
2
  requests
3
  smolagents
4
  torch
5
- transformers
 
 
2
  requests
3
  smolagents
4
  torch
5
+ smolagents[transformers]
6
+ accelerate>=0.26.0
static/aivn_logo.png ADDED