Spaces:
Runtime error
Runtime error
File size: 5,047 Bytes
4c2798e 9b5b26a c19d193 6aae614 f528b63 9b5b26a e54ddb0 4c2798e 9b5b26a 4c2798e 9b5b26a 4c2798e 1dffacd e54ddb0 8c9fc97 1dffacd 8c9fc97 d43153e 8c9fc97 1dffacd 9b5b26a ba7e21b 9b5b26a ba7e21b d43153e ba7e21b 9b5b26a ba7e21b 9b5b26a ba7e21b 8c01ffb 4c2798e 6aae614 d43153e 4c2798e ae7a494 d43153e 4c2798e e121372 d43153e 4c2798e d43153e 13d500a 8c01ffb 4c2798e 861422e 4c2798e 8c01ffb 8fe992b 8c9fc97 8c01ffb 861422e 8fe992b d43153e 8c01ffb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
import os
from tavily import TavilyClient
from Gradio_UI import GradioUI
import wikipedia
import textwrap
# Example tool template - can be modified for your needs
@tool
def my_custom_tool(arg1: str, arg2: int) -> str: # Return type specification is important
"""A tool that does nothing yet
Args:
arg1: the first argument
arg2: the second argument
"""
return "What magic will you build?"
@tool
def wiki_search(query: str, sentences: int = 3) -> str:
"""Search Wikipedia and return a summary of the topic.
Args:
query: The topic to search for on Wikipedia
sentences: Number of sentences to return in the summary (default: 3)
Returns:
str: A summary of the Wikipedia article
"""
try:
# Set language to English for consistency
wikipedia.set_lang("en")
# Search for the page
search_results = wikipedia.search(query)
if not search_results:
return f"No Wikipedia results found for: {query}"
try:
# Get the page
page = wikipedia.page(search_results[0], auto_suggest=False)
# Get summary and full URL
summary = wikipedia.summary(search_results[0], sentences=sentences, auto_suggest=False)
url = page.url
# Format the response
response = f"Wikipedia article: {page.title}\n"
response += f"URL: {url}\n\n"
response += f"Summary:\n{textwrap.fill(summary, width=80)}\n"
return response
except wikipedia.DisambiguationError as e:
# Handle disambiguation pages
options = e.options[:5] # Show first 5 options
response = f"'{query}' may refer to multiple topics. Here are some options:\n\n"
for i, option in enumerate(options, 1):
response += f"{i}. {option}\n"
return response
except Exception as e:
return f"Error searching Wikipedia: {str(e)}"
# @tool
# def tavily_search(query: str) -> str:
# """A tool that performs web search using Tavily API and formats the results.
# Args:
# query: The search query to look up
# Returns:
# str: A formatted summary of search results
# """
# try:
# client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
# search_result = client.search(query=query, search_depth="advanced")
# # Format the results in a user-friendly way
# summary = f"Here are the search results for: {query}\n\n"
# for result in search_result['results'][:5]: # Top 5 results
# summary += f"• {result['title']}\n"
# summary += f" Summary: {result['description'][:200]}...\n\n"
# return summary
# except Exception as e:
# return f"Error performing search: {str(e)}"
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""A tool that fetches and formats the current local time in a specified timezone.
Args:
timezone: A string representing a valid timezone (e.g., 'America/New_York', 'Asia/Tokyo')
Returns:
str: A formatted string containing the timezone and current time
"""
try:
tz = pytz.timezone(timezone)
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
# Return a more descriptive string with cleaned timezone name
city = timezone.split('/')[-1].replace('_', ' ')
return f"The current time in {city} is: {local_time}"
except Exception as e:
return f"Error fetching time for timezone '{timezone}': {str(e)}"
# Initialize tools
final_answer = FinalAnswerTool()
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
# If the agent does not answer, the model is overloaded, please use another model or
# the following Hugging Face Endpoint that also contains qwen2.5 coder:
# Model configuration
model_id = 'https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
model = HfApiModel(
max_tokens=2096,
temperature=0.3, # Lower temperature for more consistent responses
model_id=model_id, # 'Qwen/Qwen2.5-Coder-32B-Instruct',
custom_role_conversions=None,
)
# Load prompt templates
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
# Initialize agent with tools
agent = CodeAgent(
model=model,
tools=[final_answer, wiki_search, get_current_time_in_timezone, image_generation_tool], # tavily_search,
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
# Launch the Gradio interface
GradioUI(agent).launch() |