File size: 6,727 Bytes
9c12531
 
 
 
 
 
 
 
 
 
 
 
 
ce2af7e
 
41fbc42
3da1d4f
ce2af7e
 
 
 
3da1d4f
ce2af7e
 
 
 
3da1d4f
ce2af7e
 
 
3da1d4f
ce2af7e
 
 
3da1d4f
ce2af7e
 
 
3da1d4f
ce2af7e
 
 
3da1d4f
ce2af7e
 
 
3da1d4f
ce2af7e
 
 
3da1d4f
ce2af7e
 
 
 
3da1d4f
ce2af7e
 
 
3da1d4f
ce2af7e
 
 
 
3da1d4f
ce2af7e
 
 
3da1d4f
ce2af7e
 
 
 
 
 
9c12531
 
 
 
 
 
 
ce2af7e
9c12531
 
 
 
 
 
 
 
ce2af7e
 
9c12531
 
 
 
 
 
 
 
 
 
 
 
 
ce2af7e
9c12531
 
 
 
ce2af7e
9c12531
 
 
 
 
 
 
 
 
 
 
 
 
 
ce2af7e
 
9c12531
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01e122e
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
import gradio as gr
from openai import OpenAI
import os

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.

### Example Interactions
#### Example 1: Market Analysis
_User Query:_ "What’s the current trend of Bitcoin?"
_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."

#### Example 2: Portfolio Review
_User Query:_ "Is my portfolio balanced?"
_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."

#### Example 3: Risk Management
_User Query:_ "How do I protect my trades?"
_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%."
"""

# Function to handle chatbot responses
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}")

    # Convert seed to None if -1 (meaning random)
    if seed == -1:
        seed = None

    messages = [{"role": "system", "content": SYSTEM_PROMPT}]
    print("System prompt added to messages.")

    # Add conversation history to the context
    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})

    # Append the latest user message
    messages.append({"role": "user", "content": message})

    # Start response generation
    response = ""
    print("Sending request to OpenAI API.")

    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=seed,
        messages=messages,
    ):
        token_text = message_chunk.choices[0].delta.content
        response += token_text
        yield response

    print("Completed response generation.")

# Gradio UI
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()