Spaces:
Running on Zero
Running on Zero
Deploy ArkAssistant smolagent (Hugging Face Agents Course Unit 1)
Browse filesFiles changed (9)
- .agents/skills/deploy-space/SKILL.md+1-1
- AGENTS.md+10-6
- app.py+51-96
- prompts.yaml+2-2
- requirements.txt+7-7
- test_agent.py+68-61
- tools/get_current_time_in_timezone.py+17-20
- tools/get_weather.py+21-24
- tools/search_wikipedia.py+28-32
23 unmodified lines2425262728293023 unmodified lines```3. **Dependency Check**:Ensure all imported packages in `tools/` and `app.py` (e.g., `markdownify`, `smolagents`, `ddgs`, `litellm`) are declared in `requirements.txt`.4. **Ignore Patterns**:Verify that sensitive files (`.env`), cache folders (`__pycache__`, `.gradio`), and the virtual environment (`.venv`) are listed in `deploy_space.py`'s `ignore_patterns`.23 unmodified lines2425262728293023 unmodified lines```3. **Dependency Check**:Ensure all imported packages in `tools/` and `app.py` (e.g., `markdownify`, `smolagents`, `ddgs`) are declared in `requirements.txt`.4. **Ignore Patterns**:Verify that sensitive files (`.env`), cache folders (`__pycache__`, `.gradio`), and the virtual environment (`.venv`) are listed in `deploy_space.py`'s `ignore_patterns`.
27 unmodified lines282930313233345 unmodified lines404142434445464748495027 unmodified lines## Environment & Commands- **Local Virtual Environment**: `.venv/bin/python`- **Sanity Check All Tools (Fast, No LLM)**:```bash5 unmodified lines.venv/bin/python test_agent.py "What is the capital of Japan and what is the weather there?"```- **Run CLI Agent Query with Local Ollama (Offline)**:```bashUSE_OLLAMA=true .venv/bin/python test_agent.py "What is the time in UTC?"```- **Run Gradio Web UI Locally**:```bash.venv/bin/python app.py27 unmodified lines282930313233343536373839404142435 unmodified lines49505152535427 unmodified lines## Environment & CommandsCloud inference only. `HF_TOKEN` and `MODEL_ID` are configured in `.env`;local Ollama execution is intentionally disabled. Hugging Face InferenceProviders require available credits or a PRO plan; without them the API returnsHTTP 402 before the agent can start.- **Create the project virtual environment**:```bashuv venv .venvuv pip install --python .venv/bin/python -r requirements.txt```- **Sanity Check All Tools (Fast, No LLM)**:```bash5 unmodified lines.venv/bin/python test_agent.py "What is the capital of Japan and what is the weather there?"```- **Run Gradio Web UI Locally**:```bash.venv/bin/python app.py
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261279 unmodified lines1371381391401411421434 unmodified lines148149150151152153154155156157import datetimeimport osfrom urllib.parse import quoteimport pytzimport requestsimport yamlfrom dotenv import load_dotenvfrom smolagents import CodeAgent, DuckDuckGoSearchTool, load_tool, toolfrom tools.final_answer import FinalAnswerToolfrom tools.visit_webpage import VisitWebpageToolfrom Gradio_UI import GradioUIload_dotenv()# --- Custom Tools ---@tooldef get_current_time_in_timezone(timezone: str) -> str:"""A tool that fetches the current local time in a specified timezone.Args:timezone: A string representing a valid IANA timezone (e.g., 'America/New_York', 'Europe/Paris', 'Asia/Kolkata', 'UTC')."""try:import datetimeimport pytztz = pytz.timezone(timezone)local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")return f"The current local time in {timezone} is: {local_time}"except Exception as e:return f"Error fetching time for timezone '{timezone}': {str(e)}"@tooldef get_weather(location: str) -> str:"""Fetches the current live weather report and temperature for a given city or location.Args:location: The name of the city or location (e.g., 'Paris', 'Tokyo', 'San Francisco')."""try:import requestsfrom urllib.parse import quoteencoded_loc = quote(location)url = f"https://wttr.in/{encoded_loc}?format=%C+%t+(feels+like+%f)+wind:+%w"headers = {"User-Agent": "HF-Agents-Course-ArkAssistant/1.0"}resp = requests.get(url, headers=headers, timeout=10)if resp.status_code == 200 and resp.text:return f"Weather for {location}: {resp.text.strip()}"return f"Could not retrieve weather for {location} (status code {resp.status_code})."except Exception as e:return f"Error fetching weather for '{location}': {str(e)}"@tooldef search_wikipedia(query: str) -> str:"""Fetches an encyclopedic summary of a topic from Wikipedia.Args:query: The subject or topic name to search on Wikipedia (e.g., 'Alan Turing', 'Artificial intelligence')."""try:import requestsfrom urllib.parse import quoteencoded_query = quote(query)url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{encoded_query}"headers = {"User-Agent": "HF-Agents-Course-ArkAssistant/1.0"}resp = requests.get(url, headers=headers, timeout=10)if resp.status_code == 200:data = resp.json()extract = data.get("extract", "")title = data.get("title", query)if extract:return f"**{title}**: {extract}"return f"No extract available for '{query}'."elif resp.status_code == 404:return f"No Wikipedia article found for '{query}'."else:return f"Wikipedia query returned status code {resp.status_code}."except Exception as e:return f"Error querying Wikipedia for '{query}': {str(e)}"# --- Core Tools & Agent Setup ---final_answer = FinalAnswerTool()web_search = DuckDuckGoSearchTool()visit_webpage = VisitWebpageTool()# Image generation tool from Hugging Face Hubimage_generation_tool = Nonetry:hf_token = os.getenv("HF_TOKEN")image_generation_tool = load_tool("agents-course/text-to-image",trust_remote_code=True,token=hf_token)except Exception as e:print(f"Notice: text-to-image tool could not be loaded: {e}")# Model Configurationtry:from smolagents import HfApiModel as HfModelexcept ImportError:from smolagents import InferenceClientModel as HfModelhf_token = os.getenv("HF_TOKEN")use_ollama = os.getenv("USE_OLLAMA", "").lower() in ("true", "1")if use_ollama or (not hf_token and os.getenv("OLLAMA_ENABLED", "").lower() in ("true", "1")):print("Using local Ollama model for agent execution...")from smolagents import LiteLLMModelmodel = LiteLLMModel(model_id=os.getenv("OLLAMA_MODEL", "ollama_chat/qwen2.5-coder:3b"),api_base=os.getenv("OLLAMA_API_BASE", "http://127.0.0.1:11434"),num_ctx=8192)else:model_id = os.getenv("MODEL_ID", "Qwen/Qwen2.5-Coder-32B-Instruct")model_kwargs = {"max_tokens": 2096,"temperature": 0.5,"model_id": model_id,"custom_role_conversions": None,}if hf_token:model_kwargs["token"] = hf_tokenmodel = HfModel(**model_kwargs)# Load prompt templatesprompts_file = os.path.join(os.path.dirname(__file__), "prompts.yaml")9 unmodified linesmax_steps=5,verbosity_level=1,name="web_researcher",description="A specialist researcher that searches DuckDuckGo, queries Wikipedia, and reads webpage content to gather accurate facts and summaries.",prompt_templates=prompt_templates)4 unmodified linesmax_steps=4,verbosity_level=1,name="local_info_specialist",description="A specialist agent that fetches real-time live weather reports and calculates current time in timezones worldwide.",prompt_templates=prompt_templates)# Manager Agent: Coordinates specialists and synthesizes the final responsemanager_tools = [final_answer]if image_generation_tool is not None:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960619 unmodified lines717273747576774 unmodified lines828384858687888990919293949596979899100101102103104105106107108109110111112import osimport yamlfrom dotenv import load_dotenvfrom smolagents import CodeAgent, InferenceClientModel, load_toolfrom Gradio_UI import GradioUIfrom tools.final_answer import FinalAnswerToolfrom tools.get_current_time_in_timezone import get_current_time_in_timezonefrom tools.get_weather import get_weatherfrom tools.search_wikipedia import search_wikipediafrom tools.visit_webpage import VisitWebpageToolfrom tools.web_search import DuckDuckGoSearchToolload_dotenv()# --- Core Tools & Agent Setup ---final_answer = FinalAnswerTool()web_search = DuckDuckGoSearchTool()visit_webpage = VisitWebpageTool()hf_token = os.getenv("HF_TOKEN")if not hf_token:raise RuntimeError("HF_TOKEN is required. Local model execution is disabled in this project.")# Image generation tool from Hugging Face Hubimage_generation_tool = Nonetry:image_generation_tool = load_tool("agents-course/text-to-image",trust_remote_code=True,token=hf_token,)except Exception as e:print(f"Notice: text-to-image tool could not be loaded: {e}")# Model configuration (cloud by default; Ollama supported for local learning/testing)model_id = os.getenv("MODEL_ID", "Qwen/Qwen2.5-Coder-32B-Instruct")if "ollama" in model_id.lower():from smolagents import LiteLLMModelmodel = LiteLLMModel(model_id=model_id,api_base=os.getenv("OLLAMA_API_BASE", "http://127.0.0.1:11434"),num_ctx=int(os.getenv("OLLAMA_NUM_CTX", "8192")),temperature=0.5,)else:model = InferenceClientModel(model_id=model_id,token=hf_token,max_tokens=2096,temperature=0.5,custom_role_conversions=None,)# Load prompt templatesprompts_file = os.path.join(os.path.dirname(__file__), "prompts.yaml")9 unmodified linesmax_steps=5,verbosity_level=1,name="web_researcher",description="A specialist researcher that searches DuckDuckGo, queries Wikipedia, and reads webpage content to gather accurate facts and summaries. ALWAYS call this agent with a 'task' argument, e.g. web_researcher(task='Find the capital of Japan').",prompt_templates=prompt_templates)4 unmodified linesmax_steps=4,verbosity_level=1,name="local_info_specialist",description="A specialist agent that fetches real-time live weather reports and calculates current time in timezones worldwide. ALWAYS call this agent with a 'task' argument, e.g. local_info_specialist(task='Get current weather in Tokyo'). Never call weather() or get_weather() directly from the manager.",prompt_templates=prompt_templates)# Make managed agents tolerant of common argument names (query/question/etc.)def _adapt_managed_agent(agent):original_call = agent.__call__def _call(task=None, **kwargs):if task is None:for key in ("task", "query", "question", "request", "prompt"):if key in kwargs:task = kwargs.pop(key)breakif task is None and kwargs:task = list(kwargs.values())[0]kwargs = {}return original_call(task, **kwargs)agent.__call__ = _callreturn agentresearch_agent = _adapt_managed_agent(research_agent)local_info_agent = _adapt_managed_agent(local_info_agent)# Manager Agent: Coordinates specialists and synthesizes the final responsemanager_tools = [final_answer]if image_generation_tool is not None:
218 unmodified lines219220221222223224225226218 unmodified lines{%- if managed_agents and managed_agents.values() | list %}You can also give tasks to team members.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.Given that this team member is a real human, you should be very verbose in your request.Here is a list of the team members that you can call:{%- for agent in managed_agents.values() %}- {{ agent.name }}: {{ agent.description }}218 unmodified lines219220221222223224225226218 unmodified lines{%- if managed_agents and managed_agents.values() | list %}You can also give tasks to team members.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.Given that this team member is a real human, you should be very verbose in your task.Here is a list of the team members that you can call:{%- for agent in managed_agents.values() %}- {{ agent.name }}: {{ agent.description }}
12345678910markdownifysmolagentsrequestsduckduckgo_searchpandaspytzpython-dotenvpillowlitellmddgs12345678910ddgsgradio>=5.23,<7huggingface_hubmarkdownifypandaspillowpython-dotenvpytzrequestssmolagents>=1.26,<2
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394#!/usr/bin/env python3"""CLI Test Runner for ArkAssistant smolagentUsage:# Run a test query against the manager agent:.venv/bin/python test_agent.py "What is the capital of France and what is the current time there?"# Run with local Ollama offline model:USE_OLLAMA=true .venv/bin/python test_agent.py "What is the weather in London?"# Sanity check all tools without calling the LLM:.venv/bin/python test_agent.py --test-tools"""import osimport sysdef run_tools_sanity():print("=" * 60)print("🔬 Running Sanity Check on ArkAssistant Tools (No LLM Calls)")print("=" * 60)# 1. Weathertry:from app import get_weatherw = get_weather("London")print(f"✅ Weather Tool: {w[:80]}...")except Exception as e:print(f"❌ Weather Tool Failed: {e}")# 2. Timezonetry:from app import get_current_time_in_timezonet = get_current_time_in_timezone("UTC")print(f"✅ Timezone Tool: {t}")except Exception as e:print(f"❌ Timezone Tool Failed: {e}")# 3. Wikipediatry:from app import search_wikipediawiki = search_wikipedia("Alan Turing")print(f"✅ Wikipedia Tool: {wiki[:80]}...")except Exception as e:print(f"❌ Wikipedia Tool Failed: {e}")# 4. Visit Webpagetry:from app import visit_webpageres = visit_webpage("https://httpbin.org/html")print(f"✅ Visit Webpage Tool: Extracted {len(res)} characters.")except Exception as e:print(f"❌ Visit Webpage Tool Failed: {e}")# 5. DuckDuckGo Web Searchtry:from app import web_searchsr = web_search("smolagents Hugging Face")print(f"✅ Web Search Tool: {sr[:80]}...")except Exception as e:print(f"❌ Web Search Tool Failed: {e}")print("=" * 60)print("All tool sanity checks complete.")print("=" * 60)def main():args = sys.argv[1:]if "--test-tools" in args:run_tools_sanity()return# Check for prompt argumentprompt = " ".join([a for a in args if not a.startswith("--")])if not prompt:prompt = "What is the current time in UTC and what is the weather in Paris?"print(f"No prompt provided. Using default test prompt:\n '{prompt}'\n")print(f"🚀 Initializing ArkAssistant Agent...")from app import agentprint(f"🤖 Running Agent Task: \"{prompt}\"")print("-" * 60)try:response = agent.run(prompt)print("-" * 60)print(f"\n🎯 Agent Final Answer:\n{response}")except Exception as e:print(f"\n❌ Error during agent execution: {e}")sys.exit(1)if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101#!/usr/bin/env python3"""CLI test runner for ArkAssistant.Usage:# Run a test query against the manager agent:.venv/bin/python test_agent.py "What is the capital of France and what is the current time there?"# Sanity check all tools without calling the LLM:.venv/bin/python test_agent.py --test-toolsThe project uses the Hugging Face Inference API and requires HF_TOKEN in .env."""import sysfrom tools.get_current_time_in_timezone import get_current_time_in_timezonefrom tools.get_weather import get_weatherfrom tools.search_wikipedia import search_wikipediafrom tools.visit_webpage import VisitWebpageToolfrom tools.web_search import DuckDuckGoSearchTooldef _require_result(result: str) -> str:text = str(result).strip()if not text:raise RuntimeError("tool returned an empty result")if text.lower().startswith("error"):raise RuntimeError(text)return textdef run_tools_sanity() -> int:print("=" * 60)print("🔬 Running Sanity Check on ArkAssistant Tools (No LLM Calls)")print("=" * 60)visit_webpage = VisitWebpageTool()web_search = DuckDuckGoSearchTool()failures: list[str] = []checks = [("Weather", lambda: get_weather("London")),("Timezone", lambda: get_current_time_in_timezone("UTC")),("Wikipedia", lambda: search_wikipedia("Alan Turing")),("Visit Webpage", lambda: visit_webpage("https://httpbin.org/html")),("Web Search", lambda: web_search("smolagents Hugging Face")),]for name, check in checks:try:result = _require_result(check())preview = result.replace("\n", " ")[:100]print(f"✅ {name} Tool: {preview}")except Exception as exc:failures.append(f"{name}: {exc}")print(f"❌ {name} Tool Failed: {exc}")print("=" * 60)if failures:print(f"❌ {len(failures)} tool check(s) failed.")for failure in failures:print(f" - {failure}")return 1print("✅ All tool sanity checks passed.")return 0def main() -> int:args = sys.argv[1:]if "--test-tools" in args:return run_tools_sanity()prompt = " ".join(arg for arg in args if not arg.startswith("--"))if not prompt:prompt = "What is the current time in UTC and what is the weather in Paris?"print(f"No prompt provided. Using default test prompt:\n '{prompt}'\n")print("🚀 Initializing ArkAssistant Agent...")try:from app import agentprint(f"🤖 Running Agent Task: \"{prompt}\"")print("-" * 60)response = agent.run(prompt)print("-" * 60)print(f"\n🎯 Agent Final Answer:\n{response}")return 0except Exception as exc:message = str(exc)print(f"\n❌ Error during agent execution: {message}")if "402" in message or "Payment Required" in message:print("Hint: Hugging Face Inference has no available credits. ""Add credits/PRO or configure another cloud provider in .env.")return 1if __name__ == "__main__":sys.exit(main())
12345678910111213141516171819202122from smolagents import Toolfrom typing import Any, Optionalclass SimpleTool(Tool):name = "get_current_time_in_timezone"description = "A tool that fetches the current local time in a specified timezone."inputs = {'timezone': {'type': 'string', 'description': "A string representing a valid IANA timezone (e.g., 'America/New_York', 'Europe/Paris', 'Asia/Kolkata', 'UTC')."}}output_type = "string"def forward(self, timezone: str) -> str:"""A tool that fetches the current local time in a specified timezone.Args:timezone: A string representing a valid IANA timezone (e.g., 'America/New_York', 'Europe/Paris', 'Asia/Kolkata', 'UTC')."""try:import datetimeimport pytztz = pytz.timezone(timezone)local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")return f"The current local time in {timezone} is: {local_time}"except Exception as e:return f"Error fetching time for timezone '{timezone}': {str(e)}"12345678910111213141516171819import datetimeimport pytzfrom smolagents import tool@tooldef get_current_time_in_timezone(timezone: str) -> str:"""A tool that fetches the current local time in a specified timezone.Args:timezone: A valid IANA timezone (e.g., 'America/New_York', 'Europe/Paris', 'Asia/Kolkata', 'UTC')."""try:tz = pytz.timezone(timezone)local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")return f"The current local time in {timezone} is: {local_time}"except Exception as e:return f"Error fetching time for timezone '{timezone}': {str(e)}"
1234567891011121314151617181920212223242526from smolagents import Toolfrom typing import Any, Optionalclass SimpleTool(Tool):name = "get_weather"description = "Fetches the current live weather report and temperature for a given city or location."inputs = {'location': {'type': 'string', 'description': "The name of the city or location (e.g., 'Paris', 'Tokyo', 'San Francisco')."}}output_type = "string"def forward(self, location: str) -> str:"""Fetches the current live weather report and temperature for a given city or location.Args:location: The name of the city or location (e.g., 'Paris', 'Tokyo', 'San Francisco')."""try:import requestsfrom urllib.parse import quoteencoded_loc = quote(location)url = f"https://wttr.in/{encoded_loc}?format=%C+%t+(feels+like+%f)+wind:+%w"headers = {"User-Agent": "HF-Agents-Course-ArkAssistant/1.0"}resp = requests.get(url, headers=headers, timeout=10)if resp.status_code == 200 and resp.text:return f"Weather for {location}: {resp.text.strip()}"return f"Could not retrieve weather for {location} (status code {resp.status_code})."except Exception as e:return f"Error fetching weather for '{location}': {str(e)}"1234567891011121314151617181920212223from urllib.parse import quoteimport requestsfrom smolagents import tool@tooldef get_weather(location: str) -> str:"""Fetches the current live weather report and temperature for a given city or location.Args:location: The name of the city or location (e.g., 'Paris', 'Tokyo', 'San Francisco')."""try:encoded_loc = quote(location)url = f"https://wttr.in/{encoded_loc}?format=%C+%t+(feels+like+%f)+wind:+%w"headers = {"User-Agent": "HF-Agents-Course-ArkAssistant/1.0"}resp = requests.get(url, headers=headers, timeout=10)if resp.status_code == 200 and resp.text:return f"Weather for {location}: {resp.text.strip()}"return f"Could not retrieve weather for {location} (status code {resp.status_code})."except Exception as e:return f"Error fetching weather for '{location}': {str(e)}"
12345678910111213141516171819202122232425262728293031323334from smolagents import Toolfrom typing import Any, Optionalclass SimpleTool(Tool):name = "search_wikipedia"description = "Fetches an encyclopedic summary of a topic from Wikipedia."inputs = {'query': {'type': 'string', 'description': "The subject or topic name to search on Wikipedia (e.g., 'Alan Turing', 'Artificial intelligence')."}}output_type = "string"def forward(self, query: str) -> str:"""Fetches an encyclopedic summary of a topic from Wikipedia.Args:query: The subject or topic name to search on Wikipedia (e.g., 'Alan Turing', 'Artificial intelligence')."""try:import requestsfrom urllib.parse import quoteencoded_query = quote(query)url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{encoded_query}"headers = {"User-Agent": "HF-Agents-Course-ArkAssistant/1.0"}resp = requests.get(url, headers=headers, timeout=10)if resp.status_code == 200:data = resp.json()extract = data.get("extract", "")title = data.get("title", query)if extract:return f"**{title}**: {extract}"return f"No extract available for '{query}'."elif resp.status_code == 404:return f"No Wikipedia article found for '{query}'."else:return f"Wikipedia query returned status code {resp.status_code}."except Exception as e:return f"Error querying Wikipedia for '{query}': {str(e)}"123456789101112131415161718192021222324252627282930from urllib.parse import quoteimport requestsfrom smolagents import tool@tooldef search_wikipedia(query: str) -> str:"""Fetches an encyclopedic summary of a topic from Wikipedia.Args:query: The subject or topic name to search on Wikipedia (e.g., 'Alan Turing', 'Artificial intelligence')."""try:encoded_query = quote(query)url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{encoded_query}"headers = {"User-Agent": "HF-Agents-Course-ArkAssistant/1.0"}resp = requests.get(url, headers=headers, timeout=10)if resp.status_code == 200:data = resp.json()extract = data.get("extract", "")title = data.get("title", query)if extract:return f"**{title}**: {extract}"return f"No extract available for '{query}'."if resp.status_code == 404:return f"No Wikipedia article found for '{query}'."return f"Wikipedia query returned status code {resp.status_code}."except Exception as e:return f"Error querying Wikipedia for '{query}': {str(e)}"
.agents/skills/deploy-space/SKILL.md+1-1
AGENTS.md+10-6
app.py+51-96
prompts.yaml+2-2
requirements.txt+7-7
test_agent.py+68-61
tools/get_current_time_in_timezone.py+17-20
tools/get_weather.py+21-24
tools/search_wikipedia.py+28-32