raffaeleterribile commited on
Commit
f7b9b5a
·
verified ·
1 Parent(s): ae05590

Altra versione dell'agente

Browse files
Files changed (4) hide show
  1. app.py +34 -22
  2. prompts.yaml +12 -125
  3. requirements.txt +1 -1
  4. test.py +33 -0
app.py CHANGED
@@ -43,7 +43,7 @@ class FirstAgent:
43
  def __init__(self):
44
  """ Initializes the FirstAgent with a TransformersModel and a CodeAgent. """
45
  # microsoft/Phi-4-reasoning-plus, microsoft/Phi-4-reasoning, microsoft/Phi-4-mini-reasoning, microsoft/Phi-4-mini-instruct, microsoft/Phi-4-multimodal-instruct, "Qwen/Qwen2.5-Coder-32B-Instruct", "HuggingFaceTB/SmolLM2-1.7B-Instruct"
46
- model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
47
  model = TransformersModel(model_id=model_id, trust_remote_code=True, max_new_tokens=4096)
48
 
49
  # Inizializza l'agente
@@ -53,36 +53,48 @@ class FirstAgent:
53
  prompt_templates = PromptTemplates(**prompts)
54
 
55
  # prompt_templates = EMPTY_PROMPT_TEMPLATES
56
- # prompt_templates["system_prompt"] = """You are an intelligent agent that answers questions and uses tools to help users.
57
- # Think step by step and use tools when needed.
58
- # If you need to search the web, use the WebSearchTool.
59
- # If you need to visit a webpage, use the VisitWebpageTool.
60
- # If you need to run Python code, use the PythonInterpreterTool.
61
- # If you need to generate code to extract information, generate the code and use the PythonInterpreterTool to execute the code and extract the informations.
62
- # If you find information in Wikipedia, use the WikipediaSearchTool.
63
- # Verify your final answer and the format of the final answer before returning it.
64
- # When you have found the definitive answer, return it by calling final_answer(answer) within a Python code block.
65
- # If you don't know the answer, say 'I don't know'."""
66
-
67
- # prompt_templates = PromptTemplates(
68
- # system_prompt="You are an intelligent agent that helps users solve complex tasks using tools.",
69
- # planning="Determine the logical steps to solve the user's problem.",
70
- # managed_agent="Execute each planned step using the available tools.",
71
- # final_answer="When you have completed all steps, return the final answer using final_answer()."
72
- # )
73
-
 
 
 
 
 
 
 
74
 
