zerito commited on
Commit
fe415cd
·
verified ·
1 Parent(s): fd38e7a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -93
app.py CHANGED
@@ -1,114 +1,66 @@
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
- from bs4 import BeautifulSoup
6
  import nltk
7
  from nltk.sentiment import SentimentIntensityAnalyzer
8
 
9
- nltk.download('vader_lexicon')
10
-
11
- @tool
12
- def get_btc_price() -> str:
13
- """Fetches the current Bitcoin price in USD using the CoinGecko API."""
14
- url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
15
- response = requests.get(url)
16
- if response.status_code != 200:
17
- return '{"error": "Failed to fetch Bitcoin price"}'
18
- data = response.json()
19
- price = data.get('bitcoin', {}).get('usd')
20
- if price is None:
21
- return '{"error": "Bitcoin price not found"}'
22
- return f"The current Bitcoin price is ${price:.2f} USD."
23
 
 
24
  @tool
25
  def get_btc_confidence_conseils(price: str) -> str:
26
- """Provides confidence conseils based on the current Bitcoin price."""
27
- try:
28
- price = float(price.split('$')[1].split(' ')[0])
29
- except ValueError:
30
- return "Invalid price format. Please provide a valid price."
 
 
 
 
 
31
 
32
- if price < 20000:
33
- return "The current Bitcoin price is low. It's a good time to buy."
34
- elif price < 30000:
35
- return "The current Bitcoin price is moderate. You can hold or buy."
36
- elif price < 40000:
37
- return "The current Bitcoin price is high. You can sell or hold."
38
  else:
39
- return "The current Bitcoin price is very high. It's a good time to sell."
 
 
40
 
 
41
  @tool
42
- def get_latest_btc_news() -> list:
43
- """Fetches the latest news about Bitcoin from CoinDesk."""
44
- url = "https://www.coindesk.com/category/bitcoin/"
 
 
 
 
 
 
 
45
  response = requests.get(url)
46
  if response.status_code != 200:
47
- return ["Failed to fetch news"]
48
- soup = BeautifulSoup(response.text, 'html.parser')
49
- articles = soup.find_all('article')
50
- news = []
51
- for article in articles[:5]:
52
- title = article.find('h3').text.strip()
53
- link = article.find('a')['href']
54
- news.append({'title': title, 'link': link})
55
- return news
56
-
57
- @tool
58
- def synthesize_btc_news(news: list) -> str:
59
- """Synthesizes the 5 last articles about Bitcoin."""
60
- synthesized_news = ""
61
- for article in news:
62
- synthesized_news += f"{article['title']}: {article['link']}\n"
63
- return synthesized_news
64
-
65
- @tool
66
- def judge_btc_news_sentiment(news: list) -> str:
67
- """Judges the sentiment of the news about Bitcoin."""
68
- sia = SentimentIntensityAnalyzer()
69
- sentiment = 0
70
- for article in news:
71
- title = article['title']
72
- sentiment_score = sia.polarity_scores(title)['compound']
73
- sentiment += sentiment_score
74
- average_sentiment = sentiment / len(news)
75
- if average_sentiment > 0.5:
76
- return "The overall sentiment of the news is very positive."
77
- elif average_sentiment > 0:
78
- return "The overall sentiment of the news is positive."
79
- elif average_sentiment < -0.5:
80
- return "The overall sentiment of the news is very negative."
81
- elif average_sentiment < 0:
82
- return "The overall sentiment of the news is negative."
83
- else:
84
- return "The overall sentiment of the news is neutral."
85
-
86
- # Initialize the FinalAnswerTool
87
- final_answer = FinalAnswerTool()
88
-
89
- # Initialize the model
90
- model = HfApiModel(
91
- max_tokens=2096,
92
- temperature=0.5,
93
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
94
- custom_role_conversions=None,
95
- )
96
-
97
- # Load additional tools if needed
98
- # For example, to load an image generation tool:
99
- # image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
100
 
101
- # Create the agent
102
  agent = CodeAgent(
103
- model=model,
104
- tools=[get_btc_price, get_btc_confidence_conseils, get_latest_btc_news, synthesize_btc_news, judge_btc_news_sentiment, final_answer], # Add your tools here
 
 
 
 
105
  max_steps=6,
106
- verbosity_level=1,
107
- grammar=None,
108
- planning_interval=None,
109
- name=None,
110
- description=None,
111
- prompt_templates=None # Set to None if not using prompt templates
112
  )
113
 
114
  # Launch the Gradio interface
 
1
+ from smolagents import CodeAgent, HfApiModel, tool
2
  import requests
3
  from tools.final_answer import FinalAnswerTool
4
  from Gradio_UI import GradioUI
 
5
  import nltk
6
  from nltk.sentiment import SentimentIntensityAnalyzer
7
 
8
+ # Download required NLTK data
9
+ nltk.download('vader_lexicon', quiet=True)
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ # Modified tool with proper parameter documentation
12
  @tool
13
  def get_btc_confidence_conseils(price: str) -> str:
14
+ """Analyzes Bitcoin market confidence using price data and news sentiment.
15
+
16
+ Args:
17
+ price (str): The current Bitcoin price in USD format (e.g., "$50,000.00")
18
+
19
+ Returns:
20
+ str: Market analysis and trading advice based on current conditions
21
+ """
22
+ sia = SentimentIntensityAnalyzer()
23
+ numeric_price = float(price.replace("$", "").replace(",", ""))
24
 
25
+ # Add your analysis logic here
26
+ if numeric_price > 50000:
27
+ sentiment = "bullish"
 
 
 
28
  else:
29
+ sentiment = "cautious"
30
+
31
+ return f"Market analysis ({price}): {sentiment.capitalize()} trend detected. Consider dollar-cost averaging."
32
 
33
+ # Tool for fetching Bitcoin price (updated with parameter docs)
34
  @tool
35
+ def get_btc_price(crypto: str) -> str:
36
+ """Fetches the current Bitcoin price in USD using the CoinGecko API.
37
+
38
+ Args:
39
+ crypto (str): Cryptocurrency symbol (e.g., 'bitcoin')
40
+
41
+ Returns:
42
+ str: Formatted price string or error message
43
+ """
44
+ url = f"https://api.coingecko.com/api/v3/simple/price?ids={crypto}&vs_currencies=usd"
45
  response = requests.get(url)
46
  if response.status_code != 200:
47
+ return '{"error": "Failed to fetch Bitcoin price"}'
48
+ data = response.json()
49
+ price = data.get(crypto, {}).get('usd')
50
+ if price is None:
51
+ return '{"error": "Bitcoin price not found"}'
52
+ return f"The current Bitcoin price is ${price:,.2f} USD."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ # Initialize the agent with all tools
55
  agent = CodeAgent(
56
+ model=HfApiModel(
57
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
58
+ max_tokens=2096,
59
+ temperature=0.5
60
+ ),
61
+ tools=[get_btc_price, get_btc_confidence_conseils, FinalAnswerTool()],
62
  max_steps=6,
63
+ verbosity_level=1
 
 
 
 
 
64
  )
65
 
66
  # Launch the Gradio interface