Spaces:
Sleeping
Sleeping
File size: 7,474 Bytes
9c12531 6e6f15b 9c12531 ce2af7e 41fbc42 ce2af7e 6e6f15b 9c12531 ce2af7e 9c12531 6e6f15b ce2af7e 9c12531 6e6f15b 9c12531 6e6f15b 9c12531 6e6f15b 9c12531 ce2af7e 9c12531 6e6f15b 9c12531 6e6f15b ce2af7e 9c12531 6e6f15b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
import gradio as gr
from openai import OpenAI
import os
import requests
ACCESS_TOKEN = os.getenv("HF_TOKEN")
print("Access token loaded.")
client = OpenAI(
base_url="https://api-inference.huggingface.co/v1/",
api_key=ACCESS_TOKEN,
)
print("OpenAI client initialized.")
# Define a comprehensive system prompt
SYSTEM_PROMPT = """
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:
### 1. Communication Style
- Be professional, approachable, and clear.
- Explain complex terms in simple language, especially for novice users.
- Always maintain an unbiased, neutral stance and avoid recommending specific cryptocurrencies or financial decisions.
### 2. Core Responsibilities
#### Market Analysis:
- Analyze and provide insights into cryptocurrency market trends, including market capitalization, trading volume, price momentum, and historical performance.
- Identify patterns, trends, and potential opportunities based on user-provided data or general market conditions.
#### Portfolio Insights:
- Help users review their crypto portfolios for diversification, risk exposure, and potential improvements.
- Suggest strategies for optimizing portfolio performance based on market conditions.
#### Risk Management:
- Educate users on effective risk management strategies, including stop-loss and take-profit orders, position sizing, and diversification.
- Warn about potential risks like high volatility, scams, or regulatory changes.
#### Technical Analysis:
- Provide detailed chart analysis using tools like moving averages, RSI, MACD, Bollinger Bands, Fibonacci retracements, and candlestick patterns.
- Explain support and resistance levels, trend lines, and potential breakout scenarios.
#### Fundamental Analysis:
- Share insights into the fundamentals of cryptocurrencies, including tokenomics, utility, developer activity, and recent news.
- Highlight events such as regulatory updates, partnerships, or technological advancements that may impact the market.
#### Education and Guidance:
- Educate users about blockchain technology, decentralized finance (DeFi), staking, NFTs, and emerging trends.
- Offer advice tailored to different trading styles (e.g., day trading, swing trading, long-term investing).
#### Alert Mechanism:
- Notify users about significant market events like price surges, dips, or whale movements.
- Provide insights on real-time news and announcements impacting the crypto market.
### 3. Interaction Guidelines
- Respond promptly and accurately to user queries.
- Suggest safe and ethical trading practices.
- Always remind users to do their own research (DYOR) and consult financial professionals where appropriate.
### 4. Disclaimer
- Remind users that cryptocurrency trading involves significant risk and past performance does not guarantee future results.
- Clearly state that your responses are for informational purposes only and not financial advice.
"""
# CoinGecko API ile kripto verilerini çekme fonksiyonu
def get_crypto_data(coin_id, vs_currency="usd"):
"""
CoinGecko API'den kripto para verilerini alır.
:param coin_id: CoinGecko'daki kripto para kimliği (ör. 'bitcoin')
:param vs_currency: Fiyatın hangi para biriminde gösterileceği (ör. 'usd')
:return: Kripto para verileri (fiyat, hacim, vs.)
"""
url = f"https://api.coingecko.com/api/v3/simple/price"
params = {
"ids": coin_id,
"vs_currencies": vs_currency,
"include_market_cap": "true",
"include_24hr_vol": "true",
"include_24hr_change": "true",
"include_last_updated_at": "true",
}
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json()
else:
print(f"Error fetching data: {response.status_code}, {response.text}")
return None
# OpenAI modeline mesajı hazırlayan ve yanıt üreten fonksiyon
def respond(
message,
history: list[tuple[str, str]],
max_tokens,
temperature,
top_p,
frequency_penalty,
seed
):
print(f"Received message: {message}")
print(f"History: {history}")
# Kullanıcının mesajında bir kripto para adı olup olmadığını kontrol et
coin_name = None
supported_coins = ["bitcoin", "ethereum", "dogecoin", "solana", "cardano"] # Desteklenen coin listesi
for coin in supported_coins:
if coin in message.lower():
coin_name = coin
break
# CoinGecko API'sinden veri çek
crypto_data = None
if coin_name:
crypto_data = get_crypto_data(coin_name)
print(f"Fetched data for {coin_name}: {crypto_data}")
# Sistem mesajını oluştur
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
# API'den gelen veriyi kullanıcı mesajına ekle
if crypto_data and coin_name in crypto_data:
price = crypto_data[coin_name]["usd"]
volume = crypto_data[coin_name].get("usd_24h_vol", "N/A")
market_cap = crypto_data[coin_name].get("usd_market_cap", "N/A")
message += f"\n\nReal-time data for {coin_name.capitalize()}:\n"
message += f"Price: ${price}\n24h Volume: ${volume}\nMarket Cap: ${market_cap}\n"
# Sohbet geçmişini mesaja ekle
for val in history:
user_part = val[0]
assistant_part = val[1]
if user_part:
messages.append({"role": "user", "content": user_part})
if assistant_part:
messages.append({"role": "assistant", "content": assistant_part})
# Kullanıcı mesajını ekle
messages.append({"role": "user", "content": message})
# Modelden yanıt oluştur
response = ""
for message_chunk in client.chat.completions.create(
model="meta-llama/Llama-3.3-70B-Instruct",
max_tokens=max_tokens,
stream=True,
temperature=temperature,
top_p=top_p,
frequency_penalty=frequency_penalty,
seed=None if seed == -1 else seed,
messages=messages,
):
token_text = message_chunk.choices[0].delta.content
response += token_text
yield response
# Gradio arayüzü
chatbot = gr.Chatbot(height=600, show_copy_button=True, placeholder="Ask about crypto trading or analysis.", likeable=True)
max_tokens_slider = gr.Slider(
minimum=1,
maximum=4096,
value=512,
step=1,
label="Max new tokens"
)
temperature_slider = gr.Slider(
minimum=0.1,
maximum=4.0,
value=0.7,
step=0.1,
label="Temperature"
)
top_p_slider = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.95,
step=0.05,
label="Top-P"
)
frequency_penalty_slider = gr.Slider(
minimum=-2.0,
maximum=2.0,
value=0.0,
step=0.1,
label="Frequency Penalty"
)
seed_slider = gr.Slider(
minimum=-1,
maximum=65535,
value=-1,
step=1,
label="Seed (-1 for random)"
)
demo = gr.ChatInterface(
fn=respond,
additional_inputs=[
max_tokens_slider,
temperature_slider,
top_p_slider,
frequency_penalty_slider,
seed_slider,
],
fill_height=True,
chatbot=chatbot,
)
if __name__ == "__main__":
demo.launch()
|