zerito commited on
Commit
572441f
·
verified ·
1 Parent(s): d9d9151

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -53
app.py CHANGED
@@ -1,73 +1,77 @@
1
- from smolagents import CodeAgent, HfApiModel, load_tool, tool
2
  import requests
3
  from tools.final_answer import FinalAnswerTool
4
  from Gradio_UI import GradioUI
 
5
 
6
- # Tool for fetching Bitcoin price
7
  @tool
8
- def get_btc_price() -> str:
9
- """Fetches the current Bitcoin price in USD using the CoinGecko API."""
10
- url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
11
  response = requests.get(url)
12
  if response.status_code != 200:
13
- return '{"error": "Failed to fetch Bitcoin price"}'
14
  data = response.json()
15
- price = data.get('bitcoin', {}).get('usd')
16
  if price is None:
17
- return '{"error": "Bitcoin price not found"}'
18
- return f"The current Bitcoin price is ${price:.2f} USD."
19
 
20
- # Tool for fetching Bitcoin news using NewsData.io API
21
  @tool
22
- def get_btc_news() -> str:
23
- """Fetches the latest Bitcoin news from NewsData.io API."""
24
- url = "https://newsdata.io/api/1/news"
25
- params = {
26
- 'apikey': 'YOUR_API_KEY', # Replace with your actual API key
27
- 'q': 'Bitcoin',
28
- 'category': 'crypto',
29
- 'language': 'en',
30
- 'country': 'us',
31
- 'page': 1,
32
- 'size': 5 # Number of news articles to fetch
33
- }
34
- response = requests.get(url, params=params)
35
- if response.status_code != 200:
36
- return '{"error": "Failed to fetch Bitcoin news"}'
37
- data = response.json()
38
- articles = data.get('results', [])
39
- if not articles:
40
- return "No relevant news found."
41
- news_list = []
42
- for article in articles:
43
- title = article.get('title', 'No title')
44
- description = article.get('description', 'No description')
45
- news_list.append(f"Title: {title}\nDescription: {description}\n")
46
- return "\n\n".join(news_list)
47
-
48
- # Initialize the FinalAnswerTool
49
- final_answer = FinalAnswerTool()
50
 
51
- # Initialize the model
52
  model = HfApiModel(
53
- max_tokens=2096,
54
- temperature=0.5,
55
  model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
56
- custom_role_conversions=None,
 
 
57
  )
58
 
59
- # Create the agent
60
  agent = CodeAgent(
61
  model=model,
62
- tools=[get_btc_price, get_btc_news, final_answer], # Add your tools here
63
- max_steps=6,
64
- verbosity_level=1,
65
- grammar=None,
66
- planning_interval=None,
67
- name=None,
68
- description=None,
69
- prompt_templates=None # Set to None if not using prompt templates
70
  )
71
 
72
- # Launch the Gradio interface
73
- GradioUI(agent).launch()
 
 
 
 
 
1
+ from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, tool
2
  import requests
3
  from tools.final_answer import FinalAnswerTool
4
  from Gradio_UI import GradioUI
5
+ from datetime import datetime, timedelta
6
 
7
+ # Modified CoinGecko Price Tool with crypto parameter
8
  @tool
9
+ def get_crypto_price(crypto: str) -> str:
10
+ """Fetches current price for any cryptocurrency using CoinGecko API."""
11
+ url = f"https://api.coingecko.com/api/v3/simple/price?ids={crypto}&vs_currencies=usd"
12
  response = requests.get(url)
13
  if response.status_code != 200:
14
+ return f'{{"error": "Failed to fetch {crypto} price"}}'
15
  data = response.json()
16
+ price = data.get(crypto, {}).get('usd')
17
  if price is None:
18
+ return f'{{"error": "{crypto} price not found"}}'
19
+ return f"Current {crypto} price: ${price:,.2f} USD"
20
 
21
+ # DuckDuckGo Search Tool with crypto parameter
22
  @tool
23
+ def get_crypto_news(crypto: str) -> str:
24
+ """Fetches latest news for any cryptocurrency using DuckDuckGo."""
25
+ date_filter = (datetime.now() - timedelta(days=3)).strftime("%Y-%m-%d")
26
+ search_query = (
27
+ f"{crypto} cryptocurrency "
28
+ f"news after:{date_filter} "
29
+ "site:coindesk.com OR site:cointelegraph.com OR site:bitcoin.com"
30
+ )
31
+
32
+ results = DuckDuckGoSearchTool().run(
33
+ query=search_query,
34
+ max_results=5,
35
+ region="us-en",
36
+ time_limit="d"
37
+ )
38
+
39
+ if not results:
40
+ return "No recent news found"
41
+
42
+ news_items = []
43
+ for item in results:
44
+ news_items.append(
45
+ f"**{item.get('title', 'Untitled')}**\n"
46
+ f"{item.get('body', 'No description available')}\n"
47
+ f"Source: {item.get('href', '')}\n"
48
+ )
49
+
50
+ return "\n\n".join(news_items)
51
 
52
+ # Initialize agent with enhanced configuration
53
  model = HfApiModel(
 
 
54
  model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
55
+ max_tokens=2096,
56
+ temperature=0.3,
57
+ top_p=0.95,
58
  )
59
 
 
60
  agent = CodeAgent(
61
  model=model,
62
+ tools=[get_crypto_price, get_crypto_news, DuckDuckGoSearchTool(), FinalAnswerTool()],
63
+ max_steps=8,
64
+ verbosity_level=2,
65
+ safety_guardrails={
66
+ "web_access": "filter",
67
+ "data_privacy": "strict"
68
+ },
69
+ rate_limit=5 # Requests per minute
70
  )
71
 
72
+ # Launch Gradio interface with crypto parameter support
73
+ GradioUI(
74
+ agent,
75
+ default_prompt="Fetch latest price and news for:",
76
+ input_fields=["crypto (e.g., bitcoin)"]
77
+ ).launch()