Update app.py
Browse files
app.py
CHANGED
@@ -1,167 +1,118 @@
|
|
1 |
import gradio as gr
|
2 |
from openai import OpenAI
|
3 |
import os
|
|
|
|
|
4 |
|
|
|
5 |
ACCESS_TOKEN = os.getenv("HF_TOKEN")
|
6 |
-
|
7 |
|
|
|
8 |
client = OpenAI(
|
9 |
base_url="https://api-inference.huggingface.co/v1/",
|
10 |
api_key=ACCESS_TOKEN,
|
11 |
)
|
12 |
-
print("OpenAI client initialized.")
|
13 |
|
14 |
-
#
|
|
|
|
|
|
|
15 |
SYSTEM_PROMPT = """
|
16 |
-
You are a highly knowledgeable and reliable Crypto Trading Advisor and Analyzer.
|
17 |
-
|
18 |
-
|
19 |
-
- Explain complex terms in simple language, especially for novice users.
|
20 |
-
- Always maintain an unbiased, neutral stance and avoid recommending specific cryptocurrencies or financial decisions.
|
21 |
-
### 2. Core Responsibilities
|
22 |
-
#### Market Analysis:
|
23 |
-
- Analyze and provide insights into cryptocurrency market trends, including market capitalization, trading volume, price momentum, and historical performance.
|
24 |
-
- Identify patterns, trends, and potential opportunities based on user-provided data or general market conditions.
|
25 |
-
#### Portfolio Insights:
|
26 |
-
- Help users review their crypto portfolios for diversification, risk exposure, and potential improvements.
|
27 |
-
- Suggest strategies for optimizing portfolio performance based on market conditions.
|
28 |
-
#### Risk Management:
|
29 |
-
- Educate users on effective risk management strategies, including stop-loss and take-profit orders, position sizing, and diversification.
|
30 |
-
- Warn about potential risks like high volatility, scams, or regulatory changes.
|
31 |
-
#### Technical Analysis:
|
32 |
-
- Provide detailed chart analysis using tools like moving averages, RSI, MACD, Bollinger Bands, Fibonacci retracements, and candlestick patterns.
|
33 |
-
- Explain support and resistance levels, trend lines, and potential breakout scenarios.
|
34 |
-
#### Fundamental Analysis:
|
35 |
-
- Share insights into the fundamentals of cryptocurrencies, including tokenomics, utility, developer activity, and recent news.
|
36 |
-
- Highlight events such as regulatory updates, partnerships, or technological advancements that may impact the market.
|
37 |
-
#### Education and Guidance:
|
38 |
-
- Educate users about blockchain technology, decentralized finance (DeFi), staking, NFTs, and emerging trends.
|
39 |
-
- Offer advice tailored to different trading styles (e.g., day trading, swing trading, long-term investing).
|
40 |
-
#### Alert Mechanism:
|
41 |
-
- Notify users about significant market events like price surges, dips, or whale movements.
|
42 |
-
- Provide insights on real-time news and announcements impacting the crypto market.
|
43 |
-
### 3. Interaction Guidelines
|
44 |
-
- Respond promptly and accurately to user queries.
|
45 |
-
- Suggest safe and ethical trading practices.
|
46 |
-
- Always remind users to do their own research (DYOR) and consult financial professionals where appropriate.
|
47 |
-
### 4. Disclaimer
|
48 |
-
- Remind users that cryptocurrency trading involves significant risk and past performance does not guarantee future results.
|
49 |
-
- Clearly state that your responses are for informational purposes only and not financial advice.
|
50 |
-
### Example Interactions
|
51 |
-
#### Example 1: Market Analysis
|
52 |
-
_User Query:_ "What’s the current trend of Bitcoin?"
|
53 |
-
_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."
|
54 |
-
#### Example 2: Portfolio Review
|
55 |
-
_User Query:_ "Is my portfolio balanced?"
|
56 |
-
_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."
|
57 |
-
#### Example 3: Risk Management
|
58 |
-
_User Query:_ "How do I protect my trades?"
|
59 |
-
_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%."
|
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 |
yield response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
111 |
|
112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
|
114 |
# Gradio UI
|
115 |
-
chatbot = gr.Chatbot(height=600, show_copy_button=True, placeholder="Ask about crypto trading or analysis."
|
116 |
-
|
117 |
-
max_tokens_slider = gr.Slider(
|
118 |
-
minimum=1,
|
119 |
-
maximum=4096,
|
120 |
-
value=512,
|
121 |
-
step=1,
|
122 |
-
label="Max new tokens"
|
123 |
-
)
|
124 |
-
temperature_slider = gr.Slider(
|
125 |
-
minimum=0.1,
|
126 |
-
maximum=4.0,
|
127 |
-
value=0.7,
|
128 |
-
step=0.1,
|
129 |
-
label="Temperature"
|
130 |
-
)
|
131 |
-
top_p_slider = gr.Slider(
|
132 |
-
minimum=0.1,
|
133 |
-
maximum=1.0,
|
134 |
-
value=0.95,
|
135 |
-
step=0.05,
|
136 |
-
label="Top-P"
|
137 |
-
)
|
138 |
-
frequency_penalty_slider = gr.Slider(
|
139 |
-
minimum=-2.0,
|
140 |
-
maximum=2.0,
|
141 |
-
value=0.0,
|
142 |
-
step=0.1,
|
143 |
-
label="Frequency Penalty"
|
144 |
-
)
|
145 |
-
seed_slider = gr.Slider(
|
146 |
-
minimum=-1,
|
147 |
-
maximum=65535,
|
148 |
-
value=-1,
|
149 |
-
step=1,
|
150 |
-
label="Seed (-1 for random)"
|
151 |
-
)
|
152 |
|
153 |
demo = gr.ChatInterface(
|
154 |
fn=respond,
|
155 |
-
additional_inputs=[
|
156 |
-
max_tokens_slider,
|
157 |
-
temperature_slider,
|
158 |
-
top_p_slider,
|
159 |
-
frequency_penalty_slider,
|
160 |
-
seed_slider,
|
161 |
-
],
|
162 |
fill_height=True,
|
163 |
chatbot=chatbot,
|
164 |
)
|
165 |
|
166 |
if __name__ == "__main__":
|
167 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
from openai import OpenAI
|
3 |
import os
|
4 |
+
from crewai import Agent, Task, Crew, Process
|
5 |
+
from langchain_community.tools.tavily_search import TavilySearchResults
|
6 |
|
7 |
+
# Environment Variables
|
8 |
ACCESS_TOKEN = os.getenv("HF_TOKEN")
|
9 |
+
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
10 |
|
11 |
+
# OpenAI Client Initialization
|
12 |
client = OpenAI(
|
13 |
base_url="https://api-inference.huggingface.co/v1/",
|
14 |
api_key=ACCESS_TOKEN,
|
15 |
)
|
|
|
16 |
|
17 |
+
# Search Tool Initialization
|
18 |
+
search_tool = TavilySearchResults(tavily_api_key=TAVILY_API_KEY)
|
19 |
+
|
20 |
+
# System Prompt
|
21 |
SYSTEM_PROMPT = """
|
22 |
+
You are a highly knowledgeable and reliable Crypto Trading Advisor and Analyzer.
|
23 |
+
Your goal is to assist users in understanding, analyzing, and making informed decisions about cryptocurrency trading.
|
24 |
+
You provide accurate, concise, and actionable advice based on real-time data, historical trends, and established best practices.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
"""
|
26 |
|
27 |
+
# CrewAI Integration
|
28 |
+
llm = client # Using the OpenAI client for CrewAI agents
|
29 |
+
|
30 |
+
def run_crypto_crew(topic):
|
31 |
+
researcher = Agent(
|
32 |
+
role='Market Researcher',
|
33 |
+
goal=f'Uncover emerging trends and investment opportunities in the cryptocurrency market. Focus on the topic: {topic}.',
|
34 |
+
backstory='Identify groundbreaking trends and actionable insights.',
|
35 |
+
verbose=True,
|
36 |
+
tools=[search_tool],
|
37 |
+
allow_delegation=False,
|
38 |
+
llm=llm,
|
39 |
+
max_iter=3,
|
40 |
+
max_rpm=10,
|
41 |
+
)
|
42 |
+
|
43 |
+
analyst = Agent(
|
44 |
+
role='Investment Analyst',
|
45 |
+
goal=f'Analyze cryptocurrency market data to extract actionable insights. Focus on the topic: {topic}.',
|
46 |
+
backstory='Draw meaningful conclusions from cryptocurrency market data.',
|
47 |
+
verbose=True,
|
48 |
+
allow_delegation=False,
|
49 |
+
llm=llm,
|
50 |
+
)
|
51 |
+
|
52 |
+
research_task = Task(
|
53 |
+
description=f'Explore the internet to identify trends and investment opportunities. Topic: {topic}.',
|
54 |
+
agent=researcher,
|
55 |
+
expected_output='Detailed summary of research results.'
|
56 |
+
)
|
57 |
+
|
58 |
+
analyst_task = Task(
|
59 |
+
description=f'Analyze the market data to compile a concise report. Topic: {topic}.',
|
60 |
+
agent=analyst,
|
61 |
+
expected_output='Finalized version of the analysis report.'
|
62 |
+
)
|
63 |
+
|
64 |
+
crypto_crew = Crew(
|
65 |
+
agents=[researcher, analyst],
|
66 |
+
tasks=[research_task, analyst_task],
|
67 |
+
process=Process.sequential
|
68 |
+
)
|
69 |
+
|
70 |
+
result = crypto_crew.kickoff()
|
71 |
+
return result.raw
|
72 |
+
|
73 |
+
# Chatbot Response Function
|
74 |
+
def respond(message, history):
|
75 |
+
max_tokens = 512
|
76 |
+
temperature = 0.3
|
77 |
+
top_p = 0.95
|
78 |
+
frequency_penalty = 0.0
|
79 |
+
seed = None
|
80 |
+
|
81 |
+
if "analyze" in message.lower() or "trend" in message.lower():
|
82 |
+
response = run_crypto_crew(message)
|
83 |
yield response
|
84 |
+
else:
|
85 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
86 |
+
for user_part, assistant_part in history:
|
87 |
+
if user_part:
|
88 |
+
messages.append({"role": "user", "content": user_part})
|
89 |
+
if assistant_part:
|
90 |
+
messages.append({"role": "assistant", "content": assistant_part})
|
91 |
+
messages.append({"role": "user", "content": message})
|
92 |
|
93 |
+
response = ""
|
94 |
+
for message_chunk in client.chat.completions.create(
|
95 |
+
model="meta-llama/Llama-3.3-70B-Instruct",
|
96 |
+
max_tokens=max_tokens,
|
97 |
+
stream=True,
|
98 |
+
temperature=temperature,
|
99 |
+
top_p=top_p,
|
100 |
+
frequency_penalty=frequency_penalty,
|
101 |
+
seed=seed,
|
102 |
+
messages=messages,
|
103 |
+
):
|
104 |
+
token_text = message_chunk.choices[0].delta.content
|
105 |
+
response += token_text
|
106 |
+
yield response
|
107 |
|
108 |
# Gradio UI
|
109 |
+
chatbot = gr.Chatbot(height=600, show_copy_button=True, placeholder="Ask about crypto trading or analysis.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
|
111 |
demo = gr.ChatInterface(
|
112 |
fn=respond,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
fill_height=True,
|
114 |
chatbot=chatbot,
|
115 |
)
|
116 |
|
117 |
if __name__ == "__main__":
|
118 |
+
demo.launch()
|