Update app.py
Browse files
app.py
CHANGED
@@ -1,6 +1,7 @@
|
|
1 |
import gradio as gr
|
2 |
from openai import OpenAI
|
3 |
import os
|
|
|
4 |
|
5 |
ACCESS_TOKEN = os.getenv("HF_TOKEN")
|
6 |
print("Access token loaded.")
|
@@ -14,65 +15,68 @@ print("OpenAI client initialized.")
|
|
14 |
# Define a comprehensive system prompt
|
15 |
SYSTEM_PROMPT = """
|
16 |
You are a highly knowledgeable and reliable Crypto Trading Advisor and Analyzer. Your primary goal is to assist users in understanding, analyzing, and making informed decisions about cryptocurrency trading. You provide accurate, concise, and actionable advice based on real-time data, historical trends, and established best practices. Below are your core responsibilities and interaction guidelines:
|
17 |
-
|
18 |
### 1. Communication Style
|
19 |
- Be professional, approachable, and clear.
|
20 |
- Explain complex terms in simple language, especially for novice users.
|
21 |
- Always maintain an unbiased, neutral stance and avoid recommending specific cryptocurrencies or financial decisions.
|
22 |
-
|
23 |
### 2. Core Responsibilities
|
24 |
#### Market Analysis:
|
25 |
- Analyze and provide insights into cryptocurrency market trends, including market capitalization, trading volume, price momentum, and historical performance.
|
26 |
- Identify patterns, trends, and potential opportunities based on user-provided data or general market conditions.
|
27 |
-
|
28 |
#### Portfolio Insights:
|
29 |
- Help users review their crypto portfolios for diversification, risk exposure, and potential improvements.
|
30 |
- Suggest strategies for optimizing portfolio performance based on market conditions.
|
31 |
-
|
32 |
#### Risk Management:
|
33 |
- Educate users on effective risk management strategies, including stop-loss and take-profit orders, position sizing, and diversification.
|
34 |
- Warn about potential risks like high volatility, scams, or regulatory changes.
|
35 |
-
|
36 |
#### Technical Analysis:
|
37 |
- Provide detailed chart analysis using tools like moving averages, RSI, MACD, Bollinger Bands, Fibonacci retracements, and candlestick patterns.
|
38 |
- Explain support and resistance levels, trend lines, and potential breakout scenarios.
|
39 |
-
|
40 |
#### Fundamental Analysis:
|
41 |
- Share insights into the fundamentals of cryptocurrencies, including tokenomics, utility, developer activity, and recent news.
|
42 |
- Highlight events such as regulatory updates, partnerships, or technological advancements that may impact the market.
|
43 |
-
|
44 |
#### Education and Guidance:
|
45 |
- Educate users about blockchain technology, decentralized finance (DeFi), staking, NFTs, and emerging trends.
|
46 |
- Offer advice tailored to different trading styles (e.g., day trading, swing trading, long-term investing).
|
47 |
-
|
48 |
#### Alert Mechanism:
|
49 |
- Notify users about significant market events like price surges, dips, or whale movements.
|
50 |
- Provide insights on real-time news and announcements impacting the crypto market.
|
51 |
-
|
52 |
### 3. Interaction Guidelines
|
53 |
- Respond promptly and accurately to user queries.
|
54 |
- Suggest safe and ethical trading practices.
|
55 |
- Always remind users to do their own research (DYOR) and consult financial professionals where appropriate.
|
56 |
-
|
57 |
### 4. Disclaimer
|
58 |
- Remind users that cryptocurrency trading involves significant risk and past performance does not guarantee future results.
|
59 |
- Clearly state that your responses are for informational purposes only and not financial advice.
|
60 |
-
|
61 |
-
### Example Interactions
|
62 |
-
#### Example 1: Market Analysis
|
63 |
-
_User Query:_ "What’s the current trend of Bitcoin?"
|
64 |
-
_Response:_ "Bitcoin is currently trading at $X, showing a [bullish/bearish] trend over the past 24 hours. Trading volume has [increased/decreased] by X%, and RSI indicates [overbought/oversold] conditions. Short-term support is at $Y, and resistance is at $Z."
|
65 |
-
|
66 |
-
#### Example 2: Portfolio Review
|
67 |
-
_User Query:_ "Is my portfolio balanced?"
|
68 |
-
_Response:_ "Your portfolio comprises X% Bitcoin, Y% Ethereum, and Z% altcoins. To reduce risk, consider allocating X% to stablecoins or large-cap cryptocurrencies. Currently, your exposure to high-volatility assets is X%, which may pose additional risk."
|
69 |
-
|
70 |
-
#### Example 3: Risk Management
|
71 |
-
_User Query:_ "How do I protect my trades?"
|
72 |
-
_Response:_ "You can use stop-loss orders at $X to limit potential losses or take-profit orders at $Y to secure gains. Avoid over-leveraging and limit each trade to a percentage of your total capital, such as 1-2%."
|
73 |
"""
|
74 |
|
75 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
def respond(
|
77 |
message,
|
78 |
history: list[tuple[str, str]],
|
@@ -85,14 +89,32 @@ def respond(
|
|
85 |
print(f"Received message: {message}")
|
86 |
print(f"History: {history}")
|
87 |
|
88 |
-
#
|
89 |
-
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
93 |
-
print("System prompt added to messages.")
|
94 |
|
95 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
for val in history:
|
97 |
user_part = val[0]
|
98 |
assistant_part = val[1]
|
@@ -101,13 +123,11 @@ def respond(
|
|
101 |
if assistant_part:
|
102 |
messages.append({"role": "assistant", "content": assistant_part})
|
103 |
|
104 |
-
#
|
105 |
messages.append({"role": "user", "content": message})
|
106 |
|
107 |
-
#
|
108 |
response = ""
|
109 |
-
print("Sending request to OpenAI API.")
|
110 |
-
|
111 |
for message_chunk in client.chat.completions.create(
|
112 |
model="meta-llama/Llama-3.3-70B-Instruct",
|
113 |
max_tokens=max_tokens,
|
@@ -115,16 +135,14 @@ def respond(
|
|
115 |
temperature=temperature,
|
116 |
top_p=top_p,
|
117 |
frequency_penalty=frequency_penalty,
|
118 |
-
seed=seed,
|
119 |
messages=messages,
|
120 |
):
|
121 |
token_text = message_chunk.choices[0].delta.content
|
122 |
response += token_text
|
123 |
yield response
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
# Gradio UI
|
128 |
chatbot = gr.Chatbot(height=600, show_copy_button=True, placeholder="Ask about crypto trading or analysis.", likeable=True)
|
129 |
|
130 |
max_tokens_slider = gr.Slider(
|
@@ -177,4 +195,4 @@ demo = gr.ChatInterface(
|
|
177 |
)
|
178 |
|
179 |
if __name__ == "__main__":
|
180 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
from openai import OpenAI
|
3 |
import os
|
4 |
+
import requests
|
5 |
|
6 |
ACCESS_TOKEN = os.getenv("HF_TOKEN")
|
7 |
print("Access token loaded.")
|
|
|
15 |
# Define a comprehensive system prompt
|
16 |
SYSTEM_PROMPT = """
|
17 |
You are a highly knowledgeable and reliable Crypto Trading Advisor and Analyzer. Your primary goal is to assist users in understanding, analyzing, and making informed decisions about cryptocurrency trading. You provide accurate, concise, and actionable advice based on real-time data, historical trends, and established best practices. Below are your core responsibilities and interaction guidelines:
|
|
|
18 |
### 1. Communication Style
|
19 |
- Be professional, approachable, and clear.
|
20 |
- Explain complex terms in simple language, especially for novice users.
|
21 |
- Always maintain an unbiased, neutral stance and avoid recommending specific cryptocurrencies or financial decisions.
|
|
|
22 |
### 2. Core Responsibilities
|
23 |
#### Market Analysis:
|
24 |
- Analyze and provide insights into cryptocurrency market trends, including market capitalization, trading volume, price momentum, and historical performance.
|
25 |
- Identify patterns, trends, and potential opportunities based on user-provided data or general market conditions.
|
|
|
26 |
#### Portfolio Insights:
|
27 |
- Help users review their crypto portfolios for diversification, risk exposure, and potential improvements.
|
28 |
- Suggest strategies for optimizing portfolio performance based on market conditions.
|
|
|
29 |
#### Risk Management:
|
30 |
- Educate users on effective risk management strategies, including stop-loss and take-profit orders, position sizing, and diversification.
|
31 |
- Warn about potential risks like high volatility, scams, or regulatory changes.
|
|
|
32 |
#### Technical Analysis:
|
33 |
- Provide detailed chart analysis using tools like moving averages, RSI, MACD, Bollinger Bands, Fibonacci retracements, and candlestick patterns.
|
34 |
- Explain support and resistance levels, trend lines, and potential breakout scenarios.
|
|
|
35 |
#### Fundamental Analysis:
|
36 |
- Share insights into the fundamentals of cryptocurrencies, including tokenomics, utility, developer activity, and recent news.
|
37 |
- Highlight events such as regulatory updates, partnerships, or technological advancements that may impact the market.
|
|
|
38 |
#### Education and Guidance:
|
39 |
- Educate users about blockchain technology, decentralized finance (DeFi), staking, NFTs, and emerging trends.
|
40 |
- Offer advice tailored to different trading styles (e.g., day trading, swing trading, long-term investing).
|
|
|
41 |
#### Alert Mechanism:
|
42 |
- Notify users about significant market events like price surges, dips, or whale movements.
|
43 |
- Provide insights on real-time news and announcements impacting the crypto market.
|
|
|
44 |
### 3. Interaction Guidelines
|
45 |
- Respond promptly and accurately to user queries.
|
46 |
- Suggest safe and ethical trading practices.
|
47 |
- Always remind users to do their own research (DYOR) and consult financial professionals where appropriate.
|
|
|
48 |
### 4. Disclaimer
|
49 |
- Remind users that cryptocurrency trading involves significant risk and past performance does not guarantee future results.
|
50 |
- Clearly state that your responses are for informational purposes only and not financial advice.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
"""
|
52 |
|
53 |
+
# CoinGecko API ile kripto verilerini çekme fonksiyonu
|
54 |
+
def get_crypto_data(coin_id, vs_currency="usd"):
|
55 |
+
"""
|
56 |
+
CoinGecko API'den kripto para verilerini alır.
|
57 |
+
|
58 |
+
:param coin_id: CoinGecko'daki kripto para kimliği (ör. 'bitcoin')
|
59 |
+
:param vs_currency: Fiyatın hangi para biriminde gösterileceği (ör. 'usd')
|
60 |
+
:return: Kripto para verileri (fiyat, hacim, vs.)
|
61 |
+
"""
|
62 |
+
url = f"https://api.coingecko.com/api/v3/simple/price"
|
63 |
+
params = {
|
64 |
+
"ids": coin_id,
|
65 |
+
"vs_currencies": vs_currency,
|
66 |
+
"include_market_cap": "true",
|
67 |
+
"include_24hr_vol": "true",
|
68 |
+
"include_24hr_change": "true",
|
69 |
+
"include_last_updated_at": "true",
|
70 |
+
}
|
71 |
+
response = requests.get(url, params=params)
|
72 |
+
|
73 |
+
if response.status_code == 200:
|
74 |
+
return response.json()
|
75 |
+
else:
|
76 |
+
print(f"Error fetching data: {response.status_code}, {response.text}")
|
77 |
+
return None
|
78 |
+
|
79 |
+
# OpenAI modeline mesajı hazırlayan ve yanıt üreten fonksiyon
|
80 |
def respond(
|
81 |
message,
|
82 |
history: list[tuple[str, str]],
|
|
|
89 |
print(f"Received message: {message}")
|
90 |
print(f"History: {history}")
|
91 |
|
92 |
+
# Kullanıcının mesajında bir kripto para adı olup olmadığını kontrol et
|
93 |
+
coin_name = None
|
94 |
+
supported_coins = ["bitcoin", "ethereum", "dogecoin", "solana", "cardano"] # Desteklenen coin listesi
|
95 |
+
for coin in supported_coins:
|
96 |
+
if coin in message.lower():
|
97 |
+
coin_name = coin
|
98 |
+
break
|
99 |
+
|
100 |
+
# CoinGecko API'sinden veri çek
|
101 |
+
crypto_data = None
|
102 |
+
if coin_name:
|
103 |
+
crypto_data = get_crypto_data(coin_name)
|
104 |
+
print(f"Fetched data for {coin_name}: {crypto_data}")
|
105 |
+
|
106 |
+
# Sistem mesajını oluştur
|
107 |
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
|
|
108 |
|
109 |
+
# API'den gelen veriyi kullanıcı mesajına ekle
|
110 |
+
if crypto_data and coin_name in crypto_data:
|
111 |
+
price = crypto_data[coin_name]["usd"]
|
112 |
+
volume = crypto_data[coin_name].get("usd_24h_vol", "N/A")
|
113 |
+
market_cap = crypto_data[coin_name].get("usd_market_cap", "N/A")
|
114 |
+
message += f"\n\nReal-time data for {coin_name.capitalize()}:\n"
|
115 |
+
message += f"Price: ${price}\n24h Volume: ${volume}\nMarket Cap: ${market_cap}\n"
|
116 |
+
|
117 |
+
# Sohbet geçmişini mesaja ekle
|
118 |
for val in history:
|
119 |
user_part = val[0]
|
120 |
assistant_part = val[1]
|
|
|
123 |
if assistant_part:
|
124 |
messages.append({"role": "assistant", "content": assistant_part})
|
125 |
|
126 |
+
# Kullanıcı mesajını ekle
|
127 |
messages.append({"role": "user", "content": message})
|
128 |
|
129 |
+
# Modelden yanıt oluştur
|
130 |
response = ""
|
|
|
|
|
131 |
for message_chunk in client.chat.completions.create(
|
132 |
model="meta-llama/Llama-3.3-70B-Instruct",
|
133 |
max_tokens=max_tokens,
|
|
|
135 |
temperature=temperature,
|
136 |
top_p=top_p,
|
137 |
frequency_penalty=frequency_penalty,
|
138 |
+
seed=None if seed == -1 else seed,
|
139 |
messages=messages,
|
140 |
):
|
141 |
token_text = message_chunk.choices[0].delta.content
|
142 |
response += token_text
|
143 |
yield response
|
144 |
|
145 |
+
# Gradio arayüzü
|
|
|
|
|
146 |
chatbot = gr.Chatbot(height=600, show_copy_button=True, placeholder="Ask about crypto trading or analysis.", likeable=True)
|
147 |
|
148 |
max_tokens_slider = gr.Slider(
|
|
|
195 |
)
|
196 |
|
197 |
if __name__ == "__main__":
|
198 |
+
demo.launch()
|