75
  self.agent = CodeAgent(
76
  model=model,
77
- prompt_templates=prompt_templates,
78
  stream_outputs=True, # Enable streaming outputs
79
- additional_authorized_imports=['requests', 'bs4'],
80
  # add_base_tools=True, # Add base tools like UserInputTool
81
  # use_structured_outputs_internally=True, # Use structured outputs internally
82
  tools=[
83
  WebSearchTool(),
84
  PythonInterpreterTool(),
85
- WikipediaSearchTool(),
 
 
 
 
 
86
  VisitWebpageTool(),
87
  invert_sentence_tool, # Custom tool to invert sentences
88
  FinalAnswerTool() # Final answer tool to extract the final answer
 
43
  def __init__(self):
44
  """ Initializes the FirstAgent with a TransformersModel and a CodeAgent. """
45
  # microsoft/Phi-4-reasoning-plus, microsoft/Phi-4-reasoning, microsoft/Phi-4-mini-reasoning, microsoft/Phi-4-mini-instruct, microsoft/Phi-4-multimodal-instruct, "Qwen/Qwen2.5-Coder-32B-Instruct", "HuggingFaceTB/SmolLM2-1.7B-Instruct"
46
+ model_id = "HuggingFaceTB/SmolLM2-1.7B-Instruct"
47
  model = TransformersModel(model_id=model_id, trust_remote_code=True, max_new_tokens=4096)
48
 
49
  # Inizializza l'agente
 
53
  prompt_templates = PromptTemplates(**prompts)
54
 
55
  # prompt_templates = EMPTY_PROMPT_TEMPLATES
56
+ prompt_templates["system_prompt"] = """You are an intelligent agent that answers questions and uses tools to help users.
57
+ Think step by step and use tools when needed.
58
+ If you need information in Wikipedia, try to use the WikipediaSearchTool. If you cannot find a page with this tool, try to use wikipediaapi directly to get the page and extract content.
59
+ If you need to search the web, use the WebSearchTool.
60
+ If you need to visit a webpage, use the VisitWebpageTool.
61
+ If you need to run Python code, use the PythonInterpreterTool.
62
+ If you need to generate code to extract information, generate the code and use the PythonInterpreterTool to execute the code and extract the informations.
63
+ Verify your final answer and the format of the final answer before returning it.
64
+ 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.
65
+ Then in the '<code>' sequence, you should write the code in simple Python. The code sequence must end with '</code>' sequence.
66
+ During each intermediate step, you can use 'print()' to save whatever important information you will then need.
67
+ These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
68
+ In the end you have to return a final answer using the `final_answer` tool, like this: <code>final_answer(answer)</code>.
69
+ Here are the rules you should always follow to solve your task:
70
+ 1. Always provide a 'Thought:' sequence, and a '<code>' sequence ending with '</code>', else you will fail.
71
+ 2. Use only variables that you have defined!
72
+ 3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wikipedia_search({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wikipedia_search(query="What is the place where James Bond lives?")'.
73
+ 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 wikipedia_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.
74
+ 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
75
+ 6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
76
+ 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
77
+ 8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
78
+ 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
79
+ 10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
80
+ If you don't know the answer, say 'I don't know'."""
81
 
82
  self.agent = CodeAgent(
83
  model=model,
84
+ # prompt_templates=prompt_templates,
85
  stream_outputs=True, # Enable streaming outputs
86
+ additional_authorized_imports=['bs4', 'collections', 'datetime', 'itertools', 'math', 'queue', 'random', 're', 'requests', 'stat', 'statistics', 'time', 'unicodedata', 'wikipediaapi'],
87
  # add_base_tools=True, # Add base tools like UserInputTool
88
  # use_structured_outputs_internally=True, # Use structured outputs internally
89
  tools=[
90
  WebSearchTool(),
91
  PythonInterpreterTool(),
92
+ # WikipediaSearchTool(
93
+ # user_agent="FinalAssignmentAgent ([email protected])",
94
+ # language="en",
95
+ # content_type="text", # "summary" or "text"
96
+ # extract_format="WIKI", # "WIKI" or "HTML"
97
+ # ),
98
  VisitWebpageTool(),
99
  invert_sentence_tool, # Custom tool to invert sentences
100
  FinalAnswerTool() # Final answer tool to extract the final answer
prompts.yaml CHANGED
@@ -1,135 +1,21 @@
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 '</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
- answer = document_qa(document=document, question="Who is the oldest person mentioned?")
19
- print(answer)
20
- </code>
21
- Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
22
-
23
- Thought: I will now generate an image showcasing the oldest person.
24
- <code>
25
- image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
26
- final_answer(image)
27
- </code>
28
-
29
- ---
30
- Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
31
-
32
- Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
33
- <code>
34
- result = 5 + 3 + 1294.678
35
- final_answer(result)
36
- </code>
37
-
38
- ---
39
- Task:
40
- "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
41
- You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
42
- {'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
43
-
44
- 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.
45
- <code>
46
- translated_question = translator(question=question, src_lang="French", tgt_lang="English")
47
- print(f"The translated question is {translated_question}.")
48
- answer = image_qa(image=image, question=translated_question)
49
- final_answer(f"The answer is {answer}")
50
- </code>
51
-
52
- ---
53
- Task:
54
- In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
55
- What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
56
-
57
- Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
58
- <code>
59
- pages = web_search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
60
- print(pages)
61
- </code>
62
- Observation:
63
- No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
64
-
65
- Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
66
- <code>
67
- pages = web_search(query="1979 interview Stanislaus Ulam")
68
- print(pages)
69
- </code>
70
- Observation:
71
- Found 6 pages:
72
- [Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
73
-
74
- [Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
75
-
76
- (truncated)
77
-
78
- Thought: I will read the first 2 pages to know more.
79
- <code>
80
- for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
81
- whole_page = visit_webpage(url)
82
- print(whole_page)
83
- print("\n" + "="*80 + "\n") # Print separator between pages
84
- </code>
85
- Observation:
86
- Manhattan Project Locations:
87
- Los Alamos, NM
88
- 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
89
- (truncated)
90
-
91
- 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.
92
- <code>
93
- final_answer("diminished")
94
- </code>
95
-
96
- ---
97
- Task: "Which city has the highest population: Guangzhou or Shanghai?"
98
-
99
- Thought: I need to get the populations for both cities and compare them: I will use the tool `web_search` to get the population of both cities.
100
- <code>
101
- for city in ["Guangzhou", "Shanghai"]:
102
- print(f"Population {city}:", web_search(f"{city} population")
103
- </code>
104
- Observation:
105
- Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
106
- Population Shanghai: '26 million (2019)'
107
-
108
- Thought: Now I know that Shanghai has the highest population.
109
- <code>
110
- final_answer("Shanghai")
111
- </code>
112
-
113
- ---
114
- Task: "What is the current age of the pope, raised to the power 0.36?"
115
-
116
- Thought: I will use the tool `wikipedia_search` to get the age of the pope, and confirm that with a web search.
117
- <code>
118
- pope_age_wiki = wikipedia_search(query="current pope age")
119
- print("Pope age as per wikipedia:", pope_age_wiki)
120
- pope_age_search = web_search(query="current pope age")
121
- print("Pope age as per google search:", pope_age_search)
122
- </code>
123
- Observation:
124
- Pope age: "The pope Francis is currently 88 years old."
125
-
126
- Thought: I know that the pope is 88 years old. Let's compute the result using python code.
127
- <code>
128
- pope_current_age = 88 ** 0.36
129
- final_answer(pope_current_age)
130
- </code>
131
-
132
- 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:
133
  ```python
134
  {%- for tool in tools.values() %}
135
  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}}:
@@ -161,6 +47,7 @@ system_prompt: |-
161
  ```
162
  {%- endif %}
163
 
 
164
  Here are the rules you should always follow to solve your task:
165
  1. Always provide a 'Thought:' sequence, and a '<code>' sequence ending with '</code>', else you will fail.
166
  2. Use only variables that you have defined!
 
1
  system_prompt: |-
2
+ You are an intelligent agent that answers questions and uses tools to help users.
3
+ Think step by step and use tools when needed.
4
+ If you need information in Wikipedia, use the WikipediaSearchTool and import this tool with 'import wikipediaapi'.
5
+ If you need to search the web, use the WebSearchTool.
6
+ If you need to visit a webpage, use the VisitWebpageTool.
7
+ If you need to run Python code, use the PythonInterpreterTool.
8
+ If you need to generate code to extract information, generate the code and use the PythonInterpreterTool to execute the code and extract the informations.
9
+ Verify your final answer and the format of the final answer before returning it.
10
+ If you don't know the answer, say 'I don't know'.
11
 
12
  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.
13
  Then in the '<code>' sequence, you should write the code in simple Python. The code sequence must end with '</code>' sequence.
14
  During each intermediate step, you can use 'print()' to save whatever important information you will then need.
15
  These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
16
+ In the end you have to return a final answer using the `final_answer` tool, like this: <code>final_answer(answer)</code>.
17
 
18
+ 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:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  ```python
20
  {%- for tool in tools.values() %}
21
  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}}:
 
47
  ```
48
  {%- endif %}
49
 
50
+
51
  Here are the rules you should always follow to solve your task:
52
  1. Always provide a 'Thought:' sequence, and a '<code>' sequence ending with '</code>', else you will fail.
53
  2. Use only variables that you have defined!
requirements.txt CHANGED
@@ -11,6 +11,6 @@ tokenizers
11
  datasets
12
  accelerate
13
  # Opzionali ma utili
14
- # duckduckgo-search
15
  # bitsandbytes # Per quantizzazione
16
  huggingface_hub[hf_xet] # (installato con conda install -c conda-forge huggingface_hub)
 
11
  datasets
12
  accelerate
13
  # Opzionali ma utili
14
+ duckduckgo-search
15
  # bitsandbytes # Per quantizzazione
16
  huggingface_hub[hf_xet] # (installato con conda install -c conda-forge huggingface_hub)
test.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import wikipediaapi
2
+
3
+ def get_studio_albums(query):
4
+ # Use the Wikipedia API to search for the artist's studio albums
5
+ wiki = wikipediaapi.Wikipedia(
6
+ user_agent="FinalAssignmentAgent ([email protected])",
7
+ language="en",
8
+ # content_type="text", # "summary" or "text"
9
+ extract_format=wikipediaapi.ExtractFormat.WIKI, # "WIKI" or "HTML"
10
+ )
11
+ page = wiki.page(query)
12
+ if page.exists():
13
+ return page.text
14
+ return "No information found."
15
+
16
+ artist_name = "Mercedes Sosa"
17
+ # studio_albums = get_studio_albums(artist_name)
18
+
19
+ # print(f"The artist {artist_name} published {studio_albums} studio albums between 2000 and 2009.")
20
+
21
+ from smolagents import CodeAgent, ToolCallingAgent, TransformersModel, VisitWebpageTool, PythonInterpreterTool, WebSearchTool, WikipediaSearchTool, FinalAnswerTool, Tool, tool # InferenceClientModel, GoogleSearchTool (usa SERPAPI_API_KEY), DuckDuckGoSearchTool
22
+ model_id = "HuggingFaceTB/SmolLM2-1.7B-Instruct"
23
+ model = TransformersModel(model_id=model_id, trust_remote_code=True, max_new_tokens=4096)
24
+ agent = CodeAgent(
25
+ model=model,
26
+ tools=[
27
+ WebSearchTool(),
28
+ VisitWebpageTool(),
29
+ PythonInterpreterTool(),
30
+ FinalAnswerTool(),
31
+ ],
32
+ )
33
+ print(agent.prompt_templates)