Spaces:
Sleeping
Sleeping
Commit
·
47728dd
1
Parent(s):
ae04b8f
update agent to genearate streamlit app
Browse files- README.md +6 -6
- app.py +51 -2
- prompts.old +321 -0
- prompts.yaml +411 -77
- requirements.txt +4 -1
- streamlit_app.py +179 -16
- tools/validate_final_answer.py +21 -0
- visualizations.py +423 -0
README.md
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
---
|
2 |
title: First Agent Template
|
3 |
-
emoji:
|
4 |
colorFrom: pink
|
5 |
colorTo: yellow
|
6 |
sdk: gradio
|
@@ -15,16 +15,16 @@ tags:
|
|
15 |
- agent-course
|
16 |
---
|
17 |
|
18 |
-
# Simple Local Agent
|
19 |
|
20 |
Un agent conversationnel simple utilisant SmoLAgents pour se connecter à un modèle de langage, que ce soit via un serveur local (LMStudio) ou via d'autres APIs.
|
21 |
|
22 |
-
## Prérequis
|
23 |
|
24 |
- Python 3.8+
|
25 |
- Un modèle de langage hébergé localement ou accessible via une API
|
26 |
|
27 |
-
## Installation
|
28 |
|
29 |
1. Installez les dépendances requises :
|
30 |
|
@@ -32,7 +32,7 @@ Un agent conversationnel simple utilisant SmoLAgents pour se connecter à un mod
|
|
32 |
pip install -r requirements.txt
|
33 |
```
|
34 |
|
35 |
-
## Utilisation
|
36 |
|
37 |
### Interface Gradio
|
38 |
|
@@ -124,4 +124,4 @@ Voici quelques exemples de questions que vous pouvez poser à l'agent :
|
|
124 |
|
125 |
---
|
126 |
|
127 |
-
*Consultez la référence de configuration sur https://huggingface.co/docs/hub/spaces-config-reference*
|
|
|
1 |
---
|
2 |
title: First Agent Template
|
3 |
+
emoji: "🤖"
|
4 |
colorFrom: pink
|
5 |
colorTo: yellow
|
6 |
sdk: gradio
|
|
|
15 |
- agent-course
|
16 |
---
|
17 |
|
18 |
+
# Simple Local Agent
|
19 |
|
20 |
Un agent conversationnel simple utilisant SmoLAgents pour se connecter à un modèle de langage, que ce soit via un serveur local (LMStudio) ou via d'autres APIs.
|
21 |
|
22 |
+
## Prérequis
|
23 |
|
24 |
- Python 3.8+
|
25 |
- Un modèle de langage hébergé localement ou accessible via une API
|
26 |
|
27 |
+
## Installation
|
28 |
|
29 |
1. Installez les dépendances requises :
|
30 |
|
|
|
32 |
pip install -r requirements.txt
|
33 |
```
|
34 |
|
35 |
+
## Utilisation
|
36 |
|
37 |
### Interface Gradio
|
38 |
|
|
|
124 |
|
125 |
---
|
126 |
|
127 |
+
*Consultez la référence de configuration sur https://huggingface.co/docs/hub/spaces-config-reference*
|
app.py
CHANGED
@@ -3,12 +3,17 @@ import datetime
|
|
3 |
import requests
|
4 |
import pytz
|
5 |
import yaml
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
from tools.final_answer import FinalAnswerTool
|
7 |
from tools.visit_webpage import VisitWebpageTool
|
8 |
from tools.web_search import DuckDuckGoSearchTool
|
9 |
from Gradio_UI import GradioUI
|
10 |
from smolagents.models import OpenAIServerModel
|
11 |
-
from tools.shell_tool import ShellCommandTool
|
12 |
from tools.create_file_tool import CreateFileTool
|
13 |
from tools.modify_file_tool import ModifyFileTool
|
14 |
|
@@ -71,9 +76,18 @@ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_co
|
|
71 |
with open("prompts.yaml", 'r') as stream:
|
72 |
prompt_templates = yaml.safe_load(stream)
|
73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
agent = CodeAgent(
|
75 |
model=model,
|
76 |
-
tools=[final_answer, DuckDuckGoSearchTool(), VisitWebpageTool(),
|
77 |
max_steps=6,
|
78 |
verbosity_level=1,
|
79 |
grammar=None,
|
@@ -83,5 +97,40 @@ agent = CodeAgent(
|
|
83 |
prompt_templates=prompt_templates
|
84 |
)
|
85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
|
87 |
GradioUI(agent).launch()
|
|
|
3 |
import requests
|
4 |
import pytz
|
5 |
import yaml
|
6 |
+
import os
|
7 |
+
import sys
|
8 |
+
import subprocess # Ajout de l'import manquant pour ShellCommandTool
|
9 |
+
import io
|
10 |
+
import json
|
11 |
+
from huggingface_hub import HfApi
|
12 |
from tools.final_answer import FinalAnswerTool
|
13 |
from tools.visit_webpage import VisitWebpageTool
|
14 |
from tools.web_search import DuckDuckGoSearchTool
|
15 |
from Gradio_UI import GradioUI
|
16 |
from smolagents.models import OpenAIServerModel
|
|
|
17 |
from tools.create_file_tool import CreateFileTool
|
18 |
from tools.modify_file_tool import ModifyFileTool
|
19 |
|
|
|
76 |
with open("prompts.yaml", 'r') as stream:
|
77 |
prompt_templates = yaml.safe_load(stream)
|
78 |
|
79 |
+
# Tentative de correction pour ShellCommandTool
|
80 |
+
try:
|
81 |
+
from tools.shell_tool import ShellCommandTool
|
82 |
+
shell_tool = ShellCommandTool()
|
83 |
+
except Exception as e:
|
84 |
+
print(f"Erreur lors du chargement de ShellCommandTool: {e}")
|
85 |
+
# Créer une version simplifiée de l'outil si nécessaire
|
86 |
+
shell_tool = None
|
87 |
+
|
88 |
agent = CodeAgent(
|
89 |
model=model,
|
90 |
+
tools=[final_answer, DuckDuckGoSearchTool(), VisitWebpageTool(), CreateFileTool(), ModifyFileTool()],
|
91 |
max_steps=6,
|
92 |
verbosity_level=1,
|
93 |
grammar=None,
|
|
|
97 |
prompt_templates=prompt_templates
|
98 |
)
|
99 |
|
100 |
+
# Ajouter ShellCommandTool conditionnellement
|
101 |
+
if shell_tool is not None:
|
102 |
+
agent.tools['shell_command'] = shell_tool
|
103 |
+
|
104 |
+
# Sauvegarder manuellement sans utiliser to_dict() pour éviter les erreurs de validation
|
105 |
+
agent_data = {
|
106 |
+
"name": agent.name,
|
107 |
+
"description": agent.description,
|
108 |
+
"model": agent.model.to_dict() if hasattr(agent.model, "to_dict") else str(agent.model),
|
109 |
+
"tools": [tool.__class__.__name__ for tool in agent.tools.values()],
|
110 |
+
"max_steps": agent.max_steps,
|
111 |
+
"grammar": agent.grammar,
|
112 |
+
"planning_interval": agent.planning_interval,
|
113 |
+
}
|
114 |
+
|
115 |
+
# # Sauvegarder l'agent au format JSON personnalisé
|
116 |
+
# with open("agent.json", "w", encoding="utf-8") as f:
|
117 |
+
# json.dump(agent_data, f, ensure_ascii=False, indent=2)
|
118 |
+
|
119 |
+
# # La méthode push_to_hub pose problème avec les emojis, utiliser plutôt le script push_to_hf.py
|
120 |
+
# print("Agent sauvegardé dans agent.json. Utilisez push_to_hf.py pour le pousser sur Hugging Face.")
|
121 |
+
|
122 |
+
# Utiliser l'API Hugging Face directement avec encodage UTF-8
|
123 |
+
# try:
|
124 |
+
# api = HfApi()
|
125 |
+
# api.upload_file(
|
126 |
+
# path_or_fileobj="agent.json",
|
127 |
+
# path_in_repo="agent.json",
|
128 |
+
# repo_id="KebabLover/SmolCoderAgent_0_1",
|
129 |
+
# repo_type="space",
|
130 |
+
# commit_message="Mise à jour de l'agent"
|
131 |
+
# )
|
132 |
+
# print("Agent poussé avec succès vers Hugging Face!")
|
133 |
+
# except Exception as e:
|
134 |
+
# print(f"Erreur lors du push vers Hugging Face: {e}")
|
135 |
|
136 |
GradioUI(agent).launch()
|
prompts.old
ADDED
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"system_prompt": |-
|
2 |
+
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.
|
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 |
+
|
12 |
+
Here are a few examples using notional tools:
|
13 |
+
---
|
14 |
+
Task: "Generate an image of the oldest person in this document."
|
15 |
+
|
16 |
+
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.
|
17 |
+
Code:
|
18 |
+
```py
|
19 |
+
answer = document_qa(document=document, question="Who is the oldest person mentioned?")
|
20 |
+
print(answer)
|
21 |
+
```<end_code>
|
22 |
+
Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
|
23 |
+
|
24 |
+
Thought: I will now generate an image showcasing the oldest person.
|
25 |
+
Code:
|
26 |
+
```py
|
27 |
+
image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
|
28 |
+
final_answer(image)
|
29 |
+
```<end_code>
|
30 |
+
|
31 |
+
---
|
32 |
+
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
|
33 |
+
|
34 |
+
Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
|
35 |
+
Code:
|
36 |
+
```py
|
37 |
+
result = 5 + 3 + 1294.678
|
38 |
+
final_answer(result)
|
39 |
+
```<end_code>
|
40 |
+
|
41 |
+
---
|
42 |
+
Task:
|
43 |
+
"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
|
44 |
+
You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
|
45 |
+
{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
|
46 |
+
|
47 |
+
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.
|
48 |
+
Code:
|
49 |
+
```py
|
50 |
+
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
|
51 |
+
print(f"The translated question is {translated_question}.")
|
52 |
+
answer = image_qa(image=image, question=translated_question)
|
53 |
+
final_answer(f"The answer is {answer}")
|
54 |
+
```<end_code>
|
55 |
+
|
56 |
+
---
|
57 |
+
Task:
|
58 |
+
In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
|
59 |
+
What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
|
60 |
+
|
61 |
+
Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
|
62 |
+
Code:
|
63 |
+
```py
|
64 |
+
pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
|
65 |
+
print(pages)
|
66 |
+
```<end_code>
|
67 |
+
Observation:
|
68 |
+
No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
|
69 |
+
|
70 |
+
Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
|
71 |
+
Code:
|
72 |
+
```py
|
73 |
+
pages = search(query="1979 interview Stanislaus Ulam")
|
74 |
+
print(pages)
|
75 |
+
```<end_code>
|
76 |
+
Observation:
|
77 |
+
Found 6 pages:
|
78 |
+
[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
|
79 |
+
|
80 |
+
[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
|
81 |
+
|
82 |
+
(truncated)
|
83 |
+
|
84 |
+
Thought: I will read the first 2 pages to know more.
|
85 |
+
Code:
|
86 |
+
```py
|
87 |
+
for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
|
88 |
+
whole_page = visit_webpage(url)
|
89 |
+
print(whole_page)
|
90 |
+
print("\n" + "="*80 + "\n") # Print separator between pages
|
91 |
+
```<end_code>
|
92 |
+
Observation:
|
93 |
+
Manhattan Project Locations:
|
94 |
+
Los Alamos, NM
|
95 |
+
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
|
96 |
+
(truncated)
|
97 |
+
|
98 |
+
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.
|
99 |
+
Code:
|
100 |
+
```py
|
101 |
+
final_answer("diminished")
|
102 |
+
```<end_code>
|
103 |
+
|
104 |
+
---
|
105 |
+
Task: "Which city has the highest population: Guangzhou or Shanghai?"
|
106 |
+
|
107 |
+
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.
|
108 |
+
Code:
|
109 |
+
```py
|
110 |
+
for city in ["Guangzhou", "Shanghai"]:
|
111 |
+
print(f"Population {city}:", search(f"{city} population")
|
112 |
+
```<end_code>
|
113 |
+
Observation:
|
114 |
+
Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
|
115 |
+
Population Shanghai: '26 million (2019)'
|
116 |
+
|
117 |
+
Thought: Now I know that Shanghai has the highest population.
|
118 |
+
Code:
|
119 |
+
```py
|
120 |
+
final_answer("Shanghai")
|
121 |
+
```<end_code>
|
122 |
+
|
123 |
+
---
|
124 |
+
Task: "What is the current age of the pope, raised to the power 0.36?"
|
125 |
+
|
126 |
+
Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
|
127 |
+
Code:
|
128 |
+
```py
|
129 |
+
pope_age_wiki = wiki(query="current pope age")
|
130 |
+
print("Pope age as per wikipedia:", pope_age_wiki)
|
131 |
+
pope_age_search = web_search(query="current pope age")
|
132 |
+
print("Pope age as per google search:", pope_age_search)
|
133 |
+
```<end_code>
|
134 |
+
Observation:
|
135 |
+
Pope age: "The pope Francis is currently 88 years old."
|
136 |
+
|
137 |
+
Thought: I know that the pope is 88 years old. Let's compute the result using python code.
|
138 |
+
Code:
|
139 |
+
```py
|
140 |
+
pope_current_age = 88 ** 0.36
|
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 |
+
{%- else %}
|
160 |
+
{%- endif %}
|
161 |
+
|
162 |
+
Here are the rules you should always follow to solve your task:
|
163 |
+
1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
|
164 |
+
2. Use only variables that you have defined!
|
165 |
+
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?")'.
|
166 |
+
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.
|
167 |
+
5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
|
168 |
+
6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
|
169 |
+
7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
|
170 |
+
8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
|
171 |
+
9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
|
172 |
+
10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
|
173 |
+
|
174 |
+
Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
|
175 |
+
"planning":
|
176 |
+
"initial_facts": |-
|
177 |
+
Below I will present you a task.
|
178 |
+
|
179 |
+
You will now 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 |
+
### 1. Facts given in the task
|
185 |
+
List here the specific facts given in the task that could help you (there might be nothing here).
|
186 |
+
|
187 |
+
### 2. Facts to look up
|
188 |
+
List here any facts that we may need to look up.
|
189 |
+
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.
|
190 |
+
|
191 |
+
### 3. Facts to derive
|
192 |
+
List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
|
193 |
+
|
194 |
+
Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
|
195 |
+
### 1. Facts given in the task
|
196 |
+
### 2. Facts to look up
|
197 |
+
### 3. Facts to derive
|
198 |
+
Do not add anything else.
|
199 |
+
"initial_plan": |-
|
200 |
+
You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
|
201 |
+
|
202 |
+
Now 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 |
+
You can leverage these tools:
|
214 |
+
{%- for tool in tools.values() %}
|
215 |
+
- {{ tool.name }}: {{ tool.description }}
|
216 |
+
Takes inputs: {{tool.inputs}}
|
217 |
+
Returns an output of type: {{tool.output_type}}
|
218 |
+
{%- endfor %}
|
219 |
+
|
220 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
221 |
+
You can also give tasks to team members.
|
222 |
+
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.
|
223 |
+
Given that this team member is a real human, you should be very verbose in your request.
|
224 |
+
Here is a list of the team members that you can call:
|
225 |
+
{%- for agent in managed_agents.values() %}
|
226 |
+
- {{ agent.name }}: {{ agent.description }}
|
227 |
+
{%- endfor %}
|
228 |
+
{%- else %}
|
229 |
+
{%- endif %}
|
230 |
+
|
231 |
+
List of facts that you know:
|
232 |
+
```
|
233 |
+
{{answer_facts}}
|
234 |
+
```
|
235 |
+
|
236 |
+
Now begin! Write your plan below.
|
237 |
+
"update_facts_pre_messages": |-
|
238 |
+
You are a world expert at gathering known and unknown facts based on a conversation.
|
239 |
+
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:
|
240 |
+
### 1. Facts given in the task
|
241 |
+
### 2. Facts that we have learned
|
242 |
+
### 3. Facts still to look up
|
243 |
+
### 4. Facts still to derive
|
244 |
+
Find the task and history below:
|
245 |
+
"update_facts_post_messages": |-
|
246 |
+
Earlier we've built a list of facts.
|
247 |
+
But since in your previous steps you may have learned useful new facts or invalidated some false ones.
|
248 |
+
Please update your list of facts based on the previous history, and provide these headings:
|
249 |
+
### 1. Facts given in the task
|
250 |
+
### 2. Facts that we have learned
|
251 |
+
### 3. Facts still to look up
|
252 |
+
### 4. Facts still to derive
|
253 |
+
|
254 |
+
Now write your new list of facts below.
|
255 |
+
"update_plan_pre_messages": |-
|
256 |
+
You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
|
257 |
+
|
258 |
+
You have been given a task:
|
259 |
+
```
|
260 |
+
{{task}}
|
261 |
+
```
|
262 |
+
|
263 |
+
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.
|
264 |
+
If the previous tries so far have met some success, you can make an updated plan based on these actions.
|
265 |
+
If you are stalled, you can make a completely new plan starting from scratch.
|
266 |
+
"update_plan_post_messages": |-
|
267 |
+
You're still working towards solving this task:
|
268 |
+
```
|
269 |
+
{{task}}
|
270 |
+
```
|
271 |
+
|
272 |
+
You can leverage these tools:
|
273 |
+
{%- for tool in tools.values() %}
|
274 |
+
- {{ tool.name }}: {{ tool.description }}
|
275 |
+
Takes inputs: {{tool.inputs}}
|
276 |
+
Returns an output of type: {{tool.output_type}}
|
277 |
+
{%- endfor %}
|
278 |
+
|
279 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
280 |
+
You can also give tasks to team members.
|
281 |
+
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
|
282 |
+
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.
|
283 |
+
Here is a list of the team members that you can call:
|
284 |
+
{%- for agent in managed_agents.values() %}
|
285 |
+
- {{ agent.name }}: {{ agent.description }}
|
286 |
+
{%- endfor %}
|
287 |
+
{%- else %}
|
288 |
+
{%- endif %}
|
289 |
+
|
290 |
+
Here is the up to date list of facts that you know:
|
291 |
+
```
|
292 |
+
{{facts_update}}
|
293 |
+
```
|
294 |
+
|
295 |
+
Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
|
296 |
+
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
297 |
+
Beware that you have {remaining_steps} steps remaining.
|
298 |
+
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
299 |
+
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
300 |
+
|
301 |
+
Now write your new plan below.
|
302 |
+
"managed_agent":
|
303 |
+
"task": |-
|
304 |
+
You're a helpful agent named '{{name}}'.
|
305 |
+
You have been submitted this task by your manager.
|
306 |
+
---
|
307 |
+
Task:
|
308 |
+
{{task}}
|
309 |
+
---
|
310 |
+
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.
|
311 |
+
|
312 |
+
Your final_answer WILL HAVE to contain these parts:
|
313 |
+
### 1. Task outcome (short version):
|
314 |
+
### 2. Task outcome (extremely detailed version):
|
315 |
+
### 3. Additional context (if relevant):
|
316 |
+
|
317 |
+
Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
|
318 |
+
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.
|
319 |
+
"report": |-
|
320 |
+
Here is the final answer from your managed agent '{{name}}':
|
321 |
+
{{final_answer}}
|
prompts.yaml
CHANGED
@@ -7,140 +7,471 @@
|
|
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 |
|
12 |
Here are a few examples using notional tools:
|
13 |
---
|
14 |
-
Task: "Generate
|
15 |
|
16 |
-
Thought: I will proceed step by step and use the following tools: `
|
17 |
Code:
|
18 |
```py
|
19 |
-
|
20 |
-
print(
|
21 |
```<end_code>
|
22 |
-
Observation:
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
Code:
|
26 |
```py
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
```<end_code>
|
30 |
|
31 |
---
|
32 |
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
|
33 |
|
34 |
-
Thought: I will use python code to compute the result of the operation and then return the final answer using the
|
35 |
Code:
|
36 |
```py
|
37 |
result = 5 + 3 + 1294.678
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
```<end_code>
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
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.
|
48 |
Code:
|
49 |
```py
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
```<end_code>
|
55 |
|
56 |
---
|
57 |
Task:
|
58 |
-
|
59 |
-
What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
|
60 |
|
61 |
-
Thought: I
|
62 |
Code:
|
63 |
```py
|
64 |
-
|
65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
```<end_code>
|
67 |
Observation:
|
68 |
-
|
69 |
-
|
70 |
-
|
|
|
|
|
71 |
Code:
|
72 |
```py
|
73 |
-
|
74 |
-
print(pages)
|
75 |
```<end_code>
|
76 |
-
Observation:
|
77 |
-
Found 6 pages:
|
78 |
-
[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
|
79 |
-
|
80 |
-
[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
|
81 |
|
82 |
-
|
|
|
83 |
|
84 |
-
Thought: I
|
85 |
Code:
|
86 |
```py
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
```<end_code>
|
92 |
Observation:
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
(truncated)
|
97 |
-
|
98 |
-
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.
|
99 |
-
Code:
|
100 |
-
```py
|
101 |
-
final_answer("diminished")
|
102 |
-
```<end_code>
|
103 |
-
|
104 |
-
---
|
105 |
-
Task: "Which city has the highest population: Guangzhou or Shanghai?"
|
106 |
|
107 |
-
Thought:
|
108 |
Code:
|
109 |
```py
|
110 |
-
|
111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
```<end_code>
|
113 |
Observation:
|
114 |
-
|
115 |
-
|
|
|
116 |
|
117 |
-
Thought:
|
118 |
Code:
|
119 |
```py
|
120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
121 |
```<end_code>
|
122 |
|
123 |
---
|
124 |
-
Task: "
|
125 |
|
126 |
-
Thought: I
|
127 |
Code:
|
128 |
```py
|
129 |
-
|
130 |
-
print(
|
131 |
-
pope_age_search = web_search(query="current pope age")
|
132 |
-
print("Pope age as per google search:", pope_age_search)
|
133 |
```<end_code>
|
134 |
Observation:
|
135 |
-
|
136 |
-
|
137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
138 |
Code:
|
139 |
```py
|
140 |
-
|
141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 }}
|
@@ -170,6 +501,9 @@
|
|
170 |
8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
|
171 |
9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
|
172 |
10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
|
|
|
|
|
|
|
173 |
|
174 |
Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
|
175 |
"planning":
|
@@ -318,4 +652,4 @@
|
|
318 |
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.
|
319 |
"report": |-
|
320 |
Here is the final answer from your managed agent '{{name}}':
|
321 |
-
{{final_answer}}
|
|
|
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. Before using `final_answer`, you must validate your Streamlit code using the `validate_final_answer` tool to ensure it's valid. The `final_answer` tool accepts Streamlit code which will be rendered as an interactive web application.
|
11 |
|
12 |
Here are a few examples using notional tools:
|
13 |
---
|
14 |
+
Task: "Generate a data visualization of monthly sales data for 2023."
|
15 |
|
16 |
+
Thought: I will proceed step by step and use the following tools: `get_sales_data` to fetch the monthly sales data for 2023, then `final_answer` to generate a Streamlit application that visualizes this data.
|
17 |
Code:
|
18 |
```py
|
19 |
+
sales_data = get_sales_data(year=2023)
|
20 |
+
print(sales_data)
|
21 |
```<end_code>
|
22 |
+
Observation:
|
23 |
+
```
|
24 |
+
{
|
25 |
+
'Jan': 12500,
|
26 |
+
'Feb': 13200,
|
27 |
+
'Mar': 15400,
|
28 |
+
'Apr': 14800,
|
29 |
+
'May': 16700,
|
30 |
+
'Jun': 18900,
|
31 |
+
'Jul': 17300,
|
32 |
+
'Aug': 16500,
|
33 |
+
'Sep': 19200,
|
34 |
+
'Oct': 21500,
|
35 |
+
'Nov': 23400,
|
36 |
+
'Dec': 26800
|
37 |
+
}
|
38 |
+
```
|
39 |
+
|
40 |
+
Thought: Now I will create a Streamlit application to visualize the sales data. I'll first create the code, then validate it before submitting as the final answer.
|
41 |
Code:
|
42 |
```py
|
43 |
+
streamlit_code = """
|
44 |
+
import streamlit as st
|
45 |
+
import pandas as pd
|
46 |
+
import plotly.express as px
|
47 |
+
|
48 |
+
# Set page title
|
49 |
+
st.title('Monthly Sales Data - 2023')
|
50 |
+
|
51 |
+
# Convert the sales data to a DataFrame
|
52 |
+
data = {
|
53 |
+
'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
|
54 |
+
'Sales': [12500, 13200, 15400, 14800, 16700, 18900, 17300, 16500, 19200, 21500, 23400, 26800]
|
55 |
+
}
|
56 |
+
|
57 |
+
df = pd.DataFrame(data)
|
58 |
+
|
59 |
+
# Display the data
|
60 |
+
st.subheader('Monthly Sales Data')
|
61 |
+
st.dataframe(df)
|
62 |
+
|
63 |
+
# Create visualizations
|
64 |
+
st.subheader('Sales Trend')
|
65 |
+
fig = px.line(df, x='Month', y='Sales', markers=True)
|
66 |
+
st.plotly_chart(fig, use_container_width=True)
|
67 |
+
|
68 |
+
st.subheader('Monthly Sales Distribution')
|
69 |
+
fig2 = px.bar(df, x='Month', y='Sales')
|
70 |
+
st.plotly_chart(fig2, use_container_width=True)
|
71 |
+
|
72 |
+
# Calculate and display statistics
|
73 |
+
st.subheader('Sales Statistics')
|
74 |
+
col1, col2, col3 = st.columns(3)
|
75 |
+
with col1:
|
76 |
+
st.metric("Total Sales", f"${sum(data['Sales']):,}")
|
77 |
+
with col2:
|
78 |
+
st.metric("Average Monthly Sales", f"${sum(data['Sales'])/12:,.2f}")
|
79 |
+
with col3:
|
80 |
+
st.metric("Highest Month", f"{df.loc[df['Sales'].idxmax()]['Month']} (${df['Sales'].max():,})")
|
81 |
+
"""
|
82 |
+
|
83 |
+
# Validate the Streamlit code before submitting
|
84 |
+
validation_result = validate_final_answer(streamlit_code)
|
85 |
+
print(validation_result)
|
86 |
+
```<end_code>
|
87 |
+
Observation:
|
88 |
+
```
|
89 |
+
Answer is valide and can be submitted to final answer.
|
90 |
+
```
|
91 |
+
|
92 |
+
Thought: The validation was successful, so I can now submit the Streamlit code as the final answer.
|
93 |
+
Code:
|
94 |
+
```py
|
95 |
+
final_answer(streamlit_code)
|
96 |
```<end_code>
|
97 |
|
98 |
---
|
99 |
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
|
100 |
|
101 |
+
Thought: I will use python code to compute the result of the operation and then return the final answer using a simple Streamlit application. I'll make sure to validate the code before submitting.
|
102 |
Code:
|
103 |
```py
|
104 |
result = 5 + 3 + 1294.678
|
105 |
+
|
106 |
+
streamlit_code = f"""
|
107 |
+
import streamlit as st
|
108 |
+
|
109 |
+
st.title('Mathematical Operation Result')
|
110 |
+
|
111 |
+
st.write('Operation: 5 + 3 + 1294.678')
|
112 |
+
st.success('Result: {result}')
|
113 |
+
|
114 |
+
# Display the calculation breakdown
|
115 |
+
st.subheader('Calculation Breakdown')
|
116 |
+
st.write('5 + 3 = 8')
|
117 |
+
st.write('8 + 1294.678 = {result}')
|
118 |
+
"""
|
119 |
+
|
120 |
+
# Validate the Streamlit code before submitting
|
121 |
+
validation_result = validate_final_answer(streamlit_code)
|
122 |
+
print(validation_result)
|
123 |
```<end_code>
|
124 |
+
Observation:
|
125 |
+
```
|
126 |
+
Answer is valide and can be submitted to final answer.
|
127 |
+
```
|
128 |
+
|
129 |
+
Thought: The validation was successful, so I can now submit the Streamlit code as the final answer.
|
|
|
|
|
130 |
Code:
|
131 |
```py
|
132 |
+
streamlit_code = f"""
|
133 |
+
import streamlit as st
|
134 |
+
|
135 |
+
st.title('Mathematical Operation Result')
|
136 |
+
|
137 |
+
st.write('Operation: 5 + 3 + 1294.678')
|
138 |
+
st.success('Result: {result}')
|
139 |
+
|
140 |
+
# Display the calculation breakdown
|
141 |
+
st.subheader('Calculation Breakdown')
|
142 |
+
st.write('5 + 3 = 8')
|
143 |
+
st.write('8 + 1294.678 = {result}')
|
144 |
+
"""
|
145 |
+
|
146 |
+
# Validate the Streamlit code before submitting
|
147 |
+
validation_result = validate_final_answer(streamlit_code)
|
148 |
+
print(validation_result)
|
149 |
+
```
|
150 |
+
final_answer(streamlit_code)
|
151 |
```<end_code>
|
152 |
|
153 |
---
|
154 |
Task:
|
155 |
+
"Create an interactive tool to convert between different temperature units (Celsius, Fahrenheit, and Kelvin)."
|
|
|
156 |
|
157 |
+
Thought: I will create an interactive Streamlit application that allows users to convert between temperature units. I'll make sure to validate the code before submitting.
|
158 |
Code:
|
159 |
```py
|
160 |
+
streamlit_code = """
|
161 |
+
import streamlit as st
|
162 |
+
|
163 |
+
st.title('Temperature Converter')
|
164 |
+
|
165 |
+
# Create input fields
|
166 |
+
st.subheader('Enter Temperature Value')
|
167 |
+
temp_value = st.number_input('Temperature', value=0.0)
|
168 |
+
|
169 |
+
# Create unit selection
|
170 |
+
source_unit = st.selectbox('From Unit', ['Celsius', 'Fahrenheit', 'Kelvin'])
|
171 |
+
target_unit = st.selectbox('To Unit', ['Fahrenheit', 'Celsius', 'Kelvin'])
|
172 |
+
|
173 |
+
# Define conversion functions
|
174 |
+
def celsius_to_fahrenheit(c):
|
175 |
+
return (c * 9/5) + 32
|
176 |
+
|
177 |
+
def celsius_to_kelvin(c):
|
178 |
+
return c + 273.15
|
179 |
+
|
180 |
+
def fahrenheit_to_celsius(f):
|
181 |
+
return (f - 32) * 5/9
|
182 |
+
|
183 |
+
def fahrenheit_to_kelvin(f):
|
184 |
+
return (f - 32) * 5/9 + 273.15
|
185 |
+
|
186 |
+
def kelvin_to_celsius(k):
|
187 |
+
return k - 273.15
|
188 |
+
|
189 |
+
def kelvin_to_fahrenheit(k):
|
190 |
+
return (k - 273.15) * 9/5 + 32
|
191 |
+
|
192 |
+
# Create conversion logic
|
193 |
+
result = 0
|
194 |
+
formula = ""
|
195 |
+
|
196 |
+
if st.button('Convert'):
|
197 |
+
if source_unit == target_unit:
|
198 |
+
result = temp_value
|
199 |
+
formula = f"{temp_value} {source_unit} = {result} {target_unit}"
|
200 |
+
elif source_unit == 'Celsius' and target_unit == 'Fahrenheit':
|
201 |
+
result = celsius_to_fahrenheit(temp_value)
|
202 |
+
formula = f"{temp_value}°C × (9/5) + 32 = {result}°F"
|
203 |
+
elif source_unit == 'Celsius' and target_unit == 'Kelvin':
|
204 |
+
result = celsius_to_kelvin(temp_value)
|
205 |
+
formula = f"{temp_value}°C + 273.15 = {result}K"
|
206 |
+
elif source_unit == 'Fahrenheit' and target_unit == 'Celsius':
|
207 |
+
result = fahrenheit_to_celsius(temp_value)
|
208 |
+
formula = f"({temp_value}°F - 32) × 5/9 = {result}°C"
|
209 |
+
elif source_unit == 'Fahrenheit' and target_unit == 'Kelvin':
|
210 |
+
result = fahrenheit_to_kelvin(temp_value)
|
211 |
+
formula = f"({temp_value}°F - 32) × 5/9 + 273.15 = {result}K"
|
212 |
+
elif source_unit == 'Kelvin' and target_unit == 'Celsius':
|
213 |
+
result = kelvin_to_celsius(temp_value)
|
214 |
+
formula = f"{temp_value}K - 273.15 = {result}°C"
|
215 |
+
elif source_unit == 'Kelvin' and target_unit == 'Fahrenheit':
|
216 |
+
result = kelvin_to_fahrenheit(temp_value)
|
217 |
+
formula = f"({temp_value}K - 273.15) × 9/5 + 32 = {result}°F"
|
218 |
+
|
219 |
+
# Display result
|
220 |
+
st.success(f"Result: {result:.2f} {target_unit}")
|
221 |
+
st.info(f"Formula: {formula}")
|
222 |
+
|
223 |
+
# Display information about temperature scales
|
224 |
+
with st.expander("About Temperature Scales"):
|
225 |
+
st.write("**Celsius (°C)**: Water freezes at 0°C and boils at 100°C at standard atmospheric pressure.")
|
226 |
+
st.write("**Fahrenheit (°F)**: Water freezes at 32°F and boils at 212°F at standard atmospheric pressure.")
|
227 |
+
st.write("**Kelvin (K)**: Absolute zero is 0K, which equals -273.15°C or -459.67°F.")
|
228 |
+
"""
|
229 |
+
|
230 |
+
# Validate the Streamlit code before submitting
|
231 |
+
validation_result = validate_final_answer(streamlit_code)
|
232 |
+
print(validation_result)
|
233 |
```<end_code>
|
234 |
Observation:
|
235 |
+
```
|
236 |
+
Answer is valide and can be submitted to final answer.
|
237 |
+
```
|
238 |
+
|
239 |
+
Thought: The validation was successful, so I can now submit the Streamlit code as the final answer.
|
240 |
Code:
|
241 |
```py
|
242 |
+
final_answer(streamlit_code)
|
|
|
243 |
```<end_code>
|
|
|
|
|
|
|
|
|
|
|
244 |
|
245 |
+
---
|
246 |
+
Task: "Create a simple calculator for addition and subtraction."
|
247 |
|
248 |
+
Thought: I'll create a Streamlit application that functions as a simple calculator for addition and subtraction operations.
|
249 |
Code:
|
250 |
```py
|
251 |
+
# First attempt with a syntax error
|
252 |
+
streamlit_code = """
|
253 |
+
import streamlit as st
|
254 |
+
|
255 |
+
st.title('Simple Calculator')
|
256 |
+
|
257 |
+
# Get user inputs
|
258 |
+
num1 = st.number_input('Enter first number', value=0.0)
|
259 |
+
num2 = st.number_input('Enter second number', value=0.0)
|
260 |
+
operation = st.selectbox('Select operation', ['Addition', 'Subtraction'])
|
261 |
+
|
262 |
+
# Calculate result when button is pressed
|
263 |
+
if st.button('Calculate'):
|
264 |
+
if operation == 'Addition':
|
265 |
+
result = num1 + num2
|
266 |
+
st.success(f'Result: {num1} + {num2} = {result}')
|
267 |
+
elif operation == 'Subtraction'
|
268 |
+
result = num1 - num2 # Missing colon after condition
|
269 |
+
st.success(f'Result: {num1} - {num2} = {result}')
|
270 |
+
"""
|
271 |
+
|
272 |
+
# Validate the Streamlit code
|
273 |
+
validation_result = validate_final_answer(streamlit_code)
|
274 |
+
print(validation_result)
|
275 |
```<end_code>
|
276 |
Observation:
|
277 |
+
```
|
278 |
+
Invalid answer : name 'e' is not defined
|
279 |
+
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
280 |
|
281 |
+
Thought: The validation failed because there's a syntax error in my code. I'm missing a colon after the 'elif' condition. Let me fix the code and validate it again.
|
282 |
Code:
|
283 |
```py
|
284 |
+
# Fixed version with correct syntax
|
285 |
+
streamlit_code = """
|
286 |
+
import streamlit as st
|
287 |
+
|
288 |
+
st.title('Simple Calculator')
|
289 |
+
|
290 |
+
# Get user inputs
|
291 |
+
num1 = st.number_input('Enter first number', value=0.0)
|
292 |
+
num2 = st.number_input('Enter second number', value=0.0)
|
293 |
+
operation = st.selectbox('Select operation', ['Addition', 'Subtraction'])
|
294 |
+
|
295 |
+
# Calculate result when button is pressed
|
296 |
+
if st.button('Calculate'):
|
297 |
+
if operation == 'Addition':
|
298 |
+
result = num1 + num2
|
299 |
+
st.success(f'Result: {num1} + {num2} = {result}')
|
300 |
+
elif operation == 'Subtraction': # Added the missing colon
|
301 |
+
result = num1 - num2
|
302 |
+
st.success(f'Result: {num1} - {num2} = {result}')
|
303 |
+
"""
|
304 |
+
|
305 |
+
# Validate the fixed Streamlit code
|
306 |
+
validation_result = validate_final_answer(streamlit_code)
|
307 |
+
print(validation_result)
|
308 |
```<end_code>
|
309 |
Observation:
|
310 |
+
```
|
311 |
+
Answer is valide and can be submitted to final answer.
|
312 |
+
```
|
313 |
|
314 |
+
Thought: The validation is now successful after fixing the syntax error. I can now submit the corrected Streamlit code as the final answer.
|
315 |
Code:
|
316 |
```py
|
317 |
+
import streamlit as st
|
318 |
+
|
319 |
+
st.title('Simple Calculator')
|
320 |
+
|
321 |
+
# Get user inputs
|
322 |
+
num1 = st.number_input('Enter first number', value=0.0)
|
323 |
+
num2 = st.number_input('Enter second number', value=0.0)
|
324 |
+
operation = st.selectbox('Select operation', ['Addition', 'Subtraction'])
|
325 |
+
|
326 |
+
# Calculate result when button is pressed
|
327 |
+
if st.button('Calculate'):
|
328 |
+
if operation == 'Addition':
|
329 |
+
result = num1 + num2
|
330 |
+
st.success(f'Result: {num1} + {num2} = {result}')
|
331 |
+
elif operation == 'Subtraction': # Added the missing colon
|
332 |
+
result = num1 - num2
|
333 |
+
st.success(f'Result: {num1} - {num2} = {result}')
|
334 |
+
"""
|
335 |
+
final_answer(streamlit_code)
|
336 |
```<end_code>
|
337 |
|
338 |
---
|
339 |
+
Task: "Find the population of the three most populous cities in Japan and create a visualization."
|
340 |
|
341 |
+
Thought: I need to find the populations of the most populous cities in Japan and create a visualization. I'll use the search tool for this.
|
342 |
Code:
|
343 |
```py
|
344 |
+
search_results = search(query="most populous cities in Japan population")
|
345 |
+
print(search_results)
|
|
|
|
|
346 |
```<end_code>
|
347 |
Observation:
|
348 |
+
"The most populous cities in Japan are:
|
349 |
+
1. Tokyo: 13.96 million
|
350 |
+
2. Yokohama: 3.76 million
|
351 |
+
3. Osaka: 2.72 million
|
352 |
+
4. Nagoya: 2.33 million
|
353 |
+
5. Sapporo: 1.97 million"
|
354 |
+
|
355 |
+
Thought: Now I have the population data for the most populous cities in Japan. I'll create a Streamlit application to visualize this data.
|
356 |
+
Code:
|
357 |
+
```py
|
358 |
+
streamlit_code = """
|
359 |
+
import streamlit as st
|
360 |
+
import pandas as pd
|
361 |
+
import plotly.express as px
|
362 |
+
import matplotlib.pyplot as plt
|
363 |
+
|
364 |
+
st.title('Most Populous Cities in Japan')
|
365 |
+
|
366 |
+
# Create DataFrame
|
367 |
+
data = {
|
368 |
+
'City': ['Tokyo', 'Yokohama', 'Osaka', 'Nagoya', 'Sapporo'],
|
369 |
+
'Population (millions)': [13.96, 3.76, 2.72, 2.33, 1.97]
|
370 |
+
}
|
371 |
+
df = pd.DataFrame(data)
|
372 |
+
|
373 |
+
# Display data table
|
374 |
+
st.subheader('Population Data')
|
375 |
+
st.dataframe(df)
|
376 |
+
|
377 |
+
# Create bar chart
|
378 |
+
st.subheader('Population Comparison')
|
379 |
+
fig = px.bar(df, x='City', y='Population (millions)',
|
380 |
+
color='Population (millions)',
|
381 |
+
color_continuous_scale='Viridis',
|
382 |
+
text_auto=True)
|
383 |
+
fig.update_traces(texttemplate='%{text:.2f}M', textposition='outside')
|
384 |
+
st.plotly_chart(fig, use_container_width=True)
|
385 |
+
|
386 |
+
# Create pie chart
|
387 |
+
st.subheader('Population Distribution')
|
388 |
+
fig2 = px.pie(df, values='Population (millions)', names='City', hole=0.4)
|
389 |
+
fig2.update_traces(textinfo='percent+label')
|
390 |
+
st.plotly_chart(fig2, use_container_width=True)
|
391 |
+
|
392 |
+
# Show interesting facts
|
393 |
+
st.subheader('Did you know?')
|
394 |
+
st.info('Tokyo is the most populous metropolitan area in the world with almost 14 million people in the city proper.')
|
395 |
+
st.info('The Tokyo metropolitan area (including surrounding prefectures) has over 37 million people.')
|
396 |
+
|
397 |
+
# Add a map
|
398 |
+
st.subheader('Map of Major Japanese Cities')
|
399 |
+
japan_map_data = {
|
400 |
+
'City': ['Tokyo', 'Yokohama', 'Osaka', 'Nagoya', 'Sapporo'],
|
401 |
+
'lat': [35.6762, 35.4437, 34.6937, 35.1815, 43.0618],
|
402 |
+
'lon': [139.6503, 139.6380, 135.5023, 136.9066, 141.3545],
|
403 |
+
'Population (millions)': [13.96, 3.76, 2.72, 2.33, 1.97]
|
404 |
+
}
|
405 |
+
map_df = pd.DataFrame(japan_map_data)
|
406 |
+
st.map(map_df, latitude='lat', longitude='lon', size='Population (millions)')
|
407 |
+
"""
|
408 |
+
|
409 |
+
# Validate the Streamlit code before submitting
|
410 |
+
validation_result = validate_final_answer(streamlit_code)
|
411 |
+
print(validation_result)
|
412 |
+
```<end_code>
|
413 |
+
Observation:
|
414 |
+
```
|
415 |
+
Answer is valide and can be submitted to final answer.
|
416 |
+
```
|
417 |
+
|
418 |
+
Thought: The validation was successful, so I can now submit the Streamlit code as the final answer.
|
419 |
Code:
|
420 |
```py
|
421 |
+
streamlit_code = """
|
422 |
+
import streamlit as st
|
423 |
+
import pandas as pd
|
424 |
+
import plotly.express as px
|
425 |
+
import matplotlib.pyplot as plt
|
426 |
+
|
427 |
+
st.title('Most Populous Cities in Japan')
|
428 |
+
|
429 |
+
# Create DataFrame
|
430 |
+
data = {
|
431 |
+
'City': ['Tokyo', 'Yokohama', 'Osaka', 'Nagoya', 'Sapporo'],
|
432 |
+
'Population (millions)': [13.96, 3.76, 2.72, 2.33, 1.97]
|
433 |
+
}
|
434 |
+
df = pd.DataFrame(data)
|
435 |
+
|
436 |
+
# Display data table
|
437 |
+
st.subheader('Population Data')
|
438 |
+
st.dataframe(df)
|
439 |
+
|
440 |
+
# Create bar chart
|
441 |
+
st.subheader('Population Comparison')
|
442 |
+
fig = px.bar(df, x='City', y='Population (millions)',
|
443 |
+
color='Population (millions)',
|
444 |
+
color_continuous_scale='Viridis',
|
445 |
+
text_auto=True)
|
446 |
+
fig.update_traces(texttemplate='%{text:.2f}M', textposition='outside')
|
447 |
+
st.plotly_chart(fig, use_container_width=True)
|
448 |
+
|
449 |
+
# Create pie chart
|
450 |
+
st.subheader('Population Distribution')
|
451 |
+
fig2 = px.pie(df, values='Population (millions)', names='City', hole=0.4)
|
452 |
+
fig2.update_traces(textinfo='percent+label')
|
453 |
+
st.plotly_chart(fig2, use_container_width=True)
|
454 |
+
|
455 |
+
# Show interesting facts
|
456 |
+
st.subheader('Did you know?')
|
457 |
+
st.info('Tokyo is the most populous metropolitan area in the world with almost 14 million people in the city proper.')
|
458 |
+
st.info('The Tokyo metropolitan area (including surrounding prefectures) has over 37 million people.')
|
459 |
+
|
460 |
+
# Add a map
|
461 |
+
st.subheader('Map of Major Japanese Cities')
|
462 |
+
japan_map_data = {
|
463 |
+
'City': ['Tokyo', 'Yokohama', 'Osaka', 'Nagoya', 'Sapporo'],
|
464 |
+
'lat': [35.6762, 35.4437, 34.6937, 35.1815, 43.0618],
|
465 |
+
'lon': [139.6503, 139.6380, 135.5023, 136.9066, 141.3545],
|
466 |
+
'Population (millions)': [13.96, 3.76, 2.72, 2.33, 1.97]
|
467 |
+
}
|
468 |
+
map_df = pd.DataFrame(japan_map_data)
|
469 |
+
st.map(map_df, latitude='lat', longitude='lon', size='Population (millions)')
|
470 |
+
"""
|
471 |
+
final_answer(streamlit_code)
|
472 |
```<end_code>
|
473 |
|
474 |
+
|
475 |
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:
|
476 |
{%- for tool in tools.values() %}
|
477 |
- {{ tool.name }}: {{ tool.description }}
|
|
|
501 |
8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
|
502 |
9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
|
503 |
10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
|
504 |
+
11. When using the final_answer tool, provide Streamlit code as an argument. This code will be rendered as an interactive web application.
|
505 |
+
12. Always use the validate_final_answer tool before using final_answer to ensure your Streamlit code is valid.
|
506 |
+
13. When writing Streamlit code for the final_answer, make sure to include all necessary imports and provide a complete, standalone application.
|
507 |
|
508 |
Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
|
509 |
"planning":
|
|
|
652 |
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.
|
653 |
"report": |-
|
654 |
Here is the final answer from your managed agent '{{name}}':
|
655 |
+
{{final_answer}}
|
requirements.txt
CHANGED
@@ -6,4 +6,7 @@ pydantic>=2.4.2
|
|
6 |
openai>=1.2.0
|
7 |
gradio>=5.15.0
|
8 |
pytz>=2023.3
|
9 |
-
pyyaml>=6.0
|
|
|
|
|
|
|
|
6 |
openai>=1.2.0
|
7 |
gradio>=5.15.0
|
8 |
pytz>=2023.3
|
9 |
+
pyyaml>=6.0
|
10 |
+
plotly>=5.18.0
|
11 |
+
pandas>=2.0.0
|
12 |
+
numpy>=1.24.0
|
streamlit_app.py
CHANGED
@@ -4,7 +4,9 @@ import sys
|
|
4 |
import yaml
|
5 |
import datetime
|
6 |
import pytz
|
7 |
-
|
|
|
|
|
8 |
|
9 |
# Ajout du répertoire courant au chemin Python pour importer les modules
|
10 |
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
@@ -13,11 +15,26 @@ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
13 |
from smolagents import CodeAgent
|
14 |
from smolagents.models import OpenAIServerModel, HfApiModel
|
15 |
from tools.final_answer import FinalAnswerTool
|
|
|
16 |
from tools.visit_webpage import VisitWebpageTool
|
17 |
from tools.web_search import DuckDuckGoSearchTool
|
18 |
from tools.shell_tool import ShellCommandTool
|
19 |
from tools.create_file_tool import CreateFileTool
|
20 |
from tools.modify_file_tool import ModifyFileTool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
# Configuration de la page Streamlit
|
23 |
st.set_page_config(
|
@@ -39,15 +56,16 @@ def initialize_agent(model_type="openai_server", model_config=None):
|
|
39 |
# Configuration par défaut pour OpenAIServerModel
|
40 |
if model_config is None:
|
41 |
model_config = {
|
42 |
-
"api_base": "
|
43 |
-
"model_id": "
|
44 |
-
"api_key": "
|
45 |
}
|
46 |
|
47 |
model = OpenAIServerModel(
|
48 |
api_base=model_config["api_base"],
|
49 |
model_id=model_config["model_id"],
|
50 |
-
api_key=model_config["api_key"]
|
|
|
51 |
)
|
52 |
|
53 |
elif model_type == "hf_api":
|
@@ -92,27 +110,27 @@ def initialize_agent(model_type="openai_server", model_config=None):
|
|
92 |
st.error("Impossible de charger prompts.yaml. Utilisation des prompts par défaut.")
|
93 |
prompt_templates = None
|
94 |
|
95 |
-
# Initialisation des outils
|
96 |
-
final_answer = FinalAnswerTool()
|
97 |
|
98 |
# Création de l'agent avec les mêmes outils que dans app.py
|
99 |
agent = CodeAgent(
|
100 |
model=model,
|
101 |
tools=[
|
102 |
-
|
|
|
103 |
DuckDuckGoSearchTool(),
|
104 |
VisitWebpageTool(),
|
105 |
ShellCommandTool(),
|
106 |
CreateFileTool(),
|
107 |
ModifyFileTool()
|
108 |
],
|
109 |
-
max_steps=
|
110 |
verbosity_level=1,
|
111 |
grammar=None,
|
112 |
planning_interval=None,
|
113 |
name=None,
|
114 |
description=None,
|
115 |
-
prompt_templates=prompt_templates
|
|
|
116 |
)
|
117 |
|
118 |
return agent
|
@@ -134,14 +152,69 @@ def format_step_message(step, is_final=False):
|
|
134 |
|
135 |
if hasattr(step, "error") and step.error:
|
136 |
# Afficher les erreurs
|
137 |
-
return f"**Erreur :** {step.error}"
|
138 |
|
139 |
# Cas par défaut
|
140 |
return str(step)
|
141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
def process_user_input(agent, user_input):
|
143 |
"""Traite l'entrée utilisateur avec l'agent et renvoie les résultats étape par étape"""
|
144 |
|
|
|
|
|
|
|
|
|
|
|
145 |
# Vérification de la connexion au serveur LLM
|
146 |
try:
|
147 |
# Exécution de l'agent et capture des étapes
|
@@ -179,7 +252,12 @@ def process_user_input(agent, user_input):
|
|
179 |
# Afficher la réponse finale
|
180 |
if final_step:
|
181 |
final_answer = format_step_message(final_step, is_final=True)
|
182 |
-
|
|
|
|
|
|
|
|
|
|
|
183 |
|
184 |
return final_step
|
185 |
except Exception as e:
|
@@ -213,17 +291,17 @@ def main():
|
|
213 |
st.subheader("Configuration OpenAI Server")
|
214 |
model_config["api_base"] = st.text_input(
|
215 |
"URL du serveur",
|
216 |
-
value="
|
217 |
help="Adresse du serveur OpenAI compatible"
|
218 |
)
|
219 |
model_config["model_id"] = st.text_input(
|
220 |
"ID du modèle",
|
221 |
-
value="
|
222 |
help="Identifiant du modèle local"
|
223 |
)
|
224 |
model_config["api_key"] = st.text_input(
|
225 |
"Clé API",
|
226 |
-
value="
|
227 |
type="password",
|
228 |
help="Clé API pour le serveur (dummy pour LMStudio)"
|
229 |
)
|
@@ -321,7 +399,80 @@ def main():
|
|
321 |
# Traiter la demande avec l'agent
|
322 |
with st.chat_message("assistant"):
|
323 |
response = process_user_input(st.session_state.agent, prompt)
|
324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
325 |
if response and hasattr(response, "model_output"):
|
326 |
# Ajouter la réponse à l'historique
|
327 |
st.session_state.messages.append({"role": "assistant", "content": response.model_output})
|
@@ -344,6 +495,7 @@ def main():
|
|
344 |
- Visite de pages web
|
345 |
- Exécution de commandes shell
|
346 |
- Création et modification de fichiers
|
|
|
347 |
|
348 |
### Configuration
|
349 |
Utilisez les options ci-dessus pour configurer le modèle de langage.
|
@@ -353,6 +505,17 @@ def main():
|
|
353 |
- Assurez-vous que toutes les dépendances sont installées via `pip install -r requirements.txt`.
|
354 |
""")
|
355 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
356 |
# Afficher l'heure actuelle dans différents fuseaux horaires
|
357 |
st.subheader("Heure actuelle")
|
358 |
selected_timezone = st.selectbox(
|
|
|
4 |
import yaml
|
5 |
import datetime
|
6 |
import pytz
|
7 |
+
import pandas as pd
|
8 |
+
import numpy as np
|
9 |
+
from typing import List, Dict, Any, Optional, Union, Tuple
|
10 |
|
11 |
# Ajout du répertoire courant au chemin Python pour importer les modules
|
12 |
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
|
15 |
from smolagents import CodeAgent
|
16 |
from smolagents.models import OpenAIServerModel, HfApiModel
|
17 |
from tools.final_answer import FinalAnswerTool
|
18 |
+
from tools.validate_final_answer import ValidateFinalAnswer
|
19 |
from tools.visit_webpage import VisitWebpageTool
|
20 |
from tools.web_search import DuckDuckGoSearchTool
|
21 |
from tools.shell_tool import ShellCommandTool
|
22 |
from tools.create_file_tool import CreateFileTool
|
23 |
from tools.modify_file_tool import ModifyFileTool
|
24 |
+
from phoenix.otel import register
|
25 |
+
from openinference.instrumentation.smolagents import SmolagentsInstrumentor
|
26 |
+
from smolagents.memory import ToolCall
|
27 |
+
# register()
|
28 |
+
# SmolagentsInstrumentor().instrument()
|
29 |
+
|
30 |
+
# Import des fonctions de visualisation
|
31 |
+
from visualizations import (
|
32 |
+
create_line_chart,
|
33 |
+
create_bar_chart,
|
34 |
+
create_scatter_plot,
|
35 |
+
detect_visualization_request,
|
36 |
+
generate_sample_data
|
37 |
+
)
|
38 |
|
39 |
# Configuration de la page Streamlit
|
40 |
st.set_page_config(
|
|
|
56 |
# Configuration par défaut pour OpenAIServerModel
|
57 |
if model_config is None:
|
58 |
model_config = {
|
59 |
+
"api_base": "https://openrouter.ai/api/v1",
|
60 |
+
"model_id": "google/gemini-2.0-pro-exp-02-05:free",
|
61 |
+
"api_key": "nop"
|
62 |
}
|
63 |
|
64 |
model = OpenAIServerModel(
|
65 |
api_base=model_config["api_base"],
|
66 |
model_id=model_config["model_id"],
|
67 |
+
api_key=model_config["api_key"],
|
68 |
+
max_tokens=12000
|
69 |
)
|
70 |
|
71 |
elif model_type == "hf_api":
|
|
|
110 |
st.error("Impossible de charger prompts.yaml. Utilisation des prompts par défaut.")
|
111 |
prompt_templates = None
|
112 |
|
|
|
|
|
113 |
|
114 |
# Création de l'agent avec les mêmes outils que dans app.py
|
115 |
agent = CodeAgent(
|
116 |
model=model,
|
117 |
tools=[
|
118 |
+
FinalAnswerTool(),
|
119 |
+
ValidateFinalAnswer(),
|
120 |
DuckDuckGoSearchTool(),
|
121 |
VisitWebpageTool(),
|
122 |
ShellCommandTool(),
|
123 |
CreateFileTool(),
|
124 |
ModifyFileTool()
|
125 |
],
|
126 |
+
max_steps=20,
|
127 |
verbosity_level=1,
|
128 |
grammar=None,
|
129 |
planning_interval=None,
|
130 |
name=None,
|
131 |
description=None,
|
132 |
+
prompt_templates=prompt_templates,
|
133 |
+
additional_authorized_imports=["pandas", "numpy", "matplotlib", "seaborn", "plotly", "requests", "yaml"]
|
134 |
)
|
135 |
|
136 |
return agent
|
|
|
152 |
|
153 |
if hasattr(step, "error") and step.error:
|
154 |
# Afficher les erreurs
|
155 |
+
return f"**Erreur nooo:** {step.error}"
|
156 |
|
157 |
# Cas par défaut
|
158 |
return str(step)
|
159 |
|
160 |
+
def process_visualization_request(user_input: str) -> Tuple[bool, Optional[st.delta_generator.DeltaGenerator]]:
|
161 |
+
"""
|
162 |
+
Process a visualization request from the user.
|
163 |
+
|
164 |
+
Args:
|
165 |
+
user_input: The user's input message.
|
166 |
+
|
167 |
+
Returns:
|
168 |
+
A tuple containing:
|
169 |
+
- Boolean indicating if a visualization was processed
|
170 |
+
- The Streamlit delta generator if a visualization was created, None otherwise
|
171 |
+
"""
|
172 |
+
# Detect if this is a visualization request
|
173 |
+
viz_info = detect_visualization_request(user_input)
|
174 |
+
|
175 |
+
if not viz_info['is_visualization'] or not viz_info['chart_type']:
|
176 |
+
return False, None
|
177 |
+
|
178 |
+
# Extract information from the request
|
179 |
+
chart_type = viz_info['chart_type']
|
180 |
+
data_description = viz_info['data_description']
|
181 |
+
parameters = viz_info['parameters']
|
182 |
+
|
183 |
+
# Generate sample data based on the description and chart type
|
184 |
+
data = generate_sample_data(data_description, chart_type)
|
185 |
+
|
186 |
+
# Set default parameters if not provided
|
187 |
+
title = parameters.get('title', f"{chart_type.capitalize()} Chart" + (f" of {data_description}" if data_description else ""))
|
188 |
+
x_label = parameters.get('x_label', data.columns[0] if len(data.columns) > 0 else "X-Axis")
|
189 |
+
y_label = parameters.get('y_label', data.columns[1] if len(data.columns) > 1 else "Y-Axis")
|
190 |
+
|
191 |
+
# Create the appropriate chart
|
192 |
+
fig = None
|
193 |
+
if chart_type == 'line':
|
194 |
+
fig = create_line_chart(data, title=title, x_label=x_label, y_label=y_label)
|
195 |
+
elif chart_type == 'bar':
|
196 |
+
fig = create_bar_chart(data, title=title, x_label=x_label, y_label=y_label)
|
197 |
+
elif chart_type == 'scatter':
|
198 |
+
fig = create_scatter_plot(data, title=title, x_label=x_label, y_label=y_label)
|
199 |
+
|
200 |
+
if fig:
|
201 |
+
# Create a container for the visualization
|
202 |
+
viz_container = st.container()
|
203 |
+
with viz_container:
|
204 |
+
st.plotly_chart(fig, use_container_width=True)
|
205 |
+
|
206 |
+
return True, viz_container
|
207 |
+
|
208 |
+
return False, None
|
209 |
+
|
210 |
def process_user_input(agent, user_input):
|
211 |
"""Traite l'entrée utilisateur avec l'agent et renvoie les résultats étape par étape"""
|
212 |
|
213 |
+
# Check if this is a visualization request
|
214 |
+
is_viz_request, viz_container = process_visualization_request(user_input)
|
215 |
+
|
216 |
+
# If it's a visualization request, we'll still run the agent but we've already displayed the chart
|
217 |
+
|
218 |
# Vérification de la connexion au serveur LLM
|
219 |
try:
|
220 |
# Exécution de l'agent et capture des étapes
|
|
|
252 |
# Afficher la réponse finale
|
253 |
if final_step:
|
254 |
final_answer = format_step_message(final_step, is_final=True)
|
255 |
+
|
256 |
+
# If this was a visualization request, add a note about the visualization
|
257 |
+
if is_viz_request:
|
258 |
+
final_answer += "\n\n*Une visualisation a été générée en fonction de votre demande.*"
|
259 |
+
|
260 |
+
return (final_answer, True)
|
261 |
|
262 |
return final_step
|
263 |
except Exception as e:
|
|
|
291 |
st.subheader("Configuration OpenAI Server")
|
292 |
model_config["api_base"] = st.text_input(
|
293 |
"URL du serveur",
|
294 |
+
value="https://openrouter.ai/api/v1",
|
295 |
help="Adresse du serveur OpenAI compatible"
|
296 |
)
|
297 |
model_config["model_id"] = st.text_input(
|
298 |
"ID du modèle",
|
299 |
+
value="google/gemini-2.0-pro-exp-02-05:free",
|
300 |
help="Identifiant du modèle local"
|
301 |
)
|
302 |
model_config["api_key"] = st.text_input(
|
303 |
"Clé API",
|
304 |
+
value="nop",
|
305 |
type="password",
|
306 |
help="Clé API pour le serveur (dummy pour LMStudio)"
|
307 |
)
|
|
|
399 |
# Traiter la demande avec l'agent
|
400 |
with st.chat_message("assistant"):
|
401 |
response = process_user_input(st.session_state.agent, prompt)
|
402 |
+
if response is not None and response[1] == True:
|
403 |
+
with st.container(border = True):
|
404 |
+
def secure_imports(code_str):
|
405 |
+
"""
|
406 |
+
Process Python code to replace import statements with exec-wrapped versions.
|
407 |
+
|
408 |
+
Args:
|
409 |
+
code_str (str): The Python code string to process
|
410 |
+
|
411 |
+
Returns:
|
412 |
+
str: The processed code with import statements wrapped in exec()
|
413 |
+
"""
|
414 |
+
import re
|
415 |
+
|
416 |
+
# Define regex patterns for both import styles
|
417 |
+
# Pattern for 'import module' and 'import module as alias'
|
418 |
+
import_pattern = r'^(\s*)import\s+([^\n]+)'
|
419 |
+
|
420 |
+
# Pattern for 'from module import something'
|
421 |
+
from_import_pattern = r'^(\s*)from\s+([^\n]+)\s+import\s+([^\n]+)'
|
422 |
+
|
423 |
+
lines = code_str.split('\n')
|
424 |
+
result_lines = []
|
425 |
+
|
426 |
+
i = 0
|
427 |
+
while i < len(lines):
|
428 |
+
line = lines[i]
|
429 |
+
|
430 |
+
# Check for multiline imports with parentheses
|
431 |
+
if re.search(r'import\s+\(', line) or re.search(r'from\s+.+\s+import\s+\(', line):
|
432 |
+
# Collect all lines until closing parenthesis
|
433 |
+
start_line = i
|
434 |
+
multiline_import = [line]
|
435 |
+
i += 1
|
436 |
+
|
437 |
+
while i < len(lines) and ')' not in lines[i]:
|
438 |
+
multiline_import.append(lines[i])
|
439 |
+
i += 1
|
440 |
+
|
441 |
+
if i < len(lines): # Add the closing line with parenthesis
|
442 |
+
multiline_import.append(lines[i])
|
443 |
+
|
444 |
+
# Join the multiline import and wrap it with exec
|
445 |
+
indentation = re.match(r'^(\s*)', multiline_import[0]).group(1)
|
446 |
+
multiline_str = '\n'.join(multiline_import)
|
447 |
+
result_lines.append(f'{indentation}exec("""\n{multiline_str}\n""")')
|
448 |
+
|
449 |
+
else:
|
450 |
+
# Handle single line imports
|
451 |
+
import_match = re.match(import_pattern, line)
|
452 |
+
from_import_match = re.match(from_import_pattern, line)
|
453 |
+
|
454 |
+
if import_match:
|
455 |
+
indentation = import_match.group(1)
|
456 |
+
import_stmt = line[len(indentation):] # Remove indentation from statement
|
457 |
+
result_lines.append(f'{indentation}exec("{import_stmt}")')
|
458 |
+
|
459 |
+
elif from_import_match:
|
460 |
+
indentation = from_import_match.group(1)
|
461 |
+
from_import_stmt = line[len(indentation):] # Remove indentation from statement
|
462 |
+
result_lines.append(f'{indentation}exec("{from_import_stmt}")')
|
463 |
+
|
464 |
+
else:
|
465 |
+
# Not an import statement, keep as is
|
466 |
+
result_lines.append(line)
|
467 |
+
|
468 |
+
i += 1
|
469 |
+
|
470 |
+
return '\n'.join(result_lines)
|
471 |
+
|
472 |
+
# Process response[0] to secure import statements
|
473 |
+
# processed_response = secure_imports(response[0])
|
474 |
+
# eval(processed_response)
|
475 |
+
exec(response[0])
|
476 |
if response and hasattr(response, "model_output"):
|
477 |
# Ajouter la réponse à l'historique
|
478 |
st.session_state.messages.append({"role": "assistant", "content": response.model_output})
|
|
|
495 |
- Visite de pages web
|
496 |
- Exécution de commandes shell
|
497 |
- Création et modification de fichiers
|
498 |
+
- Visualisations de données (nouveauté!)
|
499 |
|
500 |
### Configuration
|
501 |
Utilisez les options ci-dessus pour configurer le modèle de langage.
|
|
|
505 |
- Assurez-vous que toutes les dépendances sont installées via `pip install -r requirements.txt`.
|
506 |
""")
|
507 |
|
508 |
+
# Section pour les visualisations
|
509 |
+
st.subheader("Visualisations")
|
510 |
+
st.markdown("""
|
511 |
+
Vous pouvez demander des visualisations en utilisant des phrases comme:
|
512 |
+
- "Montre-moi un graphique en ligne des températures"
|
513 |
+
- "Crée un diagramme à barres des ventes par région"
|
514 |
+
- "Affiche un nuage de points de l'âge vs revenu"
|
515 |
+
|
516 |
+
L'agent détectera automatiquement votre demande et générera une visualisation appropriée.
|
517 |
+
""")
|
518 |
+
|
519 |
# Afficher l'heure actuelle dans différents fuseaux horaires
|
520 |
st.subheader("Heure actuelle")
|
521 |
selected_timezone = st.selectbox(
|
tools/validate_final_answer.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Optional
|
2 |
+
from smolagents.tools import Tool
|
3 |
+
import os
|
4 |
+
|
5 |
+
class ValidateFinalAnswer(Tool):
|
6 |
+
name = "validate_final_answer"
|
7 |
+
description = "Provides a final answer to the given problem."
|
8 |
+
inputs = {'answer': {'type': 'any', 'description': 'The final answer to the problem to be validate'}}
|
9 |
+
output_type = "any"
|
10 |
+
|
11 |
+
def forward(self, answer: Any) -> Any:
|
12 |
+
try:
|
13 |
+
compile(answer, "bogusfile.py", "exec")
|
14 |
+
# os.remove("bogusfile.py")
|
15 |
+
return "Answer is valide and can be submitted to final answer."
|
16 |
+
except Exception as e:
|
17 |
+
return f"Invalid answer : {e}"
|
18 |
+
|
19 |
+
|
20 |
+
def __init__(self, *args, **kwargs):
|
21 |
+
self.is_initialized = False
|
visualizations.py
ADDED
@@ -0,0 +1,423 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import plotly.graph_objects as go
|
2 |
+
import plotly.express as px
|
3 |
+
import pandas as pd
|
4 |
+
import numpy as np
|
5 |
+
import re
|
6 |
+
from typing import Dict, List, Union, Optional, Any
|
7 |
+
|
8 |
+
def create_line_chart(
|
9 |
+
data: Union[pd.DataFrame, Dict[str, List[Union[int, float]]], List[Dict[str, Union[int, float]]]],
|
10 |
+
title: str = "Line Chart",
|
11 |
+
x_label: str = "X-Axis",
|
12 |
+
y_label: str = "Y-Axis",
|
13 |
+
color_sequence: Optional[List[str]] = None,
|
14 |
+
height: int = 400,
|
15 |
+
width: int = 700
|
16 |
+
) -> go.Figure:
|
17 |
+
"""
|
18 |
+
Create a line chart using Plotly.
|
19 |
+
|
20 |
+
Args:
|
21 |
+
data: Data for the chart. Can be a pandas DataFrame, a dictionary with lists as values,
|
22 |
+
or a list of dictionaries.
|
23 |
+
title: Title of the chart.
|
24 |
+
x_label: Label for the x-axis.
|
25 |
+
y_label: Label for the y-axis.
|
26 |
+
color_sequence: Optional list of colors for the lines.
|
27 |
+
height: Height of the chart in pixels.
|
28 |
+
width: Width of the chart in pixels.
|
29 |
+
|
30 |
+
Returns:
|
31 |
+
A Plotly Figure object.
|
32 |
+
"""
|
33 |
+
fig = go.Figure()
|
34 |
+
|
35 |
+
# Convert data to pandas DataFrame if it's not already
|
36 |
+
if isinstance(data, dict):
|
37 |
+
df = pd.DataFrame(data)
|
38 |
+
elif isinstance(data, list) and all(isinstance(item, dict) for item in data):
|
39 |
+
df = pd.DataFrame(data)
|
40 |
+
elif isinstance(data, pd.DataFrame):
|
41 |
+
df = data
|
42 |
+
else:
|
43 |
+
raise ValueError("Data must be a pandas DataFrame, a dictionary with lists as values, or a list of dictionaries.")
|
44 |
+
|
45 |
+
# If the DataFrame has only two columns, use them as x and y
|
46 |
+
if len(df.columns) == 2:
|
47 |
+
x_col = df.columns[0]
|
48 |
+
y_col = df.columns[1]
|
49 |
+
fig.add_trace(go.Scatter(x=df[x_col], y=df[y_col], mode='lines+markers', name=y_col))
|
50 |
+
else:
|
51 |
+
# Assume first column is x and the rest are y values
|
52 |
+
x_col = df.columns[0]
|
53 |
+
for i, col in enumerate(df.columns[1:]):
|
54 |
+
color = color_sequence[i % len(color_sequence)] if color_sequence else None
|
55 |
+
fig.add_trace(go.Scatter(
|
56 |
+
x=df[x_col],
|
57 |
+
y=df[col],
|
58 |
+
mode='lines+markers',
|
59 |
+
name=col,
|
60 |
+
line=dict(color=color) if color else None
|
61 |
+
))
|
62 |
+
|
63 |
+
# Update layout
|
64 |
+
fig.update_layout(
|
65 |
+
title=title,
|
66 |
+
xaxis_title=x_label,
|
67 |
+
yaxis_title=y_label,
|
68 |
+
height=height,
|
69 |
+
width=width,
|
70 |
+
template="plotly_white",
|
71 |
+
hovermode="x unified"
|
72 |
+
)
|
73 |
+
|
74 |
+
return fig
|
75 |
+
|
76 |
+
def create_bar_chart(
|
77 |
+
data: Union[pd.DataFrame, Dict[str, List[Union[int, float]]], List[Dict[str, Union[int, float]]]],
|
78 |
+
title: str = "Bar Chart",
|
79 |
+
x_label: str = "X-Axis",
|
80 |
+
y_label: str = "Y-Axis",
|
81 |
+
color_sequence: Optional[List[str]] = None,
|
82 |
+
orientation: str = 'v', # 'v' for vertical, 'h' for horizontal
|
83 |
+
height: int = 400,
|
84 |
+
width: int = 700
|
85 |
+
) -> go.Figure:
|
86 |
+
"""
|
87 |
+
Create a bar chart using Plotly.
|
88 |
+
|
89 |
+
Args:
|
90 |
+
data: Data for the chart. Can be a pandas DataFrame, a dictionary with lists as values,
|
91 |
+
or a list of dictionaries.
|
92 |
+
title: Title of the chart.
|
93 |
+
x_label: Label for the x-axis.
|
94 |
+
y_label: Label for the y-axis.
|
95 |
+
color_sequence: Optional list of colors for the bars.
|
96 |
+
orientation: 'v' for vertical bars, 'h' for horizontal bars.
|
97 |
+
height: Height of the chart in pixels.
|
98 |
+
width: Width of the chart in pixels.
|
99 |
+
|
100 |
+
Returns:
|
101 |
+
A Plotly Figure object.
|
102 |
+
"""
|
103 |
+
# Convert data to pandas DataFrame if it's not already
|
104 |
+
if isinstance(data, dict):
|
105 |
+
df = pd.DataFrame(data)
|
106 |
+
elif isinstance(data, list) and all(isinstance(item, dict) for item in data):
|
107 |
+
df = pd.DataFrame(data)
|
108 |
+
elif isinstance(data, pd.DataFrame):
|
109 |
+
df = data
|
110 |
+
else:
|
111 |
+
raise ValueError("Data must be a pandas DataFrame, a dictionary with lists as values, or a list of dictionaries.")
|
112 |
+
|
113 |
+
# Create the bar chart
|
114 |
+
if orientation == 'v':
|
115 |
+
# If the DataFrame has only two columns, use them as x and y
|
116 |
+
if len(df.columns) == 2:
|
117 |
+
x_col = df.columns[0]
|
118 |
+
y_col = df.columns[1]
|
119 |
+
fig = px.bar(df, x=x_col, y=y_col, title=title, color_discrete_sequence=color_sequence)
|
120 |
+
else:
|
121 |
+
# For multiple columns, create a grouped bar chart
|
122 |
+
fig = go.Figure()
|
123 |
+
x_col = df.columns[0]
|
124 |
+
for i, col in enumerate(df.columns[1:]):
|
125 |
+
color = color_sequence[i % len(color_sequence)] if color_sequence else None
|
126 |
+
fig.add_trace(go.Bar(
|
127 |
+
x=df[x_col],
|
128 |
+
y=df[col],
|
129 |
+
name=col,
|
130 |
+
marker_color=color
|
131 |
+
))
|
132 |
+
else: # horizontal
|
133 |
+
# If the DataFrame has only two columns, use them as y and x
|
134 |
+
if len(df.columns) == 2:
|
135 |
+
y_col = df.columns[0]
|
136 |
+
x_col = df.columns[1]
|
137 |
+
fig = px.bar(df, y=y_col, x=x_col, title=title, orientation='h', color_discrete_sequence=color_sequence)
|
138 |
+
else:
|
139 |
+
# For multiple columns, create a grouped bar chart
|
140 |
+
fig = go.Figure()
|
141 |
+
y_col = df.columns[0]
|
142 |
+
for i, col in enumerate(df.columns[1:]):
|
143 |
+
color = color_sequence[i % len(color_sequence)] if color_sequence else None
|
144 |
+
fig.add_trace(go.Bar(
|
145 |
+
y=df[y_col],
|
146 |
+
x=df[col],
|
147 |
+
name=col,
|
148 |
+
marker_color=color,
|
149 |
+
orientation='h'
|
150 |
+
))
|
151 |
+
|
152 |
+
# Update layout
|
153 |
+
fig.update_layout(
|
154 |
+
title=title,
|
155 |
+
xaxis_title=x_label,
|
156 |
+
yaxis_title=y_label,
|
157 |
+
height=height,
|
158 |
+
width=width,
|
159 |
+
template="plotly_white",
|
160 |
+
barmode='group'
|
161 |
+
)
|
162 |
+
|
163 |
+
return fig
|
164 |
+
|
165 |
+
def create_scatter_plot(
|
166 |
+
data: Union[pd.DataFrame, Dict[str, List[Union[int, float]]], List[Dict[str, Union[int, float]]]],
|
167 |
+
title: str = "Scatter Plot",
|
168 |
+
x_label: str = "X-Axis",
|
169 |
+
y_label: str = "Y-Axis",
|
170 |
+
color_column: Optional[str] = None,
|
171 |
+
size_column: Optional[str] = None,
|
172 |
+
hover_data: Optional[List[str]] = None,
|
173 |
+
height: int = 400,
|
174 |
+
width: int = 700
|
175 |
+
) -> go.Figure:
|
176 |
+
"""
|
177 |
+
Create a scatter plot using Plotly.
|
178 |
+
|
179 |
+
Args:
|
180 |
+
data: Data for the chart. Can be a pandas DataFrame, a dictionary with lists as values,
|
181 |
+
or a list of dictionaries.
|
182 |
+
title: Title of the chart.
|
183 |
+
x_label: Label for the x-axis.
|
184 |
+
y_label: Label for the y-axis.
|
185 |
+
color_column: Optional column name to use for coloring points.
|
186 |
+
size_column: Optional column name to use for sizing points.
|
187 |
+
hover_data: Optional list of column names to include in hover information.
|
188 |
+
height: Height of the chart in pixels.
|
189 |
+
width: Width of the chart in pixels.
|
190 |
+
|
191 |
+
Returns:
|
192 |
+
A Plotly Figure object.
|
193 |
+
"""
|
194 |
+
# Convert data to pandas DataFrame if it's not already
|
195 |
+
if isinstance(data, dict):
|
196 |
+
df = pd.DataFrame(data)
|
197 |
+
elif isinstance(data, list) and all(isinstance(item, dict) for item in data):
|
198 |
+
df = pd.DataFrame(data)
|
199 |
+
elif isinstance(data, pd.DataFrame):
|
200 |
+
df = data
|
201 |
+
else:
|
202 |
+
raise ValueError("Data must be a pandas DataFrame, a dictionary with lists as values, or a list of dictionaries.")
|
203 |
+
|
204 |
+
# If the DataFrame has only two columns, use them as x and y
|
205 |
+
if len(df.columns) == 2:
|
206 |
+
x_col = df.columns[0]
|
207 |
+
y_col = df.columns[1]
|
208 |
+
fig = px.scatter(df, x=x_col, y=y_col, title=title)
|
209 |
+
else:
|
210 |
+
# Assume first two columns are x and y, and use additional columns for color, size, etc.
|
211 |
+
x_col = df.columns[0]
|
212 |
+
y_col = df.columns[1]
|
213 |
+
|
214 |
+
# Create the scatter plot
|
215 |
+
fig = px.scatter(
|
216 |
+
df,
|
217 |
+
x=x_col,
|
218 |
+
y=y_col,
|
219 |
+
color=color_column if color_column and color_column in df.columns else None,
|
220 |
+
size=size_column if size_column and size_column in df.columns else None,
|
221 |
+
hover_data=hover_data if hover_data else None,
|
222 |
+
title=title
|
223 |
+
)
|
224 |
+
|
225 |
+
# Update layout
|
226 |
+
fig.update_layout(
|
227 |
+
title=title,
|
228 |
+
xaxis_title=x_label,
|
229 |
+
yaxis_title=y_label,
|
230 |
+
height=height,
|
231 |
+
width=width,
|
232 |
+
template="plotly_white"
|
233 |
+
)
|
234 |
+
|
235 |
+
return fig
|
236 |
+
|
237 |
+
def detect_visualization_request(user_input: str) -> Dict[str, Any]:
|
238 |
+
"""
|
239 |
+
Detect if the user is requesting a visualization and extract relevant information.
|
240 |
+
|
241 |
+
Args:
|
242 |
+
user_input: The user's input message.
|
243 |
+
|
244 |
+
Returns:
|
245 |
+
A dictionary containing:
|
246 |
+
- 'is_visualization': Boolean indicating if a visualization is requested.
|
247 |
+
- 'chart_type': The type of chart requested ('line', 'bar', 'scatter', or None).
|
248 |
+
- 'data_description': Description of the data to visualize.
|
249 |
+
- 'parameters': Additional parameters extracted from the request.
|
250 |
+
"""
|
251 |
+
# Convert to lowercase for case-insensitive matching
|
252 |
+
user_input_lower = user_input.lower()
|
253 |
+
|
254 |
+
# Check for visualization keywords
|
255 |
+
viz_keywords = ['plot', 'chart', 'graph', 'visualize', 'visualisation', 'visualization', 'display']
|
256 |
+
is_visualization = any(keyword in user_input_lower for keyword in viz_keywords)
|
257 |
+
|
258 |
+
if not is_visualization:
|
259 |
+
return {
|
260 |
+
'is_visualization': False,
|
261 |
+
'chart_type': None,
|
262 |
+
'data_description': None,
|
263 |
+
'parameters': {}
|
264 |
+
}
|
265 |
+
|
266 |
+
# Detect chart type
|
267 |
+
chart_type = None
|
268 |
+
if any(term in user_input_lower for term in ['line chart', 'line graph', 'line plot']):
|
269 |
+
chart_type = 'line'
|
270 |
+
elif any(term in user_input_lower for term in ['bar chart', 'bar graph', 'histogram']):
|
271 |
+
chart_type = 'bar'
|
272 |
+
elif any(term in user_input_lower for term in ['scatter plot', 'scatter chart', 'scatter graph']):
|
273 |
+
chart_type = 'scatter'
|
274 |
+
|
275 |
+
# Extract data description
|
276 |
+
data_description = None
|
277 |
+
data_patterns = [
|
278 |
+
r'(?:of|for|using|with)\s+([^.?!]+?)(?:\s+(?:by|over|across|versus|vs\.?|against))',
|
279 |
+
r'(?:of|for|using|with)\s+([^.?!]+?)(?:\s+data)',
|
280 |
+
r'(?:of|for|using|with)\s+([^.?!]+?)(?:\s+(?:from|in))'
|
281 |
+
]
|
282 |
+
|
283 |
+
for pattern in data_patterns:
|
284 |
+
match = re.search(pattern, user_input_lower)
|
285 |
+
if match:
|
286 |
+
data_description = match.group(1).strip()
|
287 |
+
break
|
288 |
+
|
289 |
+
# If no match found with specific patterns, try a more general approach
|
290 |
+
if not data_description:
|
291 |
+
# Look for text between the chart type and the end of the sentence
|
292 |
+
chart_type_terms = ['line chart', 'bar chart', 'scatter plot', 'chart', 'graph', 'plot']
|
293 |
+
for term in chart_type_terms:
|
294 |
+
if term in user_input_lower:
|
295 |
+
parts = user_input_lower.split(term, 1)
|
296 |
+
if len(parts) > 1:
|
297 |
+
# Extract text after the chart type until the end of the sentence
|
298 |
+
after_chart_type = parts[1].strip()
|
299 |
+
end_sentence = re.search(r'^[^.!?]*', after_chart_type)
|
300 |
+
if end_sentence:
|
301 |
+
data_description = end_sentence.group(0).strip()
|
302 |
+
# Remove common prepositions at the beginning
|
303 |
+
data_description = re.sub(r'^(?:of|for|using|with)\s+', '', data_description)
|
304 |
+
break
|
305 |
+
|
306 |
+
# Extract additional parameters
|
307 |
+
parameters = {}
|
308 |
+
|
309 |
+
# Title
|
310 |
+
title_match = re.search(r'title[d:]?\s+["\']?([^"\'.?!]+)["\']?', user_input_lower)
|
311 |
+
if title_match:
|
312 |
+
parameters['title'] = title_match.group(1).strip()
|
313 |
+
|
314 |
+
# X-axis label
|
315 |
+
x_label_match = re.search(r'x[-\s]?(?:axis|label)[:]?\s+["\']?([^"\'.?!]+)["\']?', user_input_lower)
|
316 |
+
if x_label_match:
|
317 |
+
parameters['x_label'] = x_label_match.group(1).strip()
|
318 |
+
|
319 |
+
# Y-axis label
|
320 |
+
y_label_match = re.search(r'y[-\s]?(?:axis|label)[:]?\s+["\']?([^"\'.?!]+)["\']?', user_input_lower)
|
321 |
+
if y_label_match:
|
322 |
+
parameters['y_label'] = y_label_match.group(1).strip()
|
323 |
+
|
324 |
+
return {
|
325 |
+
'is_visualization': is_visualization,
|
326 |
+
'chart_type': chart_type,
|
327 |
+
'data_description': data_description,
|
328 |
+
'parameters': parameters
|
329 |
+
}
|
330 |
+
|
331 |
+
def generate_sample_data(data_description: str, chart_type: str) -> pd.DataFrame:
|
332 |
+
"""
|
333 |
+
Generate sample data based on the description and chart type.
|
334 |
+
This is a fallback when no actual data is available.
|
335 |
+
|
336 |
+
Args:
|
337 |
+
data_description: Description of the data to generate.
|
338 |
+
chart_type: Type of chart ('line', 'bar', 'scatter').
|
339 |
+
|
340 |
+
Returns:
|
341 |
+
A pandas DataFrame with sample data.
|
342 |
+
"""
|
343 |
+
np.random.seed(42) # For reproducibility
|
344 |
+
|
345 |
+
# Default data
|
346 |
+
if chart_type == 'line':
|
347 |
+
# Generate time series data
|
348 |
+
dates = pd.date_range(start='2023-01-01', periods=30, freq='D')
|
349 |
+
values = np.cumsum(np.random.randn(30)) + 10
|
350 |
+
df = pd.DataFrame({'Date': dates, 'Value': values})
|
351 |
+
|
352 |
+
# Try to customize based on description
|
353 |
+
if data_description:
|
354 |
+
if 'temperature' in data_description or 'weather' in data_description:
|
355 |
+
df.columns = ['Date', 'Temperature (°C)']
|
356 |
+
df['Temperature (°C)'] = np.random.normal(20, 5, 30)
|
357 |
+
elif 'stock' in data_description or 'price' in data_description:
|
358 |
+
df.columns = ['Date', 'Price ($)']
|
359 |
+
df['Price ($)'] = 100 + np.cumsum(np.random.normal(0, 2, 30))
|
360 |
+
elif 'sales' in data_description or 'revenue' in data_description:
|
361 |
+
df.columns = ['Date', 'Sales ($)']
|
362 |
+
df['Sales ($)'] = 1000 + np.cumsum(np.random.normal(0, 100, 30))
|
363 |
+
else:
|
364 |
+
df.columns = ['Date', data_description.capitalize() if data_description else 'Value']
|
365 |
+
|
366 |
+
elif chart_type == 'bar':
|
367 |
+
# Generate categorical data
|
368 |
+
categories = ['A', 'B', 'C', 'D', 'E']
|
369 |
+
values = np.random.randint(10, 100, size=len(categories))
|
370 |
+
df = pd.DataFrame({'Category': categories, 'Value': values})
|
371 |
+
|
372 |
+
# Try to customize based on description
|
373 |
+
if data_description:
|
374 |
+
if 'sales by region' in data_description or 'regional' in data_description:
|
375 |
+
df['Category'] = ['North', 'South', 'East', 'West', 'Central']
|
376 |
+
df.columns = ['Region', 'Sales ($)']
|
377 |
+
elif 'product' in data_description:
|
378 |
+
df['Category'] = ['Product A', 'Product B', 'Product C', 'Product D', 'Product E']
|
379 |
+
df.columns = ['Product', 'Units Sold']
|
380 |
+
elif 'age' in data_description or 'demographic' in data_description:
|
381 |
+
df['Category'] = ['0-18', '19-35', '36-50', '51-65', '65+']
|
382 |
+
df.columns = ['Age Group', 'Count']
|
383 |
+
else:
|
384 |
+
df.columns = ['Category', data_description.capitalize() if data_description else 'Value']
|
385 |
+
|
386 |
+
elif chart_type == 'scatter':
|
387 |
+
# Generate x-y data
|
388 |
+
x = np.random.normal(0, 1, 50)
|
389 |
+
y = x + np.random.normal(0, 0.5, 50)
|
390 |
+
df = pd.DataFrame({'X': x, 'Y': y})
|
391 |
+
|
392 |
+
# Try to customize based on description
|
393 |
+
if data_description:
|
394 |
+
if 'height' in data_description and 'weight' in data_description:
|
395 |
+
df['X'] = np.random.normal(170, 10, 50) # Heights in cm
|
396 |
+
df['Y'] = df['X'] * 0.5 + np.random.normal(0, 5, 50) # Weights in kg
|
397 |
+
df.columns = ['Height (cm)', 'Weight (kg)']
|
398 |
+
elif 'age' in data_description and ('income' in data_description or 'salary' in data_description):
|
399 |
+
df['X'] = np.random.normal(40, 10, 50) # Ages
|
400 |
+
df['Y'] = df['X'] * 1000 + 20000 + np.random.normal(0, 5000, 50) # Incomes
|
401 |
+
df.columns = ['Age', 'Income ($)']
|
402 |
+
elif 'study' in data_description or 'exam' in data_description:
|
403 |
+
df['X'] = np.random.normal(5, 2, 50) # Study hours
|
404 |
+
df['Y'] = df['X'] * 10 + 50 + np.random.normal(0, 5, 50) # Exam scores
|
405 |
+
df.columns = ['Study Hours', 'Exam Score']
|
406 |
+
else:
|
407 |
+
x_label = 'X'
|
408 |
+
y_label = 'Y'
|
409 |
+
if ' vs ' in data_description:
|
410 |
+
parts = data_description.split(' vs ')
|
411 |
+
if len(parts) == 2:
|
412 |
+
x_label = parts[0].strip().capitalize()
|
413 |
+
y_label = parts[1].strip().capitalize()
|
414 |
+
df.columns = [x_label, y_label]
|
415 |
+
|
416 |
+
else:
|
417 |
+
# Default fallback
|
418 |
+
df = pd.DataFrame({
|
419 |
+
'X': range(1, 11),
|
420 |
+
'Y': np.random.randint(1, 100, 10)
|
421 |
+
})
|
422 |
+
|
423 |
+
return df
|