James MacQuillan commited on
Commit
f68dda0
·
1 Parent(s): 4f02758
Files changed (2) hide show
  1. app.py +225 -48
  2. requirements.txt +24 -1
app.py CHANGED
@@ -1,64 +1,241 @@
 
 
 
 
 
 
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
27
 
28
- response = ""
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  yield response
 
 
 
 
 
 
41
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from googlesearch import search
2
+ import requests
3
+ import trafilatura
4
+
5
+ from concurrent.futures import ThreadPoolExecutor
6
+ import json
7
+ import ast
8
  import gradio as gr
9
  from huggingface_hub import InferenceClient
10
+ import tiktoken
11
+ import time
12
+ import os
13
+
14
+ client = InferenceClient(api_key=os.getenv('HF_TOKEN'))
15
+
16
+
17
+
18
+
19
+ dots_animation = [
20
+ "Working on your response.",
21
+ "Working on your response..",
22
+ "Working on your response...",
23
+ ]
24
+
25
+ arrow_animation = [
26
+ "----> Preparing your answer",
27
+ "---> Preparing your answer",
28
+ "--> Preparing your answer",
29
+ "-> Preparing your answer",
30
+ "> Preparing your answer",
31
+ ]
32
+
33
+ loader_animation = [
34
+ "[ ] Fetching data...",
35
+ "[= ] Fetching data...",
36
+ "[== ] Fetching data...",
37
+ "[=== ] Fetching data...",
38
+ "[====] Fetching data...",
39
+ ]
40
+
41
+ typing_animation = [
42
+ "Bot is typing.",
43
+ "Bot is typing..",
44
+ "Bot is typing...",
45
+ ]
46
+ rotating_text_animation = [
47
+ "Working |",
48
+ "Working /",
49
+ "Working -",
50
+ "Working \\",
51
+ ]
52
+
53
+
54
+ def tokenize_with_qwen(text):
55
+ """
56
+ Tokenizes the input text using a compatible tokenizer for Qwen models and returns a string of tokens.
57
+
58
+ Parameters:
59
+ text (list or str): The text (or list of strings) to be tokenized.
60
+
61
+ Returns:
62
+ str: A single string of tokens, truncated to 32,500 tokens if necessary.
63
+ """
64
+ # Ensure input is a string (concatenate if it's a list)
65
+ if isinstance(text, list):
66
+ text = ''.join(text)
67
+ elif not isinstance(text, str):
68
+ raise ValueError("Input must be a string or a list of strings.")
69
+
70
+ # Use a base encoding like cl100k_base for GPT-style tokenization
71
+ encoding = tiktoken.get_encoding("cl100k_base")
72
+
73
+ # Tokenize the text into token IDs
74
+ token_ids = encoding.encode(text)
75
+
76
+ # Decode each token ID into its string representation
77
+ token_strings = [encoding.decode_single_token_bytes(token_id).decode('utf-8', errors='replace') for token_id in token_ids]
78
+
79
+ # Truncate if the number of tokens exceeds 32,500
80
+ if len(token_strings) > 23000:
81
+ token_strings = token_strings[:17000]
82
+
83
+ # Join tokens back into a single string
84
+ stringed_tokens = ''.join(token_strings)
85
+ return stringed_tokens
86
+
87
+
88
+ def fetch_and_process_url(link):
89
+ try:
90
+ # Fetch URL content
91
+ req = requests.get(link, headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
92
+ html_content = req.text # Use raw HTML directly
93
+ # Extract main content using trafilatura
94
+ return trafilatura.extract(html_content)
95
+ except Exception as e:
96
+ return f"Error fetching or processing {link}: {e}"
97
+
98
+ def perform_search(query, num_results=5):
99
+ try:
100
+ # Perform Google search
101
+ urls = [url for url in search(query, num_results=num_results)]
102
+ print("URLs Found:")
103
+ print(urls)
104
+ except Exception as e:
105
+ print(f"An error occurred during search: {e}")
106
+ return
107
+
108
+ # Fetch and process URLs in parallel
109
+ with ThreadPoolExecutor(max_workers=30) as executor:
110
+ results = list(executor.map(fetch_and_process_url, urls))
111
+
112
+ # Combine results into a single formatted output
113
+ formatted_text = '\n\n'.join(filter(None, results)) # Skip None or empty results
114
+ return formatted_text
115
+
116
+ def chat(user_input,history):
117
+
118
+ format_template = examples = """
119
+
120
+ {"user_input": "cisco systems stock price for the last 4 days", "searches": ["cisco stock price last 4 days", "cisco systems stock historical data", "current price of Cisco Systems", "cisco stock price chart"]},
121
+ {"user_input": "Apple stock price yesterday", "searches": ["Apple stock price yesterday", "historical price of Apple stock"]},
122
+ {"user_input": "Tesla quarterly revenue", "searches": ["Tesla latest quarterly revenue", "Tesla revenue report Q3 2024"]},
123
+ {"user_input": "CAPM model for Tesla", "searches": ["Tesla stock beta value", "current risk-free rate", "expected market return for CAPM model"]},
124
+ {"user_input": "Hi", "searches": []},
125
+ {"user_input": "Who are you?", "searches": []},
126
+ {"user_input": "Google earnings per share last quarter", "searches": ["Google EPS last quarter", "Google quarterly earnings report"]},
127
+ {"user_input": "Calculate WACC for Microsoft", "searches": ["Microsoft cost of equity", "Microsoft cost of debt", "Microsoft capital structure", "current risk-free rate", "Microsoft beta"]},
128
+ {"user_input": "Show Amazon stock chart for last 5 years", "searches": ["Amazon stock chart last 5 years", "Amazon historical price data"]},
129
+ {"user_input": "GDP of China in 2023", "searches": ["China GDP 2023", "latest GDP figures for China"]},
130
+ {"user_input": "Portfolio optimization model", "searches": ["efficient frontier portfolio theory", "input data for portfolio optimization model", "expected returns and covariances"]},
131
+ {"user_input": "Find current inflation rate in the US", "searches": ["current US inflation rate", "US CPI data"]},
132
+ {"user_input": "What is NPV and how do you calculate it?", "searches": ["definition of NPV", "how to calculate NPV"]},
133
+ {"user_input": "Dividend yield for Coca-Cola", "searches": ["Coca-Cola dividend yield", "latest Coca-Cola dividend data"]},
134
+ {"user_input": "Sharpe ratio formula example", "searches": ["Sharpe ratio formula", "example calculation of Sharpe ratio"]},
135
+ {"user_input": "What is the current Fed interest rate?", "searches": ["current Federal Reserve interest rate", "latest Fed interest rate decision"]},
136
+ {"user_input": "Generate DCF model for Tesla", "searches": ["Tesla free cash flow data", "Tesla growth rate projections", "current discount rate for Tesla", "steps to build a DCF model"]},
137
+ {"user_input": "Tell me a joke", "searches": []},
138
+ {"user_input": "Explain the concept of opportunity cost", "searches": ["definition of opportunity cost", "examples of opportunity cost in economics"]}
139
 
140
  """
 
 
 
141
 
142
+
143
+
144
+ search_messages = history or [{'role': 'system', 'content': 'you are IM.FIN'}]
145
 
146
+ print(f'here is the search messages: \n\n\n\n {search_messages} \n\n\n')
147
+ search_messages.append({'role':'user','content':f'based on {user_input} and {search_messages}, respond with a list of google searches that will give the correct data to respond, respond in this format: {format_template} with up to 3 searches but try and limit it to the minimum needed. RETURN 1 DICTIONARY IN THE SPECIFIED FORMAT BASED ON THE USER INPUT {user_input}. RETURN ABSOLUTELY NO OTHER TEXT OTHER THAN THE DICTIONARY WITH THE SEARCHES. here is the history use it {search_messages}'})
148
+ for value in dots_animation:
149
+ yield value
150
+ response_for_searches = client.chat.completions.create(
151
+ model='Qwen/Qwen2.5-72B-Instruct',
 
 
 
152
 
153
+ messages=search_messages
154
+ )
155
+ searches_resp = response_for_searches.choices[0].message.content
156
+ yield dots_animation[1]
157
+ print(f'search model response: {searches_resp}')
158
+ searches = ast.literal_eval(searches_resp)
159
+ search_messages.append(searches)
160
+
161
+ print(searches)
162
+ yield arrow_animation[0]
163
+ summary_messages = [
164
+ {'role':'system','content':'you are IM.FIN'}
165
+ ]
166
+
167
+ var = [perform_search(search) for search in searches['searches']]
168
+ yield arrow_animation[1]
169
+
170
+ var = tokenize_with_qwen(var)
171
+ yield arrow_animation[2]
172
+ print(f'the type of var is {type(var)}')
173
+ var = ''.join(var)
174
+ print(f'the data: {var}')
175
 
176
+
177
 
178
+
179
+ yield arrow_animation[3]
180
+ summary_messages.append({'role':'user','content':f'use {user_input} to summarize {var}, return nothing other than the summarized response. MAKE SURE TO PICK OUT THE NUMERICAL DATA BASED ON THE USER RESPONSE'})
181
+ for value in arrow_animation:
182
+ time.sleep(1)
183
+ yield value
184
+ response_for_chat = client.chat.completions.create(
185
+ model='Qwen/Qwen2.5-72B-Instruct',
186
 
187
+ messages=summary_messages,
188
+ max_tokens=2000
189
+ )
 
 
 
 
 
190
 
191
+ summary = response_for_chat.choices[0].message.content
192
+ for value in arrow_animation:
193
+
194
+ yield value
195
+ final_messages = [
196
+ {'role':'system','content':'you are IM.FIN, you are a virtual stock analyst built to automate investing tasks and simulate the intelligence of stock analysts, you can form opinions based on data and form conclusions like stock analysts, you were created by quantineuron.com. KEEP RESPONSES CONCISE, ANSWERING THE USERS INPUT '}
197
+ ]
198
+
199
+ print(f'here is the summary: {summary}')
200
+ final_messages.append({'role':'user','content': f'based on this data {summary}, answer {user_input}, here is the history {final_messages}. ONLY USE THE DATA THAT IS NEEDED AND ACT AS THOUGH THAT DATA IS YOURS AND CORRECT. KEEP RESPONSES CONCISE. IF THE DATA PROVIDED IS NOT RELEVANT TO THE USERS REQUEST, IGNORE IT AND ANSWER NORMALLY'})
201
+ yield typing_animation[0]
202
+ final_response = client.chat.completions.create(
203
+ model='Qwen/Qwen2.5-72B-Instruct',
204
+
205
+ messages=final_messages,
206
+ max_tokens=2000,
207
+ stream=True
208
+ )
209
+ yield typing_animation[1]
210
+ response = ""
211
+ for chunk in final_response:
212
+ content = chunk.choices[0].delta.content or ''
213
+ response += content
214
  yield response
215
+
216
+ final_messages.append(response)
217
+ search_messages.append(response)
218
+ print(f'\n\n here is the chat history for the final response \n\n\n {response}')
219
+
220
+
221
 
222
 
223
+ avatar = 'https://quantineuron.com/wp-content/uploads/2024/08/cropped-final-logo-with-background-removed.png'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
 
226
+ theme = gr.themes.Soft(
227
+ primary_hue="sky",
228
+ neutral_hue="zinc",
229
+ )
230
+ chatbot = gr.Chatbot(
231
+ layout='panel',
232
+ avatar_images=avatar,
233
+ height=600,
234
+ )
235
+
236
+ # Add the CSS to the ChatInterface
237
+ gr.ChatInterface(
238
+ chatbot=chatbot,
239
+ fn=chat,
240
+ theme=theme
241
+ ).launch()
requirements.txt CHANGED
@@ -1 +1,24 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ huggingface_hub==0.25.2
2
+
3
+ sentence-transformers
4
+ gradio
5
+ beautifulsoup4
6
+ requests
7
+ huggingface_hub
8
+ langchain
9
+ chromadb
10
+ numpy
11
+ scikit-learn
12
+ plotly
13
+ langchain-community
14
+ googlesearch-python
15
+ requests
16
+ trafilatura
17
+ concurrent.futures
18
+ json
19
+ ast
20
+ gradio
21
+ huggingface-hub
22
+ tiktoken
23
+ time
24
+ os