Spaces:
Sleeping
Sleeping
Commit ·
c5afa64
1
Parent(s): 9a8c112
Style the code and make it local runnable
Browse filesFiles changed (9)
- .gitignoreAdded+173
- Gradio_UI.py+64-21
- README.md+9
- app.py+30-14
- requirements.txt+5
- tools/__init__.pyAdded+5
- tools/final_answer.py+4-1
- tools/visit_webpage.py+5-1
- tools/web_search.py+8-2
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173.gradio
# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# UV# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.#uv.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control#poetry.lock
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.#pdm.lock# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it# in version control.# https://pdm.fming.dev/latest/usage/project/#working-with-version-control.pdm.toml.pdm-python.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.#.idea/
# PyPI configuration file.pypirc18 unmodified lines192021222223242526272829307 unmodified lines383940413642434445461 unmodified line48495044454651525354555657585960616213 unmodified lines767778666779808182838485868719 unmodified lines107108109931101111121131141151161171 unmodified line1191201211011221231241251261271281291 unmodified line13113213310913413513613713813914014111311411511614214314414514614711914814915015115215315415516 unmodified lines17217317414217517617717817918026 unmodified lines20720820917521021121221321421563 unmodified lines27928028124528228328428528624828728828929029129225 unmodified lines3183193202803213223233243253269 unmodified lines33633733829633918 unmodified linesimport shutilfrom typing import Optional
from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_typesfrom smolagents.agent_types import ( AgentAudio, AgentImage, AgentText, handle_agent_output_types,)from smolagents.agents import ActionStep, MultiStepAgentfrom smolagents.memory import MemoryStepfrom smolagents.utils import _is_package_available7 unmodified lines
if isinstance(step_log, ActionStep): # Output the step number step_number = ( step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else "" f"Step {step_log.step_number}" if step_log.step_number is not None else "" ) yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
# First yield the thought/reasoning from the LLM1 unmodified line # Clean up the LLM output model_output = step_log.model_output.strip() # Remove any trailing <end_code> and extra backticks, handling multiple possible formats model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code> model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>``` model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code> model_output = re.sub( r"```\s*<end_code>", "```", model_output ) # handles ```<end_code> model_output = re.sub( r"<end_code>\s*```", "```", model_output ) # handles <end_code>``` model_output = re.sub( r"```\s*\n\s*<end_code>", "```", model_output ) # handles ```\n<end_code> model_output = model_output.strip() yield gr.ChatMessage(role="assistant", content=model_output)
13 unmodified lines
if used_code: # Clean up the content by removing any end code tags content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags content = re.sub( r"```.*?\n", "", content ) # Remove existing code blocks content = re.sub( r"\s*<end_code>\s*", "", content ) # Remove end_code tags content = content.strip() if not content.startswith("```python"): content = f"```python\n{content}\n```"19 unmodified lines yield gr.ChatMessage( role="assistant", content=f"{log_content}", metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"}, metadata={ "title": "📝 Execution Logs", "parent_id": parent_id, "status": "done", }, )
# Nesting any errors under the tool call1 unmodified line yield gr.ChatMessage( role="assistant", content=str(step_log.error), metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"}, metadata={ "title": "💥 Error", "parent_id": parent_id, "status": "done", }, )
# Update parent message metadata to done status without yielding a new message1 unmodified line
# Handle standalone errors but not from tool calls elif hasattr(step_log, "error") and step_log.error is not None: yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"}) yield gr.ChatMessage( role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"}, )
# Calculate duration and token information step_footnote = f"{step_number}" if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"): token_str = ( f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}" ) if hasattr(step_log, "input_token_count") and hasattr( step_log, "output_token_count" ): token_str = f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}" step_footnote += token_str if hasattr(step_log, "duration"): step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None step_duration = ( f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None ) step_footnote += step_duration step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """ yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")16 unmodified lines total_input_tokens = 0 total_output_tokens = 0
for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args): for step_log in agent.run( task, stream=True, reset=reset_agent_memory, additional_args=additional_args ): # Track tokens if model provides them if hasattr(agent.model, "last_input_token_count"): total_input_tokens += agent.model.last_input_token_count26 unmodified lines content={"path": final_answer.to_string(), "mime_type": "audio/wav"}, ) else: yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}") yield gr.ChatMessage( role="assistant", content=f"**Final answer:** {str(final_answer)}" )
class GradioUI:63 unmodified lines sanitized_name = "".join(sanitized_name)
# Save the uploaded file to the specified folder file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name)) file_path = os.path.join( self.file_upload_folder, os.path.basename(sanitized_name) ) shutil.copy(file.name, file_path)
return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path] return gr.Textbox( f"File uploaded: {file_path}", visible=True ), file_uploads_log + [file_path]
def log_user_message(self, text_input, file_uploads_log): return (25 unmodified lines # If an upload folder is provided, enable the upload feature if self.file_upload_folder is not None: upload_file = gr.File(label="Upload a file") upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False) upload_status = gr.Textbox( label="Upload Status", interactive=False, visible=False ) upload_file.change( self.upload_file, [upload_file, file_uploads_log],9 unmodified lines demo.launch(debug=True, share=True, **kwargs)
__all__ = ["stream_to_gradio", "GradioUI"]__all__ = ["stream_to_gradio", "GradioUI"]15 unmodified lines16171819202122232425262715 unmodified lines---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
---
- [First Agent Template - a Hugging Face Space by daviddwlee84](https://huggingface.co/spaces/daviddwlee84/First_Agent)
```bash# BUG: somehow failed to inference locallypython app.py```112345667891011121314151617181213141920212223242526272829303112 unmodified lines4445463940414247484950515253545556575859496061516263646566676869547071727374757661777879806581from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,toolfrom smolagents import CodeAgent, HfApiModel, load_tool, toolimport datetimeimport requestsimport pytzimport yamlfrom tools.final_answer import FinalAnswerToolfrom tools import ( FinalAnswerTool, VisitWebpageTool, DuckDuckGoSearchTool, # This is also built-in in smolagents)
from Gradio_UI import GradioUI
# Below is an example of a tool that does nothing. Amaze us with your creativity !@tooldef my_cutom_tool( arg1: str, arg2: intdef my_cutom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type #Keep this format for the description / args / args description but feel free to modify the tool """A tool that does nothing yet ) -> str: # it's import to specify the return type # Keep this format for the description / args / args description but feel free to modify the tool """A tool that does nothing yet Args: arg1: the first argument arg2: the second argument """ return "What magic will you build ?"
@tooldef get_current_time_in_timezone(timezone: str) -> str: """A tool that fetches the current local time in a specified timezone.12 unmodified lines
final_answer = FinalAnswerTool()model = HfApiModel(max_tokens=2096,temperature=0.5,model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud',# it is possible that this model may be overloadedcustom_role_conversions=None, max_tokens=2096, temperature=0.5, model_id="https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud", # it is possible that this model may be overloaded custom_role_conversions=None,)
# Import tool from Hubimage_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
duckduckgo_tool = DuckDuckGoSearchTool()visit_webpage_tool = VisitWebpageTool()
with open("prompts.yaml", 'r') as stream:with open("prompts.yaml", "r") as stream: prompt_templates = yaml.safe_load(stream)
agent = CodeAgent( model=model, tools=[ final_answer, image_generation_tool, duckduckgo_tool, visit_webpage_tool, tools=[final_answer], ## add your tools here (don't remove final answer) ], # Add your tools here (don't remove final answer) max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates prompt_templates=prompt_templates,)
GradioUI(agent).launch()GradioUI(agent).launch()2 unmodified lines3456789102 unmodified linesrequestsduckduckgo_searchpandas
# Local developmentgradio# ImportError: Using SOCKS proxy, but the 'socksio' package is not installed. Make sure to install httpx using `pip install httpx[socks]`httpx[socks]12345from .visit_webpage import VisitWebpageToolfrom .final_answer import FinalAnswerToolfrom .web_search import DuckDuckGoSearchTool
__all__ = ["VisitWebpageTool", "FinalAnswerTool", "DuckDuckGoSearchTool"]123456778910111213from typing import Any, Optionalfrom smolagents.tools import Tool
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'}} inputs = { "answer": {"type": "any", "description": "The final answer to the problem"} } output_type = "any"
def forward(self, answer: Any) -> Any:2 unmodified lines34567891011101213141516172 unmodified linesimport requestsimport markdownifyimport smolagentsimport re
class VisitWebpageTool(Tool): name = "visit_webpage" description = "Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages." inputs = {'url': {'type': 'string', 'description': 'The url of the webpage to visit.'}} inputs = { "url": {"type": "string", "description": "The url of the webpage to visit."} } output_type = "string"
def forward(self, url: str) -> str:1 unmodified line234567889101112131411 unmodified lines2627282629303132331 unmodified linefrom smolagents.tools import Toolimport duckduckgo_search
class DuckDuckGoSearchTool(Tool): name = "web_search" description = "Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results." inputs = {'query': {'type': 'string', 'description': 'The search query to perform.'}} inputs = { "query": {"type": "string", "description": "The search query to perform."} } output_type = "string"
def __init__(self, max_results=10, **kwargs):11 unmodified lines results = self.ddgs.text(query, max_results=self.max_results) if len(results) == 0: raise Exception("No results found! Try a less restrictive/shorter query.") postprocessed_results = [f"[{result['title']}]({result['href']})\n{result['body']}" for result in results] postprocessed_results = [ f"[{result['title']}]({result['href']})\n{result['body']}" for result in results ] return "## Search Results\n\n" + "\n\n".join(postprocessed_results).gitignoreAdded+173
Gradio_UI.py+64-21
README.md+9
app.py+30-14
requirements.txt+5
tools/__init__.pyAdded+5
tools/final_answer.py+4-1
tools/visit_webpage.py+5-1
tools/web_search.py+8-2