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 lines192021222324257 unmodified lines333435363738391 unmodified line41424344454647484913 unmodified lines636465666768697019 unmodified lines909192939495961 unmodified line98991001011021031041 unmodified line10610710810911011111211311411511611711811912012112216 unmodified lines13914014114214314414526 unmodified lines17217317417517617717863 unmodified lines24224324424524624724824925025125 unmodified lines2772782792802812822839 unmodified lines29329429529618 unmodified linesimport shutilfrom typing import Optionalfrom smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_typesfrom smolagents.agents import ActionStep, MultiStepAgentfrom smolagents.memory import MemoryStepfrom smolagents.utils import _is_package_available7 unmodified linesif isinstance(step_log, ActionStep):# Output the step numberstep_number = 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 outputmodel_output = step_log.model_output.strip()# Remove any trailing <end_code> and extra backticks, handling multiple possible formatsmodel_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 linesif used_code:# Clean up the content by removing any end code tagscontent = re.sub(r"```.*?\n", "", content) # Remove existing code blockscontent = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tagscontent = content.strip()if not content.startswith("```python"):content = f"```python\n{content}\n```"19 unmodified linesyield gr.ChatMessage(role="assistant",content=f"{log_content}",metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},)# Nesting any errors under the tool call1 unmodified lineyield gr.ChatMessage(role="assistant",content=str(step_log.error),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 callselif hasattr(step_log, "error") and step_log.error is not None:yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})# Calculate duration and token informationstep_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:,}")step_footnote += token_strif hasattr(step_log, "duration"):step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else Nonestep_footnote += step_durationstep_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")16 unmodified linestotal_input_tokens = 0total_output_tokens = 0for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):# Track tokens if model provides themif hasattr(agent.model, "last_input_token_count"):total_input_tokens += agent.model.last_input_token_count26 unmodified linescontent={"path": final_answer.to_string(), "mime_type": "audio/wav"},)else:yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")class GradioUI:63 unmodified linessanitized_name = "".join(sanitized_name)# Save the uploaded file to the specified folderfile_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]def log_user_message(self, text_input, file_uploads_log):return (25 unmodified lines# If an upload folder is provided, enable the upload featureif 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_file.change(self.upload_file,[upload_file, file_uploads_log],9 unmodified linesdemo.launch(debug=True, share=True, **kwargs)__all__ = ["stream_to_gradio", "GradioUI"]18 unmodified lines1920212223242526272829307 unmodified lines3839404142434445461 unmodified line48495051525354555657585960616213 unmodified lines76777879808182838485868719 unmodified lines1071081091101111121131141151161171 unmodified line1191201211221231241251261271281291 unmodified line13113213313413513613713813914014114214314414514614714814915015115215315415516 unmodified lines17217317417517617717817918026 unmodified lines20720820921021121221321421563 unmodified lines27928028128228328428528628728828929029129225 unmodified lines3183193203213223233243253269 unmodified lines33633733833918 unmodified linesimport shutilfrom typing import Optionalfrom 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 linesif isinstance(step_log, ActionStep):# Output the step numberstep_number = (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 outputmodel_output = step_log.model_output.strip()# Remove any trailing <end_code> and extra backticks, handling multiple possible formatsmodel_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 linesif used_code:# Clean up the content by removing any end code tagscontent = re.sub(r"```.*?\n", "", content) # Remove existing code blockscontent = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tagscontent = content.strip()if not content.startswith("```python"):content = f"```python\n{content}\n```"19 unmodified linesyield gr.ChatMessage(role="assistant",content=f"{log_content}",metadata={"title": "📝 Execution Logs","parent_id": parent_id,"status": "done",},)# Nesting any errors under the tool call1 unmodified lineyield gr.ChatMessage(role="assistant",content=str(step_log.error),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 callselif hasattr(step_log, "error") and step_log.error is not None:yield gr.ChatMessage(role="assistant",content=str(step_log.error),metadata={"title": "💥 Error"},)# Calculate duration and token informationstep_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:,}"step_footnote += token_strif hasattr(step_log, "duration"):step_duration = (f" | Duration: {round(float(step_log.duration), 2)}"if step_log.durationelse None)step_footnote += step_durationstep_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")16 unmodified linestotal_input_tokens = 0total_output_tokens = 0for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):# Track tokens if model provides themif hasattr(agent.model, "last_input_token_count"):total_input_tokens += agent.model.last_input_token_count26 unmodified linescontent={"path": final_answer.to_string(), "mime_type": "audio/wav"},)else:yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")class GradioUI:63 unmodified linessanitized_name = "".join(sanitized_name)# Save the uploaded file to the specified folderfile_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]def log_user_message(self, text_input, file_uploads_log):return (25 unmodified lines# If an upload folder is provided, enable the upload featureif 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_file.change(self.upload_file,[upload_file, file_uploads_log],9 unmodified linesdemo.launch(debug=True, share=True, **kwargs)__all__ = ["stream_to_gradio", "GradioUI"]
15 unmodified lines16171815 unmodified lines---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference15 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```
123456789101112131415161718192021222312 unmodified lines363738394041424344454647484950515253545556575859606162636465from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,toolimport datetimeimport requestsimport pytzimport yamlfrom tools.final_answer import FinalAnswerToolfrom 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: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 yetArgs:arg1: the first argumentarg2: 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 linesfinal_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,)# Import tool from Hubimage_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)with open("prompts.yaml", 'r') as stream:prompt_templates = yaml.safe_load(stream)agent = CodeAgent(model=model,tools=[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)GradioUI(agent).launch()1234567891011121314151617181920212223242526272829303112 unmodified lines4445464748495051525354555657585960616263646566676869707172737475767778798081from smolagents import CodeAgent, HfApiModel, load_tool, toolimport datetimeimport requestsimport pytzimport yamlfrom 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: 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 yetArgs:arg1: the first argumentarg2: 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 linesfinal_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,)# 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:prompt_templates = yaml.safe_load(stream)agent = CodeAgent(model=model,tools=[final_answer,image_generation_tool,duckduckgo_tool,visit_webpage_tool,], # 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,)GradioUI(agent).launch()
2 unmodified lines3452 unmodified linesrequestsduckduckgo_searchpandas2 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"]12345678910from typing import Any, Optionalfrom smolagents.tools import Toolclass 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:12345678910111213from typing import Any, Optionalfrom smolagents.tools import Toolclass 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:
2 unmodified lines3456789101112132 unmodified linesimport requestsimport markdownifyimport smolagentsclass 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.'}}output_type = "string"def forward(self, url: str) -> str:2 unmodified lines345678910111213141516172 unmodified linesimport requestsimport markdownifyimport smolagentsimport reclass 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."}}output_type = "string"def forward(self, url: str) -> str:
1 unmodified line23456789101111 unmodified lines23242526271 unmodified linefrom smolagents.tools import Toolimport duckduckgo_searchclass 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.'}}output_type = "string"def __init__(self, max_results=10, **kwargs):11 unmodified linesresults = 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]return "## Search Results\n\n" + "\n\n".join(postprocessed_results)1 unmodified line23456789101112131411 unmodified lines26272829303132331 unmodified linefrom smolagents.tools import Toolimport duckduckgo_searchclass 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."}}output_type = "string"def __init__(self, max_results=10, **kwargs):11 unmodified linesresults = 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]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