Files changed (1) hide show
  1. app.py +76 -50
app.py CHANGED
@@ -1,69 +1,95 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
7
-
8
  from Gradio_UI import GradioUI
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
  Args:
16
- arg1: the first argument
17
- arg2: the second argument
18
  """
19
- return "What magic will you build ?"
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
24
  Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
 
26
  """
27
  try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
 
 
 
 
 
 
 
 
33
  except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
-
36
-
37
- final_answer = FinalAnswerTool()
38
-
39
- # 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:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
41
 
42
- model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
47
- )
48
-
49
-
50
- # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
-
53
- with open("prompts.yaml", 'r') as stream:
54
- prompt_templates = yaml.safe_load(stream)
55
-
56
- agent = CodeAgent(
57
- model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
- max_steps=6,
60
- verbosity_level=1,
61
- grammar=None,
62
- planning_interval=None,
63
- name=None,
64
- description=None,
65
- prompt_templates=prompt_templates
66
- )
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- GradioUI(agent).launch()
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
 
7
  from Gradio_UI import GradioUI
8
 
9
+ # 定义工具
10
  @tool
11
+ def get_weather(city: str) -> str:
12
+ """A tool that fetches the current weather for a specified city.
 
13
  Args:
14
+ city: The name of the city (e.g., 'Beijing').
 
15
  """
16
+ try:
17
+ api_key = "YOUR_OPENWEATHERMAP_API_KEY" # 替换为你的OpenWeatherMap API Key
18
+ url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
19
+ response = requests.get(url)
20
+ data = response.json()
21
+ if response.status_code == 200:
22
+ weather = data['weather'][0]['description']
23
+ temperature = data['main']['temp']
24
+ return f"The current weather in {city} is {weather} with a temperature of {temperature}°C."
25
+ else:
26
+ return f"Error fetching weather data for {city}: {data['message']}"
27
+ except Exception as e:
28
+ return f"Error fetching weather data for {city}: {str(e)}"
29
 
30
  @tool
31
+ def translate_text(text: str, source_lang: str, target_lang: str) -> str:
32
+ """A tool that translates text from one language to another.
33
  Args:
34
+ text: The text to be translated.
35
+ source_lang: The source language code (e.g., 'en' for English).
36
+ target_lang: The target language code (e.g., 'zh' for Chinese).
37
  """
38
  try:
39
+ api_key = "YOUR_GOOGLE_TRANSLATE_API_KEY" # 替换为你的Google Translate API Key
40
+ url = f"https://translation.googleapis.com/language/translate/v2?key={api_key}"
41
+ data = {
42
+ "q": text,
43
+ "source": source_lang,
44
+ "target": target_lang
45
+ }
46
+ response = requests.post(url, json=data)
47
+ result = response.json()
48
+ if 'data' in result and 'translations' in result['data']:
49
+ return result['data']['translations'][0]['translatedText']
50
+ else:
51
+ return f"Error translating text: {result.get('error', {}).get('message', 'Unknown error')}"
52
  except Exception as e:
53
+ return f"Error translating text: {str(e)}"
 
 
 
 
 
 
54
 
55
+ @tool
56
+ def read_file(file_path: str) -> str:
57
+ """A tool that reads the content of a local file.
58
+ Args:
59
+ file_path: The path to the file (e.g., 'example.txt').
60
+ """
61
+ try:
62
+ with open(file_path, 'r', encoding='utf-8') as file:
63
+ content = file.read()
64
+ return content
65
+ except FileNotFoundError:
66
+ return f"File not found: {file_path}"
67
+ except Exception as e:
68
+ return f"Error reading file {file_path}: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ @tool
71
+ def summarize_text(text: str, max_length: int = 100) -> str:
72
+ """A tool that generates a summary of a given text.
73
+ Args:
74
+ text: The text to be summarized.
75
+ max_length: The maximum length of the summary (default is 100).
76
+ """
77
+ try:
78
+ from transformers import pipeline
79
+ summarizer = pipeline("summarization")
80
+ summary = summarizer(text, max_length=max_length, clean_up_tokenization_spaces=True)
81
+ return summary[0]['summary_text']
82
+ except Exception as e:
83
+ return f"Error summarizing text: {str(e)}"
84
 
85
+ @tool
86
+ def calculate_expression(expression: str) -> str:
87
+ """A tool that evaluates a mathematical expression.
88
+ Args:
89
+ expression: The mathematical expression to evaluate (e.g., '2 + 3 * 4').
90
+ """
91
+ try:
92
+ result = eval(expression)
93
+ return f"The result of the expression '{expression}' is {result}."
94
+ except Exception as e:
95
+ return f"Error evaluating expression '{expression}': {str(e)}"