matthoffner commited on
Commit
937b739
·
1 Parent(s): 3fb7a02

Create llm.py

Browse files
Files changed (1) hide show
  1. llm.py +280 -0
llm.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain.llms import LlamaCpp
3
+ from llama_index import (
4
+ GPTVectorStoreIndex,
5
+ GPTVectorStoreIndex,
6
+ GPTListIndex,
7
+ ServiceContext,
8
+ ResponseSynthesizer,
9
+ LangchainEmbedding
10
+ )
11
+ from langchain.embeddings import HuggingFaceEmbeddings
12
+ from llama_index import download_loader, StorageContext, load_index_from_storage
13
+ from llama_index import (
14
+ Document,
15
+ LLMPredictor,
16
+ PromptHelper
17
+ )
18
+ from llama_index.indices.postprocessor import SimilarityPostprocessor
19
+ from llama_index.query_engine import RetrieverQueryEngine
20
+ from llama_index.storage.index_store import SimpleIndexStore
21
+ from llama_index.storage.docstore import SimpleDocumentStore
22
+ from llama_index.storage.storage_context import SimpleVectorStore
23
+
24
+ from googlesearch import search as google_search
25
+
26
+ from utils import *
27
+
28
+ import logging
29
+ import argparse
30
+
31
+ parser = argparse.ArgumentParser()
32
+ parser.add_argument('--model', type=str, required=True)
33
+ args = parser.parse_args()
34
+ model_path = args.model
35
+
36
+
37
+ def query_llm(index, prompt, service_context, retriever_mode='embedding', response_mode='tree_summarize'):
38
+ response_synthesizer = ResponseSynthesizer.from_args(
39
+ service_context=service_context,
40
+ node_postprocessors=[
41
+ SimilarityPostprocessor(similarity_cutoff=0.7)
42
+ ]
43
+ )
44
+ retriever = index.as_retriever(retriever_mode=retriever_mode, service_context=service_context)
45
+ query_engine = RetrieverQueryEngine.from_args(retriever, response_synthesizer=response_synthesizer, response_mode=response_mode, service_context=service_context)
46
+ return query_engine.query(prompt)
47
+
48
+
49
+ def get_documents(file_src):
50
+ documents = []
51
+ logging.debug("Loading documents...")
52
+ print(f"file_src: {file_src}")
53
+ for file in file_src:
54
+ if type(file) == str:
55
+ print(f"file: {file}")
56
+ if "http" in file:
57
+ logging.debug("Loading web page...")
58
+ BeautifulSoupWebReader = download_loader("BeautifulSoupWebReader")
59
+ loader = BeautifulSoupWebReader()
60
+ documents += loader.load_data([file])
61
+ else:
62
+ logging.debug(f"file: {file.name}")
63
+ if os.path.splitext(file.name)[1] == ".pdf":
64
+ logging.debug("Loading PDF...")
65
+ CJKPDFReader = download_loader("CJKPDFReader")
66
+ loader = CJKPDFReader()
67
+ documents += loader.load_data(file=file.name)
68
+ else:
69
+ logging.debug("Loading text file...")
70
+ with open(file.name, "r", encoding="utf-8") as f:
71
+ text = add_space(f.read())
72
+ documents += [Document(text)]
73
+ return documents
74
+
75
+
76
+ def construct_index(
77
+ file_src,
78
+ index_name,
79
+ index_type,
80
+ max_input_size=4096,
81
+ num_outputs=512,
82
+ max_chunk_overlap=20,
83
+ chunk_size_limit=None,
84
+ embedding_limit=None,
85
+ separator=" ",
86
+ num_children=10,
87
+ max_keywords_per_chunk=10
88
+ ):
89
+ chunk_size_limit = None if chunk_size_limit == 0 else chunk_size_limit
90
+ embedding_limit = None if embedding_limit == 0 else embedding_limit
91
+ separator = " " if separator == "" else separator
92
+
93
+ llm = LlamaCpp(model_path=model_path,
94
+ n_ctx=2048,
95
+ use_mlock=True,
96
+ n_parts=-1,
97
+ temperature=0.7,
98
+ top_p=0.40,
99
+ last_n_tokens_size=200,
100
+ n_threads=4,
101
+ f16_kv=True,
102
+ max_tokens=400
103
+ )
104
+ llm_predictor = LLMPredictor(
105
+ llm=llm
106
+ )
107
+ prompt_helper = PromptHelper(
108
+ max_input_size,
109
+ num_outputs,
110
+ max_chunk_overlap,
111
+ embedding_limit,
112
+ chunk_size_limit,
113
+ separator=separator,
114
+ )
115
+ service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor, prompt_helper=prompt_helper)
116
+ documents = get_documents(file_src)
117
+
118
+ try:
119
+ if index_type == "_GPTVectorStoreIndex":
120
+ index = GPTVectorStoreIndex.from_documents(documents, service_context=service_context)
121
+ else:
122
+ index = GPTListIndex.from_documents(documents, service_context=service_context)
123
+ index.storage_context.persist(persist_dir=f"{index_name}")
124
+ except Exception as e:
125
+ print(e)
126
+ return None
127
+
128
+
129
+ newlist = refresh_json_list(plain=True)
130
+ return gr.Dropdown.update(choices=newlist, value=index_name)
131
+
132
+
133
+ def chat_ai(
134
+ index_select,
135
+ question,
136
+ prompt_tmpl,
137
+ refine_tmpl,
138
+ sim_k,
139
+ chat_tone,
140
+ context,
141
+ chatbot,
142
+ search_mode=[],
143
+ ):
144
+ if index_select == "search" and search_mode==[]:
145
+ chatbot.append((question, "❗search"))
146
+ return context, chatbot
147
+
148
+ logging.info(f"Question: {question}")
149
+
150
+ temprature = 2 if chat_tone == 0 else 1 if chat_tone == 1 else 0.5
151
+ if search_mode:
152
+ index_select = search_construct(question, search_mode, index_select)
153
+ logging.debug(f"Index: {index_select}")
154
+ response = ask_ai(
155
+ index_select,
156
+ question,
157
+ prompt_tmpl,
158
+ refine_tmpl,
159
+ sim_k,
160
+ temprature,
161
+ context
162
+ )
163
+ print(response)
164
+
165
+ if response is None:
166
+ response = llm._call(question)
167
+ response = parse_text(response)
168
+
169
+ context.append({"role": "user", "content": question})
170
+ context.append({"role": "assistant", "content": response})
171
+ chatbot.append((question, response))
172
+
173
+ return context, chatbot
174
+
175
+
176
+ def ask_ai(
177
+ index_select,
178
+ question,
179
+ prompt_tmpl,
180
+ refine_tmpl,
181
+ sim_k=1,
182
+ temprature=0,
183
+ prefix_messages=[]
184
+ ):
185
+ logging.debug("Querying index...")
186
+ prompt_helper = PromptHelper(
187
+ 2048,
188
+ 512,
189
+ 20
190
+ )
191
+ llm = LlamaCpp(model_path=model_path,
192
+ n_ctx=2048,
193
+ use_mlock=True,
194
+ n_parts=-1,
195
+ temperature=temprature,
196
+ top_p=0.40,
197
+ last_n_tokens_size=400,
198
+ n_threads=4,
199
+ f16_kv=True,
200
+ max_tokens=200
201
+ )
202
+ embeddings = HuggingFaceEmbeddings(model_kwargs={"device": "mps"})
203
+ embed_model = LangchainEmbedding(embeddings)
204
+ llm_predictor = LLMPredictor(
205
+ llm=llm
206
+ )
207
+ service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor, embed_model=embed_model, prompt_helper=prompt_helper)
208
+ response = None
209
+ logging.debug("Using GPTVectorStoreIndex")
210
+ storage_context = StorageContext.from_defaults(
211
+ docstore=SimpleDocumentStore.from_persist_dir(persist_dir="./index"),
212
+ vector_store=SimpleVectorStore.from_persist_dir(persist_dir="./index"),
213
+ index_store=SimpleIndexStore.from_persist_dir(persist_dir="./index"),
214
+ )
215
+ index = load_index_from_storage(service_context=service_context, storage_context=storage_context)
216
+ response = query_llm(index, question, service_context)
217
+
218
+ if response is not None:
219
+ logging.info(f"Response: {response}")
220
+ ret_text = response.response
221
+ ret_text += "\n----------\n"
222
+ nodes = []
223
+ for index, node in enumerate(response.source_nodes):
224
+ nodes.append(f"[{index+1}] {node.source_text}")
225
+ ret_text += "\n\n".join(nodes)
226
+ return ret_text
227
+ else:
228
+ logging.debug("No response found, returning None")
229
+ return None
230
+
231
+
232
+ def search_construct(question, search_mode, index_select):
233
+ print(f"You asked: {question}")
234
+ llm = LlamaCpp(model_path=model_path,
235
+ n_ctx=500,
236
+ use_mlock=True,
237
+ n_parts=-1,
238
+ temperature=0.5,
239
+ top_p=0.40,
240
+ last_n_tokens_size=400,
241
+ n_threads=4,
242
+ f16_kv=True,
243
+ max_tokens=400
244
+ )
245
+ chat = llm
246
+ search_terms = (
247
+ chat.generate(
248
+ [
249
+ f"Please extract search terms from the user’s question. The search terms is a concise sentence, which will be searched on Google to obtain relevant information to answer the user’s question, too generalized search terms doesn’t help. Please provide no more than two search terms. Please provide the most relevant search terms only, the search terms should directly correspond to the user’s question. Please separate different search items with commas, with no quote marks. The user’s question is: {question}"
250
+ ]
251
+ )
252
+ .generations[0][0]
253
+ .text.strip()
254
+ )
255
+ search_terms = search_terms.replace('"', "")
256
+ search_terms = search_terms.replace(".", "")
257
+ links = []
258
+ for keywords in search_terms.split(","):
259
+ keywords = keywords.strip()
260
+ for search_engine in search_mode:
261
+ if "Google" in search_engine:
262
+ print(f"Googling: {keywords}")
263
+ search_iter = google_search(keywords, num_results=5)
264
+ links += [next(search_iter) for _ in range(10)]
265
+ if "Manual" in search_engine:
266
+ print(f"Searching manually: {keywords}")
267
+ print("Please input links manually. (Enter 'q' to quit.)")
268
+ while True:
269
+ link = input("Enter link:\n")
270
+ if link == "q":
271
+ break
272
+ else:
273
+ links.append(link)
274
+ links = list(set(links))
275
+ if len(links) == 0:
276
+ return index_select
277
+ print("Extracting data from links...")
278
+ print("\n".join(links))
279
+ search_index_name = " ".join(search_terms.split(","))
280
+ construct_index(links, search_index_name, "GPTVectorStoreIndex")