Spaces:
Sleeping
Sleeping
# agents.py | |
# agents.py | |
import shutil | |
import os | |
import json | |
from smolagents import CodeAgent, LiteLLMModel, DuckDuckGoSearchTool, HfApiModel,VisitWebpageTool, FinalAnswerTool | |
# import datetime | |
from smolagents.tools import Tool | |
from typing import Any | |
from tools import get_text_from_ascii_file, get_wikipedia_markdown, transcribe_mp3, describe_image_file, read_xls_File, get_youtube_video_transcript | |
# class FinalAnswerTool(Tool): | |
# name = "final_answer" | |
# description = "Provides a final answer to the given problem." | |
# inputs = {"answer": {"type": "any", "description": "The final answer to the problem"}} | |
# output_type = "any" | |
# def forward(self, answer: Any) -> Any: | |
# if "FINAL ANSWER:" in answer: | |
# return answer.split("FINAL ANSWER:")[-1].strip() | |
# else: | |
# return answer.strip() | |
# helper function based on recommendations: | |
# "For the sake of this course, make sure you don’t include the text “FINAL ANSWER” in your submission, | |
# just make your agent reply with the answer and nothing else." | |
def extract_final_answer(answer: str) -> str: | |
# answer = answer.strip() | |
# Check if the answer contains "FINAL ANSWER:" and elemint it | |
if "</think>" in answer: | |
answer = answer.split("</think>")[-1].strip() | |
while "final answer" in answer.lower(): | |
answer = answer.replace("FINAL ANSWER:", "").replace("Final Answer:", "").replace("Final answer:", "").replace("final answer:", "") | |
answer = answer.replace("FINAL ANSWER", "").replace("Final Answer", "").replace("Final answer", "").replace("final answer", "") | |
return answer.strip() | |
# Define GAIAAgent | |
class GAIAAgent: | |
def __init__(self, use_model: str = "ollamaSRV") -> None: | |
# Initialize LiteLLMModel with Gemini Flash | |
# check for ollama | |
if use_model == "ollamaSRV": | |
print("Using LiteLLMModel with Ollama reverse proxy server.") | |
self.model = LiteLLMModel( | |
# model_id='ollama/devstral:24b', | |
# model_id="ollama/cogito:14b", | |
model_id='ollama/qwen3:32b', | |
# model_id='ollama/gemma3:27b', | |
# model_id='ollama/qwen2.5-coder:32b-instruct-q4_K_M', | |
api_base="https://192.168.5.217:8000", # replace with remote open-ai compatible server if necessary | |
api_key=os.getenv("OLLAMA_REVPROXY_SRVML"), | |
num_ctx=16384, # ollama default is 2048 which will often fail horribly. 8192 works for easy tasks, more is better. Check https://huggingface.co/spaces/NyxKrage/LLM-Model-VRAM-Calculator to calculate how much VRAM this will need for the selected model | |
ssl_verify=False, # Explicitly disable SSL verification | |
extra_headers={ | |
"Authorization": f"Bearer {os.getenv('OLLAMA_REVPROXY_SRVML')}", # Explicitly set auth header | |
}, | |
flatten_messages_as_text = False, | |
timeout=900 # seconds, default is 600 seconds, set to 15 minutes to allow for longer tasks | |
) | |
elif (use_model == "ollama") and shutil.which("ollama"): | |
print("Using LiteLLMModel with local Ollama CLI.") | |
self.model = LiteLLMModel( | |
model_id="ollama/devstral:24b", | |
# model_id="ollama/cogito:14b", | |
max_tokens=16384 | |
) | |
elif (use_model == "gemini") and "GEMINI_API_KEY" in os.environ: | |
print("Using Gemini Flash model with API key.") | |
self.model = LiteLLMModel( | |
model_id="gemini/gemini-2.5-flash-preview-05-20", | |
api_key=os.getenv("GEMINI_API_KEY"), | |
) | |
else: | |
print("Using HfApiModel with Qwen2.5-Coder-32B-Instruct.") | |
self.model = HfApiModel( | |
max_tokens=2096, | |
temperature=0.5, | |
model_id='Qwen/Qwen2.5-Coder-32B-Instruct', | |
custom_role_conversions=None | |
) | |
# Define the tools | |
self.tools = [ | |
get_wikipedia_markdown, get_text_from_ascii_file, transcribe_mp3, | |
describe_image_file, get_youtube_video_transcript, read_xls_File, | |
DuckDuckGoSearchTool(), # Web search (main retrieval) | |
VisitWebpageTool(), # Optional: visit page if needed (sometimes helps) | |
FinalAnswerTool(), # Needed for FINAL ANSWER output | |
] | |
prompt_templates = {'system_prompt': 'You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.\nTo do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.\nTo solve the task, you must plan forward to proceed in a series of steps, in a cycle of \'Thought:\', \'Code:\', and \'Observation:\' sequences.\n\nAt each step, in the \'Thought:\' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.\nThen in the \'Code:\' sequence, you should write the code in simple Python. The code sequence must end with \'<end_code>\' sequence.\nDuring each intermediate step, you can use \'print()\' to save whatever important information you will then need.\nThese print outputs will then appear in the \'Observation:\' field, which will be available as input for the next step.\nIn the end you have to return a final answer using the `final_answer` tool with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don\'t use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don\'t use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string. \n\nHere are a few examples using notional tools:\n---\nTask: "What is the result of the following operation: 5 + 3 + 1294.678?"\n\nThought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool\nCode:\n```py\nresult = 5 + 3 + 1294.678\nfinal_answer(print(f"FINAL ANSWER: {result}"))\n```<end_code>\n\n---\nTask:\n"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.\nYou have been provided with these additional arguments, that you can access using the keys as variables in your python code:\n{\'question\': \'Quel est l\'animal sur l\'image?\', \'image\': \'path/to/image.jpg\'}"\n\nThought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.\nCode:\n```py\ntranslated_question = translator(question=question, src_lang="French", tgt_lang="English")\nprint(f"The translated question is {translated_question}.")\nanswer = image_qa(image=image, question=translated_question)\nfinal_answer(f"FINAL ANSWER {answer}")\n```<end_code>\n\n---\nTask:\nIn a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.\nWhat does he say was the consequence of Einstein learning too much math on his creativity, in one word?\n\nThought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.\nCode:\n```py\npages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")\nprint(pages)\n```<end_code>\nObservation:\nNo result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".\n\nThought: The query was maybe too restrictive and did not find any results. Let\'s try again with a broader query.\nCode:\n```py\npages = search(query="1979 interview Stanislaus Ulam")\nprint(pages)\n```<end_code>\nObservation:\nFound 6 pages:\n[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)\n\n[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)\n\n(truncated)\n\nThought: I will read the first 2 pages to know more.\nCode:\n```py\nfor url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:\n whole_page = visit_webpage(url)\n print(whole_page)\n print("\\n" + "="*80 + "\\n") # Print separator between pages\n```<end_code>\nObservation:\nManhattan Project Locations:\nLos Alamos, NM\nStanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at\n(truncated)\n\nThought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let\'s answer in one word.\nCode:\n```py\nfinal_answer("FINAL ANSWER diminished")\n```<end_code>\n\n---\nTask: "Which city has the highest population: Guangzhou or Shanghai?"\n\nThought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.\nCode:\n```py\nfor city in ["Guangzhou", "Shanghai"]:\n print(f"Population {city}:", search(f"{city} population")\n```<end_code>\nObservation:\nPopulation Guangzhou: [\'Guangzhou has a population of 15 million inhabitants as of 2021.\']\nPopulation Shanghai: \'26 million (2019)\'\n\nThought: Now I know that Shanghai has the highest population.\nCode:\n```py\nfinal_answer("FINAL ANSWER Shanghai")\n```<end_code>\n\n---\nTask: "What is the current age of the pope, raised to the power 0.36?"\n\nThought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.\nCode:\n```py\npope_age_wiki = wiki(query="current pope age")\nprint("Pope age as per wikipedia:", pope_age_wiki)\npope_age_search = web_search(query="current pope age")\nprint("Pope age as per google search:", pope_age_search)\n```<end_code>\nObservation:\nPope age: "The pope Francis is currently 88 years old."\n\nThought: I know that the pope is 88 years old. Let\'s compute the result using python code.\nCode:\n```py\npope_current_age = 88 ** 0.36\nfinal_answer(f"FINAL ANSWER {pope_current_age}")\n```<end_code>\n\nAbove example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools, behaving like regular python functions:\n```python\n{%- for tool in tools.values() %}\ndef {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:\n """{{ tool.description }}\n\n Args:\n {%- for arg_name, arg_info in tool.inputs.items() %}\n {{ arg_name }}: {{ arg_info.description }}\n {%- endfor %}\n """\n{% endfor %}\n```\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is \'task\'.\nGiven that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.\nHere is a list of the team members that you can call:\n```python\n{%- for agent in managed_agents.values() %}\ndef {{ agent.name }}("Your query goes here.") -> str:\n """{{ agent.description }}"""\n{% endfor %}\n```\n{%- endif %}\n\nHere are the rules you should always follow to solve your task:\n1. Always provide a \'Thought:\' sequence, and a \'Code:\\n```py\' sequence ending with \'```<end_code>\' sequence, else you will fail.\n2. Use only variables that you have defined!\n3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in \'answer = wiki({\'query\': "What is the place where James Bond lives?"})\', but use the arguments directly as in \'answer = wiki(query="What is the place where James Bond lives?")\'.\n4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.\n5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.\n6. Don\'t name any new variable with the same name as a tool: for instance don\'t name a variable \'final_answer\'.\n7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.\n8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}\n9. The state persists between code executions: so if in one step you\'ve created variables or imported modules, these will all persist.\n10. Don\'t give up! You\'re in charge of solving the task, not providing directions to solve it.\n\nNow Begin!', | |
'planning': {'initial_plan': 'You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.\nBelow I will present you a task. You will need to 1. build a survey of facts known or needed to solve the task, then 2. make a plan of action to solve the task.\n\n## 1. Facts survey\nYou will build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.\nThese "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:\n### 1.1. Facts given in the task\nList here the specific facts given in the task that could help you (there might be nothing here).\n\n### 1.2. Facts to look up\nList here any facts that we may need to look up.\nAlso list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.\n\n### 1.3. Facts to derive\nList here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.\n\nDon\'t make any assumptions. For each item, provide a thorough reasoning. Do not add anything else on top of three headings above.\n\n## 2. Plan\nThen for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.\nThis plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.\nDo not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.\nAfter writing the final step of the plan, write the \'\\n<end_plan>\' tag and stop there.\n\nYou can leverage these tools, behaving like regular python functions:\n```python\n{%- for tool in tools.values() %}\ndef {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:\n """{{ tool.description }}\n\n Args:\n {%- for arg_name, arg_info in tool.inputs.items() %}\n {{ arg_name }}: {{ arg_info.description }}\n {%- endfor %}\n """\n{% endfor %}\n```\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is \'task\'.\nGiven that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.\nHere is a list of the team members that you can call:\n```python\n{%- for agent in managed_agents.values() %}\ndef {{ agent.name }}("Your query goes here.") -> str:\n """{{ agent.description }}"""\n{% endfor %}\n```\n{%- endif %}\n\n---\nNow begin! Here is your task:\n```\n{{task}}\n```\nFirst in part 1, write the facts survey, then in part 2, write your plan.', | |
'update_plan_pre_messages': 'You are a world expert at analyzing a situation, and plan accordingly towards solving a task.\nYou have been given the following task:\n```\n{{task}}\n```\n\nBelow you will find a history of attempts made to solve this task.\nYou will first have to produce a survey of known and unknown facts, then propose a step-by-step high-level plan to solve the task.\nIf the previous tries so far have met some success, your updated plan can build on these results.\nIf you are stalled, you can make a completely new plan starting from scratch.\n\nFind the task and history below:', | |
'update_plan_post_messages': 'Now write your updated facts below, taking into account the above history:\n## 1. Updated facts survey\n### 1.1. Facts given in the task\n### 1.2. Facts that we have learned\n### 1.3. Facts still to look up\n### 1.4. Facts still to derive\n\nThen write a step-by-step high-level plan to solve the task above.\n## 2. Plan\n### 2. 1. ...\nEtc.\nThis plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.\nBeware that you have {remaining_steps} steps remaining.\nDo not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.\nAfter writing the final step of the plan, write the \'\\n<end_plan>\' tag and stop there.\n\nYou can leverage these tools, behaving like regular python functions:\n```python\n{%- for tool in tools.values() %}\ndef {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:\n """{{ tool.description }}\n\n Args:\n {%- for arg_name, arg_info in tool.inputs.items() %}\n {{ arg_name }}: {{ arg_info.description }}\n {%- endfor %}"""\n{% endfor %}\n```\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is \'task\'.\nGiven that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.\nHere is a list of the team members that you can call:\n```python\n{%- for agent in managed_agents.values() %}\ndef {{ agent.name }}("Your query goes here.") -> str:\n """{{ agent.description }}"""\n{% endfor %}\n```\n{%- endif %}\n\nNow write your updated facts survey below, then your new plan.'}, | |
'managed_agent': {'task':( | |
"You are a highly capable and autonomous agent named {{name}}, designed to solve complex tasks efficiently.\n" | |
"A valued client has assigned you the following task:\n" | |
"---\n" | |
"Task:\n" | |
"{{task}}\n" | |
"---\n" | |
"To complete this task successfully, follow these steps carefully:\n" | |
" 1. Comprehend the task and identify the intended goal.\n" | |
" 2. Break the task into clear, logical steps.\n" | |
" 3. Select and prepare the tools or resources you need.\n" | |
" 4. Set up the required environment or context.\n" | |
" 5. Execute each step methodically.\n" | |
" 6. Monitor outcomes and identify any deviations.\n" | |
" 7. Revise your plan if necessary based on feedback.\n" | |
" 8. Maintain internal state and track progress.\n" | |
" 9. Verify that the goal has been fully achieved.\n" | |
" 10. Present the final result clearly and concisely.\n" | |
"If you succeed, you will be rewarded with a significant bonus.\n\n" | |
"Your final_answer MUST be:\n" | |
"- a number (retain its original type; do not include units),\n" | |
"- a concise phrase,\n" | |
"- or a comma-separated list of numbers or strings (no articles, no abbreviations).\n\n" | |
"Only the content passed to the final_answer tool will be preserved. Any other content will be discarded."), | |
'report': "{{final_answer}}"}, | |
'final_answer': { | |
'pre_messages': "", | |
'post_messages': "" | |
}} | |
# Create the CodeAgent | |
self.agent = CodeAgent( | |
tools=self.tools, | |
model=self.model, | |
prompt_templates = prompt_templates, | |
max_steps=10, # should be enough, first guess --> to check | |
planning_interval=3, # should be enough, first guess --> to check | |
verbosity_level=2, # 0: no output, 1: only errors, 2: all outputs | |
additional_authorized_imports=["datetime", "numpy", "requests", "json", "re", | |
"bs4", "pandas", "lxml", "pymupdf", "openpyxl", | |
"scipy", "PIL", "cv2"], | |
name="RendelsGAIAAgent" | |
) | |
print("✅ GAIAAgent initialized with tools:", [t.name for t in self.tools]) | |
def __call__(self, question: str) -> str: | |
print(f"\n[GAIAAgent] Running agent on question:\n{question}\n") | |
try: | |
result = self.agent.run(question) | |
final_answer = extract_final_answer(result) | |
print(f"\n[GAIAAgent] FINAL ANSWER extracted: {final_answer}\n") | |
return final_answer | |
except Exception as e: | |
print(f"[GAIAAgent] ERROR: {e}") | |
return f"ERROR: {e}" | |