zerito commited on
Commit
5cafb21
·
verified ·
1 Parent(s): 037e99a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -141
app.py CHANGED
@@ -1,165 +1,69 @@
 
 
 
1
  import requests
2
- from typing import List, Dict, Any
3
- import numpy as np
4
  import yaml
5
- from smolagents import CodeAgent, HfApiModel, load_tool, tool
6
  from tools.final_answer import FinalAnswerTool
7
  from Gradio_UI import GradioUI
8
 
9
- # ✅ Final Answer Tool
10
- final_answer = FinalAnswerTool()
11
-
12
- # ✅ AI Model Setup
13
- model = HfApiModel(
14
- max_tokens=2096,
15
- temperature=0.5,
16
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
17
- custom_role_conversions=None,
18
- )
19
-
20
- # ✅ Load Prompt Templates
21
- with open("prompts.yaml", 'r') as stream:
22
- prompt_templates = yaml.safe_load(stream)
23
-
24
-
25
- # --- Utility Functions ---
26
-
27
- def fetch_data(url: str, params: Dict[str, Any] = None) -> Dict[str, Any]:
28
- """Make GET requests and return JSON response."""
29
- try:
30
- response = requests.get(url, params=params, timeout=10)
31
- response.raise_for_status()
32
- return response.json()
33
- except requests.exceptions.RequestException as e:
34
- return {"error": str(e)}
35
-
36
-
37
- def compute_moving_average(prices: List[float], window: int) -> float:
38
- """Compute moving average for given price data."""
39
- return np.mean(prices[-window:]) if len(prices) >= window else np.mean(prices)
40
-
41
-
42
- # --- Tools ---
43
-
44
  @tool
45
- def fetch_btc_news() -> List[Dict[str, str]]:
46
- """Fetch latest Bitcoin news from CryptoPanic API."""
47
- url = "https://cryptopanic.com/api/v1/posts/?auth_token=ccbeafb47d266a78086f76c3f547546f6b747e88&currencies=BTC"
48
- data = fetch_data(url)
49
- return [{"title": post["title"], "url": post["url"]} for post in data.get("results", [])[:5]]
50
-
 
 
 
 
 
51
 
52
  @tool
53
- def btc_market_insights() -> Dict[str, Any]:
54
- """Fetch BTC market data and technical indicators."""
55
- # Current price data
56
- price_data = fetch_data(
57
- "https://api.coingecko.com/api/v3/simple/price",
58
- {"ids": "bitcoin", "vs_currencies": "usd", "include_24hr_change": "true"}
59
- )
60
- if "error" in price_data:
61
- return price_data
62
-
63
- # Historical data (90 days with hourly intervals)
64
- hist_data = fetch_data(
65
- "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart",
66
- {"vs_currency": "usd", "days": "90", "interval": "hourly"}
67
- )
68
- if "error" in hist_data:
69
- return hist_data
70
-
71
- prices = [entry[1] for entry in hist_data.get("prices", [])]
72
-
73
- # Moving averages calculations (hours)
74
- return {
75
- "price": price_data["bitcoin"]["usd"],
76
- "24h_change": price_data["bitcoin"]["usd_24h_change"],
77
- "ma_4h": compute_moving_average(prices, 4),
78
- "ma_12h": compute_moving_average(prices, 12),
79
- "ma_24h": compute_moving_average(prices, 24),
80
- "ma_7d": compute_moving_average(prices, 168),
81
- "ma_30d": compute_moving_average(prices, 720),
82
- **get_fear_greed_index()
83
- }
84
 
85
  @tool
86
- def btc_decision(market_insights: Dict[str, Any]) -> Dict[str, str]:
87
- """
88
- Aggregates market insights to suggest a Buy, Sell, or HODL decision.
89
-
90
- :param market_insights: A dictionary containing BTC market data. It must include:
91
- - 'price': Current BTC price in USD.
92
- - '24h_change': 24-hour price change percentage.
93
- - 'ma_5m': 5-minute moving average.
94
- - 'ma_1h': 1-hour moving average.
95
- - 'ma_1d': 1-day moving average.
96
- - 'ma_7d': 7-day moving average.
97
- - 'ma_1m': 1-month moving average.
98
- - 'ma_1y': 1-year moving average.
99
- - 'fear_greed': Current Fear & Greed index value.
100
- - 'fgi_text': Classification text for the Fear & Greed index.
101
- :return: A dictionary mapping timeframes (e.g., "5m-1H", "1D", "7D", "1M", "1Y") to a decision
102
- ("BUY 🚀", "SELL 📉", or "HODL 🤔").
103
- """
104
- btc_price = market_insights["price"]
105
- fgi = int(market_insights["fear_greed"])
106
-
107
- # Moving averages for different timeframes
108
- ma_5m = market_insights["ma_5m"]
109
- ma_1h = market_insights["ma_1h"]
110
- ma_1d = market_insights["ma_1d"]
111
- ma_7d = market_insights["ma_7d"]
112
- ma_1m = market_insights["ma_1m"]
113
- ma_1y = market_insights["ma_1y"]
114
-
115
- # Initialize decision template
116
- decision = {
117
- "5m-1H": "HODL 🤔",
118
- "1D": "HODL 🤔",
119
- "7D": "HODL 🤔",
120
- "1M": "HODL 🤔",
121
- "1Y": "HODL 🤔"
122
- }
123
-
124
- def make_decision(timeframe: str, ma: float) -> str:
125
- if btc_price > ma and fgi < 40:
126
- decision[timeframe] = "BUY 🚀"
127
- elif btc_price < ma and fgi > 60:
128
- decision[timeframe] = "SELL 📉"
129
- return decision[timeframe]
130
-
131
- decision["5m-1H"] = make_decision("5m-1H", ma_5m)
132
- decision["1D"] = make_decision("1D", ma_1d)
133
- decision["7D"] = make_decision("7D", ma_7d)
134
- decision["1M"] = make_decision("1M", ma_1m)
135
-
136
- return decision
137
 
 
 
 
 
 
 
 
138
 
