Spaces:
Sleeping
Sleeping
Daniel Sellmeier
commited on
Commit
·
0f8361a
1
Parent(s):
81917a3
Verbesserte Antwortformatierung und Parsing-Kompatibilität für exakte Antwortabgleiche
Browse files- .gitignore +100 -0
- app.py +272 -11
- prompts.yaml +338 -0
- requirements.txt +7 -1
- tools/final_answer.py +34 -0
.gitignore
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Byte-compiled / optimized / DLL files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
|
| 6 |
+
# C extensions
|
| 7 |
+
*.so
|
| 8 |
+
|
| 9 |
+
# Distribution / packaging
|
| 10 |
+
.Python
|
| 11 |
+
build/
|
| 12 |
+
dist/
|
| 13 |
+
downloads/
|
| 14 |
+
eggs/
|
| 15 |
+
*.egg-info/
|
| 16 |
+
.installed.cfg
|
| 17 |
+
*.egg
|
| 18 |
+
MANIFEST
|
| 19 |
+
|
| 20 |
+
# PyInstaller
|
| 21 |
+
# Usually these files are written by a python script from a template
|
| 22 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 23 |
+
*.manifest
|
| 24 |
+
*.spec
|
| 25 |
+
|
| 26 |
+
# Installer logs
|
| 27 |
+
pip-log.txt
|
| 28 |
+
pip-delete-this-directory.txt
|
| 29 |
+
|
| 30 |
+
# Unit test / coverage reports
|
| 31 |
+
htmlcov/
|
| 32 |
+
.tox/
|
| 33 |
+
.nox/
|
| 34 |
+
.coverage
|
| 35 |
+
.coverage.*
|
| 36 |
+
.cache
|
| 37 |
+
nosetests.xml
|
| 38 |
+
coverage.xml
|
| 39 |
+
*.cover
|
| 40 |
+
*.py,cover
|
| 41 |
+
.hypothesis/
|
| 42 |
+
.pytest_cache/
|
| 43 |
+
|
| 44 |
+
# Environments
|
| 45 |
+
.env
|
| 46 |
+
.venv
|
| 47 |
+
env/
|
| 48 |
+
venv/
|
| 49 |
+
ENV/
|
| 50 |
+
env.bak/
|
| 51 |
+
venv.bak/
|
| 52 |
+
|
| 53 |
+
# Spyder project settings
|
| 54 |
+
.spyderproject
|
| 55 |
+
.spyproject
|
| 56 |
+
|
| 57 |
+
# Rope project settings
|
| 58 |
+
.ropeproject
|
| 59 |
+
|
| 60 |
+
# mkdocs documentation
|
| 61 |
+
/site
|
| 62 |
+
|
| 63 |
+
# mypy
|
| 64 |
+
.mypy_cache/
|
| 65 |
+
.dmypy.json
|
| 66 |
+
dmypy.json
|
| 67 |
+
|
| 68 |
+
# Jupyter Notebook
|
| 69 |
+
.ipynb_checkpoints
|
| 70 |
+
|
| 71 |
+
# IPython
|
| 72 |
+
profile_default/
|
| 73 |
+
ipython_config.py
|
| 74 |
+
|
| 75 |
+
# pyenv
|
| 76 |
+
.python-version
|
| 77 |
+
|
| 78 |
+
# PEP 582; used by PDM, PEP 582 proposal
|
| 79 |
+
__pypackages__/
|
| 80 |
+
|
| 81 |
+
# Celery stuff
|
| 82 |
+
celerybeat-schedule.*
|
| 83 |
+
celerybeat.pid
|
| 84 |
+
|
| 85 |
+
# SageMath parsed files
|
| 86 |
+
*.sage.py
|
| 87 |
+
|
| 88 |
+
# Environments
|
| 89 |
+
.env.*
|
| 90 |
+
!.env.example
|
| 91 |
+
|
| 92 |
+
# VSCode
|
| 93 |
+
.vscode/
|
| 94 |
+
|
| 95 |
+
# macOS
|
| 96 |
+
.DS_Store
|
| 97 |
+
|
| 98 |
+
# Optional: Add if you use databases locally
|
| 99 |
+
# *.sqlite
|
| 100 |
+
# *.sqlite3
|
app.py
CHANGED
|
@@ -3,25 +3,286 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
# ---
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def __init__(self):
|
| 15 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
-
print(f"
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
| 24 |
-
Fetches all questions, runs the
|
| 25 |
and displays the results.
|
| 26 |
"""
|
| 27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
|
@@ -40,7 +301,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 40 |
|
| 41 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
try:
|
| 43 |
-
agent =
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
|
@@ -192,5 +453,5 @@ if __name__ == "__main__":
|
|
| 192 |
|
| 193 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
|
| 195 |
-
print("Launching Gradio Interface for
|
| 196 |
demo.launch(debug=True, share=False)
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
# --- New Imports ---
|
| 7 |
+
import datetime
|
| 8 |
+
import pytz
|
| 9 |
+
import yaml
|
| 10 |
+
import secrets
|
| 11 |
+
import string
|
| 12 |
+
import re # Import re for visit_webpage
|
| 13 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel, load_tool, tool
|
| 14 |
+
from tools.final_answer import FinalAnswerTool
|
| 15 |
+
from smolagents.utils import truncate_content
|
| 16 |
+
import dotenv
|
| 17 |
+
|
| 18 |
+
dotenv.load_dotenv()
|
| 19 |
+
|
| 20 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 21 |
|
| 22 |
# (Keep Constants as is)
|
| 23 |
# --- Constants ---
|
| 24 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 25 |
|
| 26 |
+
# --- Tool Definitions ---
|
| 27 |
+
|
| 28 |
+
# Tool: search (using DuckDuckGoSearchTool)
|
| 29 |
+
@tool
|
| 30 |
+
def search(query:str) -> str:
|
| 31 |
+
"""Perform a web query with the specified search string.
|
| 32 |
+
Args:
|
| 33 |
+
query: The search string to pass to the search engine.
|
| 34 |
+
"""
|
| 35 |
+
# Note: DuckDuckGoSearchTool itself handles the import check now.
|
| 36 |
+
search_tool_instance = DuckDuckGoSearchTool()
|
| 37 |
+
return search_tool_instance(query)
|
| 38 |
+
|
| 39 |
+
# Tool: get_current_time_in_timezone
|
| 40 |
+
@tool
|
| 41 |
+
def get_current_time_in_timezone(timezone: str) -> str:
|
| 42 |
+
"""A tool that fetches the current local time in a specified timezone.
|
| 43 |
+
Args:
|
| 44 |
+
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
| 45 |
+
"""
|
| 46 |
+
try:
|
| 47 |
+
# Create timezone object
|
| 48 |
+
tz = pytz.timezone(timezone)
|
| 49 |
+
# Get current time in that timezone
|
| 50 |
+
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 51 |
+
return f"The current local time in {timezone} is: {local_time}"
|
| 52 |
+
except Exception as e:
|
| 53 |
+
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 54 |
+
|
| 55 |
+
# Tool: get_open_meteo_weather
|
| 56 |
+
@tool
|
| 57 |
+
def get_open_meteo_weather(city: str) -> str:
|
| 58 |
+
"""
|
| 59 |
+
Fetches the current weather for a given city using Open-Meteo's APIs.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
city: The name of the city (e.g., "Berlin", "New York").
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
A string summarizing the current weather conditions, or an error message.
|
| 66 |
+
"""
|
| 67 |
+
try:
|
| 68 |
+
# First, use the geocoding API to convert the city name to coordinates.
|
| 69 |
+
geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}"
|
| 70 |
+
geo_response = requests.get(geo_url)
|
| 71 |
+
geo_response.raise_for_status()
|
| 72 |
+
geo_data = geo_response.json()
|
| 73 |
+
|
| 74 |
+
results = geo_data.get("results")
|
| 75 |
+
if not results:
|
| 76 |
+
return f"No coordinates found for city: {city}"
|
| 77 |
+
|
| 78 |
+
# Use the first matching result.
|
| 79 |
+
first_result = results[0]
|
| 80 |
+
latitude = first_result.get("latitude")
|
| 81 |
+
longitude = first_result.get("longitude")
|
| 82 |
+
resolved_name = first_result.get("name", city)
|
| 83 |
+
|
| 84 |
+
# Now, query the Open-Meteo weather API with the obtained coordinates.
|
| 85 |
+
weather_url = (
|
| 86 |
+
f"https://api.open-meteo.com/v1/forecast"
|
| 87 |
+
f"?latitude={latitude}&longitude={longitude}¤t_weather=true"
|
| 88 |
+
)
|
| 89 |
+
weather_response = requests.get(weather_url)
|
| 90 |
+
weather_response.raise_for_status()
|
| 91 |
+
weather_data = weather_response.json()
|
| 92 |
+
|
| 93 |
+
current = weather_data.get("current_weather")
|
| 94 |
+
if not current:
|
| 95 |
+
return "Current weather data not available."
|
| 96 |
+
|
| 97 |
+
temperature = current.get("temperature")
|
| 98 |
+
windspeed = current.get("windspeed")
|
| 99 |
+
winddirection = current.get("winddirection")
|
| 100 |
+
weathercode = current.get("weathercode")
|
| 101 |
+
weather_time = current.get("time")
|
| 102 |
+
|
| 103 |
+
return (
|
| 104 |
+
f"In {resolved_name} at {weather_time}, the temperature is {temperature}°C, "
|
| 105 |
+
f"wind speed is {windspeed} km/h, wind direction is {winddirection}°, "
|
| 106 |
+
f"weather code: {weathercode}."
|
| 107 |
+
)
|
| 108 |
+
except Exception as e:
|
| 109 |
+
return f"Error fetching weather data: {str(e)}"
|
| 110 |
+
|
| 111 |
+
# Tool: get_random_joke
|
| 112 |
+
@tool
|
| 113 |
+
def get_random_joke() -> str:
|
| 114 |
+
"""
|
| 115 |
+
Fetches a random joke from the Official Joke API.
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
A string containing the joke's setup and punchline, or an error message.
|
| 119 |
+
"""
|
| 120 |
+
try:
|
| 121 |
+
# The API endpoint for a random joke:
|
| 122 |
+
url = "https://official-joke-api.appspot.com/random_joke"
|
| 123 |
+
response = requests.get(url)
|
| 124 |
+
response.raise_for_status()
|
| 125 |
+
joke_data = response.json()
|
| 126 |
+
|
| 127 |
+
setup = joke_data.get("setup")
|
| 128 |
+
punchline = joke_data.get("punchline")
|
| 129 |
+
if not setup or not punchline:
|
| 130 |
+
return "Couldn't find a complete joke."
|
| 131 |
+
return f"{setup} - {punchline}"
|
| 132 |
+
except Exception as e:
|
| 133 |
+
return f"Error fetching joke: {str(e)}"
|
| 134 |
+
|
| 135 |
+
# Tool: generate_password
|
| 136 |
+
@tool
|
| 137 |
+
def generate_password(length: int = 16, use_punctuation: bool = True) -> str:
|
| 138 |
+
"""
|
| 139 |
+
Generates a secure random password with at least 16 characters.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
length: The desired length of the password (must be at least 16; default is 16).
|
| 143 |
+
use_punctuation: Whether to include punctuation symbols in the password (default is True).
|
| 144 |
+
|
| 145 |
+
Returns:
|
| 146 |
+
A randomly generated password as a string.
|
| 147 |
+
|
| 148 |
+
Raises:
|
| 149 |
+
ValueError: If the requested length is less than 16.
|
| 150 |
+
"""
|
| 151 |
+
if length < 16:
|
| 152 |
+
# Instead of raising an error, return a message for Gradio
|
| 153 |
+
return "Error: Password length must be at least 16 characters"
|
| 154 |
+
|
| 155 |
+
# Build the alphabet from which to choose characters.
|
| 156 |
+
alphabet = string.ascii_letters + string.digits
|
| 157 |
+
if use_punctuation:
|
| 158 |
+
alphabet += string.punctuation
|
| 159 |
+
|
| 160 |
+
# Generate a secure random password using secrets.choice.
|
| 161 |
+
password = ''.join(secrets.choice(alphabet) for _ in range(length))
|
| 162 |
+
return password
|
| 163 |
+
|
| 164 |
+
# Tool: VisitWebpageTool
|
| 165 |
+
@tool
|
| 166 |
+
def visit_webpage(url: str) -> str:
|
| 167 |
+
"""Visits a webpage at the given url and reads its content as a markdown string.
|
| 168 |
+
Use this to browse webpages.
|
| 169 |
+
Args:
|
| 170 |
+
url: The url of the webpage to visit.
|
| 171 |
+
"""
|
| 172 |
+
try:
|
| 173 |
+
# Send a GET request to the URL with a 20-second timeout
|
| 174 |
+
response = requests.get(url, timeout=20)
|
| 175 |
+
response.raise_for_status() # Raise an exception for bad status codes
|
| 176 |
+
|
| 177 |
+
# Convert the HTML content to Markdown
|
| 178 |
+
# Ensure markdownify is imported
|
| 179 |
+
from markdownify import markdownify
|
| 180 |
+
markdown_content = markdownify(response.text).strip()
|
| 181 |
+
|
| 182 |
+
# Remove multiple line breaks
|
| 183 |
+
markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
|
| 184 |
+
|
| 185 |
+
# Truncate content (ensure truncate_content is imported from smolagents.utils)
|
| 186 |
+
return truncate_content(markdown_content, 10000)
|
| 187 |
+
|
| 188 |
+
except requests.exceptions.Timeout:
|
| 189 |
+
return "The request timed out. Please try again later or check the URL."
|
| 190 |
+
except requests.exceptions.RequestException as e:
|
| 191 |
+
return f"Error fetching the webpage: {str(e)}"
|
| 192 |
+
except Exception as e:
|
| 193 |
+
return f"An unexpected error occurred: {str(e)}"
|
| 194 |
+
|
| 195 |
+
# --- User's Agent Definition ---
|
| 196 |
+
class MyCodeAgent:
|
| 197 |
def __init__(self):
|
| 198 |
+
print("Initializing MyCodeAgent...")
|
| 199 |
+
try:
|
| 200 |
+
# Load prompts
|
| 201 |
+
with open("prompts.yaml", 'r') as stream:
|
| 202 |
+
self.prompt_templates = yaml.safe_load(stream)
|
| 203 |
+
print("Prompts loaded successfully.")
|
| 204 |
+
|
| 205 |
+
# Initialize OpenAI Model
|
| 206 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 207 |
+
if not openai_api_key:
|
| 208 |
+
# Raise an error if the key is missing, as the app cannot function without it.
|
| 209 |
+
# Provide a clear message for the user.
|
| 210 |
+
raise ValueError("Environment variable OPENAI_API_KEY is not set. Please set it to your OpenAI API key.")
|
| 211 |
+
|
| 212 |
+
self.model = OpenAIServerModel(
|
| 213 |
+
model_id="gpt-4.1", # Or use "gpt-4o" or another compatible model
|
| 214 |
+
api_base="https://api.openai.com/v1", # Default OpenAI API base
|
| 215 |
+
api_key=openai_api_key,
|
| 216 |
+
)
|
| 217 |
+
print(f"OpenAIServerModel initialized with model_id='{self.model.model_id}'.")
|
| 218 |
+
|
| 219 |
+
# Load tools
|
| 220 |
+
self.final_answer_tool = FinalAnswerTool()
|
| 221 |
+
# Assuming 'agents-course/text-to-image' needs trust_remote_code
|
| 222 |
+
self.image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 223 |
+
print("Tools loaded.")
|
| 224 |
+
|
| 225 |
+
# Initialize CodeAgent
|
| 226 |
+
self.agent = CodeAgent(
|
| 227 |
+
model=self.model,
|
| 228 |
+
tools=[self.final_answer_tool, get_current_time_in_timezone, self.image_generation_tool, search, get_open_meteo_weather, get_random_joke, generate_password, visit_webpage],
|
| 229 |
+
max_steps=15, # As per user's code
|
| 230 |
+
verbosity_level=1, # As per user's code
|
| 231 |
+
grammar=None,
|
| 232 |
+
planning_interval=None,
|
| 233 |
+
name=None,
|
| 234 |
+
description=None,
|
| 235 |
+
prompt_templates=self.prompt_templates,
|
| 236 |
+
additional_authorized_imports=['pandas', 'numpy', 'openpyxl', 'xlrd']
|
| 237 |
+
)
|
| 238 |
+
print("CodeAgent initialized.")
|
| 239 |
+
print("MyCodeAgent initialized successfully.")
|
| 240 |
+
except Exception as e:
|
| 241 |
+
print(f"Error during MyCodeAgent initialization: {e}")
|
| 242 |
+
# Raise the exception to prevent the app from potentially running in a broken state
|
| 243 |
+
raise
|
| 244 |
+
|
| 245 |
def __call__(self, question: str) -> str:
|
| 246 |
+
print(f"MyCodeAgent received question (first 50 chars): {question[:50]}...")
|
| 247 |
+
try:
|
| 248 |
+
response = self.agent(question)
|
| 249 |
+
|
| 250 |
+
# Ensure the response is a string for submission
|
| 251 |
+
if not isinstance(response, str):
|
| 252 |
+
print(f"Warning: Agent returned non-string type ({type(response)}). Converting to string.")
|
| 253 |
+
response = str(response)
|
| 254 |
+
|
| 255 |
+
# Verarbeite die Antwort, um nur die kurze Version zu extrahieren
|
| 256 |
+
if "### 1. Task outcome (short version):" in response:
|
| 257 |
+
short_answer_start = response.find("### 1. Task outcome (short version):") + len("### 1. Task outcome (short version):")
|
| 258 |
+
|
| 259 |
+
# Suche nach dem Ende der kurzen Antwort (dem Beginn des nächsten Abschnitts)
|
| 260 |
+
next_section = response.find("### 2.", short_answer_start)
|
| 261 |
+
if next_section != -1:
|
| 262 |
+
short_answer = response[short_answer_start:next_section].strip()
|
| 263 |
+
else:
|
| 264 |
+
short_answer = response[short_answer_start:].strip()
|
| 265 |
+
|
| 266 |
+
# Bereinige die Antwort von unnötigen Formatierungen
|
| 267 |
+
short_answer = short_answer.strip()
|
| 268 |
+
print(f"Extrahierte kurze Antwort: {short_answer}")
|
| 269 |
+
|
| 270 |
+
# Verwende die vollständige Antwort nur für Debugging-Zwecke
|
| 271 |
+
print(f"Vollständige Antwort für Debugging: {response[:100]}...")
|
| 272 |
+
|
| 273 |
+
return short_answer
|
| 274 |
+
|
| 275 |
+
print(f"MyCodeAgent returning answer (first 100 chars): {response[:100]}...")
|
| 276 |
+
return response
|
| 277 |
+
except Exception as e:
|
| 278 |
+
print(f"Error during MyCodeAgent execution: {e}")
|
| 279 |
+
# Return an error message instead of crashing the Gradio app
|
| 280 |
+
return f"AGENT_EXECUTION_ERROR: {e}"
|
| 281 |
+
|
| 282 |
|
| 283 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 284 |
"""
|
| 285 |
+
Fetches all questions, runs the MyCodeAgent on them, submits all answers,
|
| 286 |
and displays the results.
|
| 287 |
"""
|
| 288 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
|
|
|
| 301 |
|
| 302 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 303 |
try:
|
| 304 |
+
agent = MyCodeAgent()
|
| 305 |
except Exception as e:
|
| 306 |
print(f"Error instantiating agent: {e}")
|
| 307 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 453 |
|
| 454 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 455 |
|
| 456 |
+
print("Launching Gradio Interface for MyCodeAgent Evaluation...")
|
| 457 |
demo.launch(debug=True, share=False)
|
prompts.yaml
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
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.
|
| 6 |
+
Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
|
| 7 |
+
During each intermediate step, you can use 'print()' to save whatever important information you will then need.
|
| 8 |
+
These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
|
| 9 |
+
In the end you have to return a final answer using the `final_answer` tool.
|
| 10 |
+
|
| 11 |
+
Here are a few examples using notional tools:
|
| 12 |
+
---
|
| 13 |
+
Task: "Generate an image of the oldest person in this document."
|
| 14 |
+
|
| 15 |
+
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.
|
| 16 |
+
Code:
|
| 17 |
+
```py
|
| 18 |
+
answer = document_qa(document=document, question="Who is the oldest person mentioned?")
|
| 19 |
+
print(answer)
|
| 20 |
+
```<end_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 |
+
```py
|
| 26 |
+
image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
|
| 27 |
+
final_answer(image)
|
| 28 |
+
```<end_code>
|
| 29 |
+
|
| 30 |
+
---
|
| 31 |
+
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
|
| 32 |
+
|
| 33 |
+
Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
|
| 34 |
+
Code:
|
| 35 |
+
```py
|
| 36 |
+
result = 5 + 3 + 1294.678
|
| 37 |
+
final_answer(result)
|
| 38 |
+
```<end_code>
|
| 39 |
+
|
| 40 |
+
---
|
| 41 |
+
Task:
|
| 42 |
+
"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
|
| 43 |
+
You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
|
| 44 |
+
{'question': 'Quel est l\'animal sur l\'image?', 'image': 'path/to/image.jpg'}"
|
| 45 |
+
|
| 46 |
+
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.
|
| 47 |
+
Code:
|
| 48 |
+
```py
|
| 49 |
+
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
|
| 50 |
+
print(f"The translated question is {translated_question}.")
|
| 51 |
+
answer = image_qa(image=image, question=translated_question)
|
| 52 |
+
final_answer(f"The answer is {answer}")
|
| 53 |
+
```<end_code>
|
| 54 |
+
---
|
| 55 |
+
Task:
|
| 56 |
+
In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
|
| 57 |
+
What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
|
| 58 |
+
Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
|
| 59 |
+
Code:
|
| 60 |
+
```py
|
| 61 |
+
pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
|
| 62 |
+
print(pages)
|
| 63 |
+
```<end_code>
|
| 64 |
+
Observation:
|
| 65 |
+
No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
|
| 66 |
+
|
| 67 |
+
Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
|
| 68 |
+
Code:
|
| 69 |
+
```py
|
| 70 |
+
pages = search(query="1979 interview Stanislaus Ulam")
|
| 71 |
+
print(pages)
|
| 72 |
+
```<end_code>
|
| 73 |
+
Observation:
|
| 74 |
+
Found 6 pages:
|
| 75 |
+
[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
|
| 76 |
+
|
| 77 |
+
[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
|
| 78 |
+
|
| 79 |
+
(truncated)
|
| 80 |
+
|
| 81 |
+
Thought: I will read the first 2 pages to know more.
|
| 82 |
+
Code:
|
| 83 |
+
```py
|
| 84 |
+
for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
|
| 85 |
+
whole_page = visit_webpage(url)
|
| 86 |
+
print(whole_page)
|
| 87 |
+
print("\n" + "="*80 + "\n") # Print separator between pages
|
| 88 |
+
```<end_code>
|
| 89 |
+
Observation:
|
| 90 |
+
Manhattan Project Locations:
|
| 91 |
+
Los Alamos, NM
|
| 92 |
+
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
|
| 93 |
+
(truncated)
|
| 94 |
+
|
| 95 |
+
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.
|
| 96 |
+
Code:
|
| 97 |
+
```py
|
| 98 |
+
final_answer("diminished")
|
| 99 |
+
```<end_code>
|
| 100 |
+
|
| 101 |
+
---
|
| 102 |
+
Task: "Which city has the highest population: Guangzhou or Shanghai?"
|
| 103 |
+
|
| 104 |
+
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.
|
| 105 |
+
Code:
|
| 106 |
+
```py
|
| 107 |
+
for city in ["Guangzhou", "Shanghai"]:
|
| 108 |
+
print(f"Population {city}:", search(f"{city} population")
|
| 109 |
+
```<end_code>
|
| 110 |
+
Observation:
|
| 111 |
+
Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
|
| 112 |
+
Population Shanghai: '26 million (2019)'
|
| 113 |
+
|
| 114 |
+
Thought: Now I know that Shanghai has the highest population.
|
| 115 |
+
Code:
|
| 116 |
+
```py
|
| 117 |
+
final_answer("Shanghai")
|
| 118 |
+
```<end_code>
|
| 119 |
+
|
| 120 |
+
---
|
| 121 |
+
Task: "What is the current age of the pope, raised to the power 0.36?"
|
| 122 |
+
|
| 123 |
+
Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
|
| 124 |
+
Code:
|
| 125 |
+
```py
|
| 126 |
+
pope_age_wiki = wiki(query="current pope age")
|
| 127 |
+
print("Pope age as per wikipedia:", pope_age_wiki)
|
| 128 |
+
pope_age_search = web_search(query="current pope age")
|
| 129 |
+
print("Pope age as per google search:", pope_age_search)
|
| 130 |
+
```<end_code>
|
| 131 |
+
Observation:
|
| 132 |
+
Pope age: "The pope Francis is currently 88 years old."
|
| 133 |
+
|
| 134 |
+
Thought: I know that the pope is 88 years old. Let's compute the result using python code.
|
| 135 |
+
Code:
|
| 136 |
+
```py
|
| 137 |
+
pope_current_age = 88 ** 0.36
|
| 138 |
+
final_answer(pope_current_age)
|
| 139 |
+
```<end_code>
|
| 140 |
+
|
| 141 |
+
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:
|
| 142 |
+
{%- for tool in tools.values() %}
|
| 143 |
+
- {{ tool.name }}: {{ tool.description }}
|
| 144 |
+
Takes inputs: {{tool.inputs}}
|
| 145 |
+
Returns an output of type: {{tool.output_type}}
|
| 146 |
+
{%- endfor %}
|
| 147 |
+
|
| 148 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
| 149 |
+
You can also give tasks to team members.
|
| 150 |
+
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.
|
| 151 |
+
Given that this team member is a real human, you should be very verbose in your task.
|
| 152 |
+
Here is a list of the team members that you can call:
|
| 153 |
+
{%- for agent in managed_agents.values() %}
|
| 154 |
+
- {{ agent.name }}: {{ agent.description }}
|
| 155 |
+
{%- endfor %}
|
| 156 |
+
{%- else %}
|
| 157 |
+
{%- endif %}
|
| 158 |
+
|
| 159 |
+
Here are the rules you should always follow to solve your task:
|
| 160 |
+
1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
|
| 161 |
+
2. Use only variables that you have defined!
|
| 162 |
+
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?")'.
|
| 163 |
+
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.
|
| 164 |
+
5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
|
| 165 |
+
6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
|
| 166 |
+
7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
|
| 167 |
+
8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
|
| 168 |
+
9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
|
| 169 |
+
10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
|
| 170 |
+
|
| 171 |
+
Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
|
| 172 |
+
"planning":
|
| 173 |
+
"initial_facts": |-
|
| 174 |
+
Below I will present you a task.
|
| 175 |
+
You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
|
| 176 |
+
To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
|
| 177 |
+
Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
|
| 178 |
+
|
| 179 |
+
---
|
| 180 |
+
### 1. Facts given in the task
|
| 181 |
+
List here the specific facts given in the task that could help you (there might be nothing here).
|
| 182 |
+
|
| 183 |
+
### 2. Facts to look up
|
| 184 |
+
List here any facts that we may need to look up.
|
| 185 |
+
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.
|
| 186 |
+
|
| 187 |
+
### 3. Facts to derive
|
| 188 |
+
List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
|
| 189 |
+
|
| 190 |
+
Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
|
| 191 |
+
### 1. Facts given in the task
|
| 192 |
+
### 2. Facts to look up
|
| 193 |
+
### 3. Facts to derive
|
| 194 |
+
Do not add anything else.
|
| 195 |
+
"initial_plan": |-
|
| 196 |
+
You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
|
| 197 |
+
Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
|
| 198 |
+
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
| 199 |
+
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
| 200 |
+
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
| 201 |
+
|
| 202 |
+
Here is your task:
|
| 203 |
+
|
| 204 |
+
Task:
|
| 205 |
+
```
|
| 206 |
+
{{task}}
|
| 207 |
+
```
|
| 208 |
+
You can leverage these tools:
|
| 209 |
+
{%- for tool in tools.values() %}
|
| 210 |
+
- {{ tool.name }}: {{ tool.description }}
|
| 211 |
+
Takes inputs: {{tool.inputs}}
|
| 212 |
+
Returns an output of type: {{tool.output_type}}
|
| 213 |
+
{%- endfor %}
|
| 214 |
+
|
| 215 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
| 216 |
+
You can also give tasks to team members.
|
| 217 |
+
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.
|
| 218 |
+
Given that this team member is a real human, you should be very verbose in your request.
|
| 219 |
+
Here is a list of the team members that you can call:
|
| 220 |
+
{%- for agent in managed_agents.values() %}
|
| 221 |
+
- {{ agent.name }}: {{ agent.description }}
|
| 222 |
+
{%- endfor %}
|
| 223 |
+
{%- else %}
|
| 224 |
+
{%- endif %}
|
| 225 |
+
|
| 226 |
+
List of facts that you know:
|
| 227 |
+
```
|
| 228 |
+
{{answer_facts}}
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
Now begin! Write your plan below.
|
| 232 |
+
"update_facts_pre_messages": |-
|
| 233 |
+
You are a world expert at gathering known and unknown facts based on a conversation.
|
| 234 |
+
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:
|
| 235 |
+
### 1. Facts given in the task
|
| 236 |
+
### 2. Facts that we have learned
|
| 237 |
+
### 3. Facts still to look up
|
| 238 |
+
### 4. Facts still to derive
|
| 239 |
+
Find the task and history below:
|
| 240 |
+
"update_facts_post_messages": |-
|
| 241 |
+
Earlier we've built a list of facts.
|
| 242 |
+
But since in your previous steps you may have learned useful new facts or invalidated some false ones.
|
| 243 |
+
Please update your list of facts based on the previous history, and provide these headings:
|
| 244 |
+
### 1. Facts given in the task
|
| 245 |
+
### 2. Facts that we have learned
|
| 246 |
+
### 3. Facts still to look up
|
| 247 |
+
### 4. Facts still to derive
|
| 248 |
+
Now write your new list of facts below.
|
| 249 |
+
"update_plan_pre_messages": |-
|
| 250 |
+
You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
|
| 251 |
+
You have been given a task:
|
| 252 |
+
```
|
| 253 |
+
{{task}}
|
| 254 |
+
```
|
| 255 |
+
|
| 256 |
+
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.
|
| 257 |
+
If the previous tries so far have met some success, you can make an updated plan based on these actions.
|
| 258 |
+
If you are stalled, you can make a completely new plan starting from scratch.
|
| 259 |
+
"update_plan_post_messages": |-
|
| 260 |
+
You're still working towards solving this task:
|
| 261 |
+
```
|
| 262 |
+
{{task}}
|
| 263 |
+
```
|
| 264 |
+
You can leverage these tools:
|
| 265 |
+
{%- for tool in tools.values() %}
|
| 266 |
+
- {{ tool.name }}: {{ tool.description }}
|
| 267 |
+
Takes inputs: {{tool.inputs}}
|
| 268 |
+
Returns an output of type: {{tool.output_type}}
|
| 269 |
+
{%- endfor %}
|
| 270 |
+
|
| 271 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
| 272 |
+
You can also give tasks to team members.
|
| 273 |
+
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
|
| 274 |
+
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.
|
| 275 |
+
Here is a list of the team members that you can call:
|
| 276 |
+
{%- for agent in managed_agents.values() %}
|
| 277 |
+
- {{ agent.name }}: {{ agent.description }}
|
| 278 |
+
{%- endfor %}
|
| 279 |
+
{%- else %}
|
| 280 |
+
{%- endif %}
|
| 281 |
+
|
| 282 |
+
Here is the up to date list of facts that you know:
|
| 283 |
+
```
|
| 284 |
+
{{facts_update}}
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
|
| 288 |
+
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
| 289 |
+
Beware that you have {remaining_steps} steps remaining.
|
| 290 |
+
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
| 291 |
+
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
| 292 |
+
|
| 293 |
+
Now write your new plan below.
|
| 294 |
+
"managed_agent":
|
| 295 |
+
"task": |-
|
| 296 |
+
You're a helpful agent named '{{name}}'.
|
| 297 |
+
You have been submitted this task by your manager.
|
| 298 |
+
---
|
| 299 |
+
Task:
|
| 300 |
+
{{task}}
|
| 301 |
+
---
|
| 302 |
+
WICHTIG: Gib EXAKTE Antworten ohne zusätzliche Erklärungen oder Einleitungen.
|
| 303 |
+
- Bei Zahlen: Keine Tausender-Trennzeichen, keine Einheiten (wie $ oder %)
|
| 304 |
+
- Bei Zeichenketten: Keine Artikel, keine Abkürzungen
|
| 305 |
+
- Bei Listen: Kommagetrennte Werte ohne zusätzlichen Text
|
| 306 |
+
|
| 307 |
+
Bei der Beantwortung MUSST du das folgende Code-Format verwenden:
|
| 308 |
+
|
| 309 |
+
Thought: [Deine Gedanken zum Lösungsweg]
|
| 310 |
+
Code:
|
| 311 |
+
```py
|
| 312 |
+
# Verwende die final_answer-Funktion mit folgender Struktur
|
| 313 |
+
final_answer({
|
| 314 |
+
"answer": """
|
| 315 |
+
### 1. Task outcome (short version):
|
| 316 |
+
[Schreibe hier GENAU das Ergebnis - nur die Antwort selbst ohne weitere Erklärungen]
|
| 317 |
+
|
| 318 |
+
### 2. Task outcome (extremely detailed version):
|
| 319 |
+
[Hier kannst du ausführliche Erklärungen zum Lösungsweg geben]
|
| 320 |
+
|
| 321 |
+
### 3. Additional context (if relevant):
|
| 322 |
+
[Weitere Informationen falls relevant]
|
| 323 |
+
"""
|
| 324 |
+
})
|
| 325 |
+
```<end_code>
|
| 326 |
+
|
| 327 |
+
Deine Antwort wird durch ein EXACT MATCH-Verfahren bewertet, wobei nur der Inhalt von "Task outcome (short version)" verglichen wird.
|
| 328 |
+
Bei Zahlen schreib keine Einheiten, bei Namen keine Artikel, und halte die Antwort so kurz wie möglich.
|
| 329 |
+
|
| 330 |
+
Füge alle diese Abschnitte in das final_answer-Tool ein, alles, was du nicht als Argument an final_answer übergibst, geht verloren.
|
| 331 |
+
Auch wenn deine Aufgabenlösung nicht erfolgreich ist, gib so viel Kontext wie möglich zurück, damit dein Manager auf dieses Feedback reagieren kann.
|
| 332 |
+
"report": |-
|
| 333 |
+
{{final_answer}}
|
| 334 |
+
|
| 335 |
+
# Replace the simple final_answer prompt with a structured one
|
| 336 |
+
"final_answer":
|
| 337 |
+
"pre_messages": "Use this tool to provide the final answer to the task in the required format."
|
| 338 |
+
"post_messages": "Final answer provided."
|
requirements.txt
CHANGED
|
@@ -1,2 +1,8 @@
|
|
| 1 |
gradio
|
| 2 |
-
requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
gradio
|
| 2 |
+
requests
|
| 3 |
+
smolagents
|
| 4 |
+
duckduckgo-search
|
| 5 |
+
pytz
|
| 6 |
+
PyYAML
|
| 7 |
+
huggingface_hub
|
| 8 |
+
markdownify
|
tools/final_answer.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
from smolagents.tools import Tool
|
| 3 |
+
|
| 4 |
+
class FinalAnswerTool(Tool):
|
| 5 |
+
name = "final_answer"
|
| 6 |
+
description = "Provides a final answer to the given problem in the exact format needed."
|
| 7 |
+
inputs = {'answer': {'type': 'any', 'description': 'The final answer to the problem'}}
|
| 8 |
+
output_type = "any"
|
| 9 |
+
|
| 10 |
+
def forward(self, answer: Any) -> Any:
|
| 11 |
+
# Wenn die Antwort ein Wörterbuch ist, versuchen wir, die strukturierte Antwort zu extrahieren
|
| 12 |
+
if isinstance(answer, dict) and 'answer' in answer:
|
| 13 |
+
answer = answer['answer']
|
| 14 |
+
|
| 15 |
+
# Wenn die Antwort ein langer Text mit Abschnitten ist, versuchen wir, die kurze Version zu extrahieren
|
| 16 |
+
if isinstance(answer, str) and "### 1. Task outcome (short version):" in answer:
|
| 17 |
+
# Extrahiere die kurze Antwort
|
| 18 |
+
short_answer_start = answer.find("### 1. Task outcome (short version):") + len("### 1. Task outcome (short version):")
|
| 19 |
+
|
| 20 |
+
# Suche nach dem Ende der kurzen Antwort (dem Beginn des nächsten Abschnitts)
|
| 21 |
+
next_section = answer.find("### 2.", short_answer_start)
|
| 22 |
+
if next_section != -1:
|
| 23 |
+
short_answer = answer[short_answer_start:next_section].strip()
|
| 24 |
+
else:
|
| 25 |
+
short_answer = answer[short_answer_start:].strip()
|
| 26 |
+
|
| 27 |
+
# Entferne mögliche Formatierungen
|
| 28 |
+
short_answer = short_answer.strip()
|
| 29 |
+
return short_answer
|
| 30 |
+
|
| 31 |
+
return answer
|
| 32 |
+
|
| 33 |
+
def __init__(self, *args, **kwargs):
|
| 34 |
+
self.is_initialized = False
|