SnowHA commited on
Commit
6737453
·
verified ·
1 Parent(s): 5fbb520

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -79
app.py CHANGED
@@ -1,38 +1,25 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
  import pandas as pd
7
  import numpy as np
 
8
  from tools.final_answer import FinalAnswerTool
9
  from tools.visit_webpage import VisitWebpageTool
 
10
 
11
  from Gradio_UI import GradioUI
12
 
13
  final_answer = FinalAnswerTool()
14
  visit_webpage = VisitWebpageTool()
15
- web_search = DuckDuckGoSearchTool()
16
-
17
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
18
- @tool
19
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
20
- #Keep this format for the description / args / args description but feel free to modify the tool
21
- """A tool that does nothing yet
22
- Args:
23
- arg1: the first argument
24
- arg2: the second argument
25
- """
26
- return "What magic will you build ?"
27
 
28
  @tool
29
  def get_crypto_price(crypto: str, currency: str) -> str:
30
- """A tool to fetch real-time cryptocurrency prices from CoinGecko API.
31
-
32
  Args:
33
  crypto: The cryptocurrency symbol (e.g., 'bitcoin', 'ethereum').
34
  currency: The fiat currency (e.g., 'usd', 'twd').
35
-
36
  Returns:
37
  The current price of the cryptocurrency in the specified currency.
38
  """
@@ -48,15 +35,13 @@ def get_crypto_price(crypto: str, currency: str) -> str:
48
 
49
  @tool
50
  def get_crypto_history(crypto: str, currency: str, days: int) -> str:
51
- """A tool to fetch historical cryptocurrency prices from CoinGecko API.
52
-
53
  Args:
54
  crypto: The cryptocurrency symbol (e.g., 'bitcoin', 'ethereum').
55
  currency: The fiat currency (e.g., 'usd', 'twd').
56
- days: The number of past days to retrieve (e.g., 30 for the past month).
57
-
58
  Returns:
59
- A list of historical prices over the specified time period.
60
  """
61
  url = f"https://api.coingecko.com/api/v3/coins/{crypto}/market_chart?vs_currency={currency}&days={days}&interval=daily"
62
  try:
@@ -70,81 +55,40 @@ def get_crypto_history(crypto: str, currency: str, days: int) -> str:
70
 
71
  prices_str = "\n".join([f"Date: {pd.to_datetime(p[0], unit='ms').date()}, Price: {p[1]:.2f} {currency}" for p in prices])
72
  return f"Historical prices for {crypto} in {currency} over {days} days:\n{prices_str}"
73
-
74
  except requests.RequestException as e:
75
  return f"Error fetching historical data: {e}"
76
 
77
  @tool
78
- def get_crypto_moving_average(crypto: str, currency: str, days: int, window: int) -> str:
79
- """A tool to compute the moving average of cryptocurrency prices.
80
-
81
  Args:
82
- crypto: The cryptocurrency symbol (e.g., 'bitcoin', 'ethereum').
83
- currency: The fiat currency (e.g., 'usd', 'twd').
84
- days: The number of past days to retrieve.
85
- window: The moving average window size (e.g., 7 for 7-day SMA).
86
-
87
  Returns:
88
- A list of moving average values.
89
- """
90
- url = f"https://api.coingecko.com/api/v3/coins/{crypto}/market_chart?vs_currency={currency}&days={days}&interval=daily"
91
- try:
92
- response = requests.get(url)
93
- response.raise_for_status()
94
- data = response.json()
95
- prices = data.get("prices", [])
96
-
97
- if not prices or len(prices) < window:
98
- return "Not enough data for moving average calculation."
99
-
100
- df = pd.DataFrame(prices, columns=["timestamp", "price"])
101
- df["date"] = pd.to_datetime(df["timestamp"], unit="ms").dt.date
102
- df["sma"] = df["price"].rolling(window=window).mean()
103
-
104
- moving_avg_str = "\n".join([f"Date: {df['date'][i]}, SMA: {df['sma'][i]:.2f} {currency}" for i in range(len(df)) if not np.isnan(df['sma'][i])])
105
- return f"Moving Average (window={window}) for {crypto} in {currency} over {days} days:\n{moving_avg_str}"
106
-
107
- except requests.RequestException as e:
108
- return f"Error fetching historical data: {e}"
109
-
110
- @tool
111
- def get_current_time_in_timezone(timezone: str) -> str:
112
- """A tool that fetches the current local time in a specified timezone.
113
- Args:
114
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
115
  """
116
  try:
