-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
259 lines (235 loc) · 8.7 KB
/
app.py
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import streamlit as st
from web3 import Web3
import openai
import requests
import json
import shelve
import os
import pandas as pd
from datetime import datetime, timedelta
import matplotlib .pyplot as plt
# CoinGecko API base URL
COINGECKO_API_BASE_URL = 'https://api.coingecko.com/api/v3'
# Etherscan API base URL
ETHERSCAN_API_BASE_URL = 'https://api.etherscan.io/68PQB8YRA35YU5VFW4N9P32IXSU8AHKCD6'
st.title("Blockchat AI")
# Set up OpenAI API key
openai.api_key = "sk-proj-sHIZiRnWl9c3ShA9qYnlT3BlbkFJMmJuF1t6zJ93ITbw5xa8"
def crypto_price(currency):
coin_symbol = currency.lower()
response = requests.get(f"{COINGECKO_API_BASE_URL}/simple/price?ids={coin_symbol}&vs_currencies=usd")
if response.status_code == 200:
value = response.json()
data = {"name":str(value.keys()),"price":value.get(currency)}
return json.dumps(data)
def filter_lowest_price(currencies):
coin_symbol = currencies.lower()
response = requests.get(f"{COINGECKO_API_BASE_URL}/simple/price?ids={coin_symbol}&vs_currencies=usd")
data = response.json()
out={}
# Find the coin with the lowest price in USD
lowest_price = float('inf')
lowest_price_coin = None
for coin, price_info in data.items():
price_usd = price_info.get('usd', float('inf'))
if price_usd < lowest_price:
lowest_price = price_usd
lowest_price_coin = coin
out["coin"] = lowest_price_coin
out["price"]= lowest_price
print(out)
return json.dumps(out)
def fetch_price_history(coin_id="bitcoin", days=30):
"""
Fetches historical price data for a given cryptocurrency over a specified number of days.
"""
end_date = datetime.now()
start_date = end_date - timedelta(days=days)
url = f"https://api.coingecko.com/api/v3/coins/{coin_id}/market_chart/range"
params = {
'vs_currency': 'usd',
'from': start_date.timestamp(),
'to': end_date.timestamp()
}
response = requests.get(url, params=params)
data = response.json()
prices = data['prices']
timestamps = [datetime.fromtimestamp(ts / 1000) for ts in [price[0] for price in prices]]
prices = [price[1] for price in prices] # Extract only prices
df = pd.DataFrame(list(zip(timestamps, prices)), columns=['timestamp', 'price'])
showchart(df)
return df
def showchart(df):
st.line_chart(df,x="timestamp",y= "price")
#st.pyplot(plt.gcf())
#st.session_state.messages.append({"role": "assistant", "content": plt.gcf()})
def recommendation(coin_id):
df=fetch_price_history(coin_id)
df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
df['price_change'] = df['price'].pct_change()
strategy={}
df['trend'] = df['price_change'].rolling(window=5).mean() # 5-day moving average
if df['trend'].iloc[-1] > 0:
strategy['trend'] = "Bullish"
strategy['recommendation'] = "Buying"
return json.dumps(strategy)
elif df['trend'].iloc[-1] < 0:
strategy['trend'] = "Bearish"
strategy['recommendation'] = "selling"
return json.dumps(strategy)
else:
strategy['trend'] = "No trend"
strategy['recommendation'] = "holding"
return json.dumps(strategy)
def filter_highest_price(currencies):
coin_symbol = currencies.lower()
response = requests.get(f"{COINGECKO_API_BASE_URL}/simple/price?ids={coin_symbol}&vs_currencies=usd")
data = response.json()
out={}
# Find the coin with the lowest price in USD
highest_price = 0.000001
highest_price_coin = None
for coin, price_info in data.items():
price_usd = price_info.get('usd', float('inf'))
if price_usd > highest_price:
highest_price = price_usd
highest_price_coin = coin
out["coin"] = highest_price_coin
out["price"]= highest_price
print(out)
return json.dumps(out)
functions = [
{
"name":"crypto_price",
"description":"Get the current market price of crytocurrency, e.g. bitcoin,etheruem",
"parameters":{
"type":"object",
"properties":{
"currency":{
"type":"string",
"description":"the name of cryptocurrency"
},
},
"required":["currency"],
},
},
{
"name":"filter_lowest_price",
"description":"filters and returns cheapest coin and price among the given list of cryptocurrencies, e.g. bitcoin,ethereum,ripple",
"parameters":{
"type":"object",
"properties":{
"currencies":{
"type":"string",
"description":"list of cryptocurrencies, e.g. bitcoin,ethereum,ripple."
},
},
"required":["currencies"],
},
},
{
"name":"filter_highest_price",
"description":"filters and returns expensive coin and price among the given list of cryptocurrencies, e.g. bitcoin,ethereum,ripple",
"parameters":{
"type":"object",
"properties":{
"currencies":{
"type":"string",
"description":"list of cryptocurrencies, e.g. bitcoin,ethereum,ripple."
},
},
"required":["currencies"],
},
},
{
"name":"recommendation",
"description":"gets the current market trend of gievn cryptocurrency.",
"parameters":{
"type":"object",
"properties":{
"coin_id":{
"type":"string",
"description":"the name of cryptocurrency"
},
},
"required":["coin_id"],
},
}
]
def bot(query):
response = openai.chat.completions.create(
model="gpt-3.5-turbo-0613",
messages=[{"role":"user","content":query}],
functions=functions,
function_call="auto"
)
print(response.choices[0])
mes=response.choices[0].message
if mes.function_call is not None:
return second(mes)
else:
return mes.content
def second(mes):
if mes.function_call is not None:
function_name=mes.function_call.name
if function_name=="crypto_price":
currency=json.loads(mes.function_call.arguments).get("currency")
function_response=crypto_price(currency)
sec_response = openai.chat.completions.create(
model="gpt-3.5-turbo-0613", # Use GPT-3.5 Davinci model
messages=[
{"role":"function",
"name":function_name,
"content":function_response}],
)
elif function_name=="filter_highest_price":
currencies=json.loads(mes.function_call.arguments).get("currencies")
function_response=filter_highest_price(currencies)
elif function_name=="filter_lowest_price":
currencies=json.loads(mes.function_call.arguments).get("currencies")
function_response=filter_lowest_price(currencies)
elif function_name=="recommendation":
coin_id=json.loads(mes.function_call.arguments).get("coin_id")
function_response=recommendation(coin_id)
sec_response = openai.chat.completions.create(
model="gpt-3.5-turbo-0613", # Use GPT-3.5 Davinci model
messages=[
{"role":"function",
"name":function_name,
"content":function_response}],
)
return sec_response.choices[0].message.content
def load_history():
with shelve.open("chat_history") as db:
return db.get("messages",[])
def save_chat(messages):
with shelve.open("chat_history") as db:
db["messages"]=messages
def main():
if "messages" not in st.session_state:
st.session_state.messages = load_history()
with st.sidebar:
if st.button("DELETE CHAT"):
st.session_state.messages = []
save_chat([])
# Main conversation loop
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Main chat interface
if prompt := st.chat_input("How can I help?"):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
if prompt:
with st.spinner("Waiting for response..."):
full_response=bot(prompt)
with st.chat_message("assistant"):
message_placeholder = st.empty()
message_placeholder.markdown(full_response + "|")
message_placeholder.markdown(full_response)
st.session_state.messages.append({"role": "assistant", "content": full_response})
# Save chat history after each interaction
save_chat(st.session_state.messages)
if __name__ == "__main__":
main()