139
- def get_fear_greed_index() -> Dict[str, Any]:
140
- """Fetch Fear & Greed Index data."""
141
- fgi_data = fetch_data("https://api.alternative.me/fng/")
142
- if "error" in fgi_data or not fgi_data.get("data"):
143
- return {"fear_greed": 50, "fgi_text": "Neutral"}
144
-
145
- return {
146
- "fear_greed": int(fgi_data["data"][0]["value"]),
147
- "fgi_text": fgi_data["data"][0]["value_classification"]
148
- }
149
 
 
 
150
 
151
- # --- Agent Setup ---
152
  agent = CodeAgent(
153
  model=model,
154
- tools=[final_answer, fetch_btc_news, btc_market_insights, btc_decision],
155
  max_steps=6,
156
  verbosity_level=1,
157
- prompt_templates=prompt_templates,
158
  grammar=None,
159
  planning_interval=None,
160
  name=None,
161
- description=None
 
162
  )
163
 
164
- # --- Launch UI ---
165
  GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
+ import datetime
3
+ import json
4
  import requests
5
+ import pytz
 
6
  import yaml
 
7
  from tools.final_answer import FinalAnswerTool
8
  from Gradio_UI import GradioUI
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  @tool
11
+ def get_btc_price() -> str:
12
+ """Fetches the current Bitcoin price in USD using the CoinGecko API."""
13
+ url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
14
+ response = requests.get(url)
15
+ if response.status_code != 200:
16
+ return '{"error": "Failed to fetch Bitcoin price"}'
17
+ data = response.json()
18
+ price = data.get('bitcoin', {}).get('usd')
19
+ if price is None:
20
+ return '{"error": "Bitcoin price not found"}'
21
+ return f"The current Bitcoin price is ${price:.2f} USD."
22
 
23
  @tool
24
+ def get_btc_news() -> str:
25
+ """Fetches the latest Bitcoin news using DuckDuckGo search."""
26
+ search_query = "latest Bitcoin news"
27
+ search_results = DuckDuckGoSearchTool().search(search_query)
28
+ if not search_results:
29
+ return '{"error": "No news found"}'
30
+ news = [{"title": result['title'], "url": result['url']} for result in search_results]
31
+ return json.dumps(news, indent=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  @tool
34
+ def get_current_time_in_timezone(timezone: str) -> str:
35
+ """Fetches the current local time in a specified timezone."""
36
+ try:
37
+ tz = pytz.timezone(timezone)
38
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
39
+ return f"The current local time in {timezone} is: {local_time}"
40
+ except Exception as e:
41
+ return f"Error fetching time for timezone '{timezone}': {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ final_answer = FinalAnswerTool()
44
+ model = HfApiModel(
45
+ max_tokens=1048,
46
+ temperature=0.5,
47
+ model_id='deepseek-ai/DeepSeek-R1-Distill-Qwen-32B',
48
+ custom_role_conversions=None,
49
+ )
50
 
51
+ # Import tool from Hub
52
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
 
 
 
 
 
 
 
53
 
54
+ with open("prompts.yaml", 'r') as stream:
55
+ prompt_templates = yaml.safe_load(stream)
56
 
 
57
  agent = CodeAgent(
58
  model=model,
59
+ tools=[get_btc_price, get_btc_news, DuckDuckGoSearchTool(), image_generation_tool, final_answer],
60
  max_steps=6,
61
  verbosity_level=1,
 
62
  grammar=None,
63
  planning_interval=None,
64
  name=None,
65
+ description=None,
66
+ prompt_templates=prompt_templates
67
  )
68
 
 
69
  GradioUI(agent).launch()