117
- # Create timezone object
118
- tz = pytz.timezone(timezone)
119
- # Get current time in that timezone
120
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
121
- return f"The current local time in {timezone} is: {local_time}"
122
  except Exception as e:
123
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
124
-
125
-
126
- final_answer = FinalAnswerTool()
127
-
128
- # 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:
129
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' ,'Qwen/Qwen2.5-Coder-32B-Instruct'
130
 
 
131
  model = HfApiModel(
132
- max_tokens=2096,
133
- temperature=0.5,
134
- model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',# it is possible that this model may be overloaded
135
- custom_role_conversions=None,
136
  )
137
 
138
-
139
- # Import tool from Hub
140
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
141
 
142
  with open("prompts.yaml", 'r') as stream:
143
  prompt_templates = yaml.safe_load(stream)
144
-
145
  agent = CodeAgent(
146
  model=model,
147
- tools=[final_answer], ## add your tools here (don't remove final answer)
148
  max_steps=6,
149
  verbosity_level=1,
150
  grammar=None,
@@ -154,5 +98,4 @@ agent = CodeAgent(
154
  prompt_templates=prompt_templates
155
  )
156
 
157
-
158
- GradioUI(agent).launch()
 
 
1
  import datetime
2
  import requests
3
  import pytz
4
  import yaml
5
  import pandas as pd
6
  import numpy as np
7
+ from smolagents import CodeAgent, HfApiModel, load_tool, tool
8
  from tools.final_answer import FinalAnswerTool
9
  from tools.visit_webpage import VisitWebpageTool
10
+ from web import search # 使用 web.search() 來替代 DuckDuckGoSearchTool
11
 
12
  from Gradio_UI import GradioUI
13
 
14
  final_answer = FinalAnswerTool()
15
  visit_webpage = VisitWebpageTool()
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  @tool
18
  def get_crypto_price(crypto: str, currency: str) -> str:
19
+ """Fetch real-time cryptocurrency prices from CoinGecko API.
 
20
  Args:
21
  crypto: The cryptocurrency symbol (e.g., 'bitcoin', 'ethereum').
22
  currency: The fiat currency (e.g., 'usd', 'twd').
 
23
  Returns:
24
  The current price of the cryptocurrency in the specified currency.
25
  """
 
35
 
36
  @tool
37
  def get_crypto_history(crypto: str, currency: str, days: int) -> str:
38
+ """Fetch historical cryptocurrency prices from CoinGecko API.
 
39
  Args:
40
  crypto: The cryptocurrency symbol (e.g., 'bitcoin', 'ethereum').
41
  currency: The fiat currency (e.g., 'usd', 'twd').
42
+ days: The number of past days to retrieve.
 
43
  Returns:
44
+ A list of historical prices.
45
  """
46
  url = f"https://api.coingecko.com/api/v3/coins/{crypto}/market_chart?vs_currency={currency}&days={days}&interval=daily"
47
  try:
 
55
 
56
  prices_str = "\n".join([f"Date: {pd.to_datetime(p[0], unit='ms').date()}, Price: {p[1]:.2f} {currency}" for p in prices])
57
  return f"Historical prices for {crypto} in {currency} over {days} days:\n{prices_str}"
 
58
  except requests.RequestException as e:
59
  return f"Error fetching historical data: {e}"
60
 
61
  @tool
62
+ def web_search(query: str) -> str:
63
+ """Search the web for real-time information.
 
64
  Args:
65
+ query: The search query.
 
 
 
 
66
  Returns:
67
+ The top search results.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  """
69
  try:
70
+ results = search(query)
71
+ return f"Search results for '{query}':\n" + "\n".join(results)
 
 
 
72
  except Exception as e:
73
+ return f"Error performing web search: {e}"
 
 
 
 
 
 
74
 
75
+ # 設置模型
76
  model = HfApiModel(
77
+ max_tokens=2096,
78
+ temperature=0.5,
79
+ model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',
80
+ custom_role_conversions=None,
81
  )
82
 
83
+ # 載入工具
 
84
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
85
 
86
  with open("prompts.yaml", 'r') as stream:
87
  prompt_templates = yaml.safe_load(stream)
88
+
89
  agent = CodeAgent(
90
  model=model,
91
+ tools=[final_answer, visit_webpage, get_crypto_price, get_crypto_history, web_search],
92
  max_steps=6,
93
  verbosity_level=1,
94
  grammar=None,
 
98
  prompt_templates=prompt_templates
99
  )
100
 
101
+ GradioUI(agent).launch()