Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -14,13 +14,15 @@ from langchain.schema import Document
|
|
14 |
from langchain.embeddings import OpenAIEmbeddings
|
15 |
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
|
16 |
from langchain.vectorstores import FAISS
|
17 |
-
from langchain.chains import ConversationalRetrievalChain,RetrievalQA
|
18 |
from langchain.prompts import PromptTemplate
|
19 |
from langchain.prompts.prompt import PromptTemplate
|
20 |
from langchain.chat_models import ChatOpenAI
|
|
|
21 |
|
22 |
def load_model():
|
23 |
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
|
|
|
24 |
model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True).quantize(bits=4, compile_parallel_kernel=True, parallel_num=2).float()
|
25 |
model = model.eval()
|
26 |
return tokenizer,model
|
@@ -32,11 +34,11 @@ def chat_glm(input, history=None):
|
|
32 |
|
33 |
tokenizer,model = load_model()
|
34 |
response, history = model.chat(tokenizer, input, history)
|
35 |
-
logger.
|
36 |
return history, history
|
37 |
|
38 |
def search_web(query):
|
39 |
-
logger.
|
40 |
results = ddg(query)
|
41 |
web_content = ''
|
42 |
if results:
|
@@ -44,55 +46,46 @@ def search_web(query):
|
|
44 |
web_content += result['body']
|
45 |
return web_content
|
46 |
|
47 |
-
def
|
48 |
-
|
49 |
-
history = []
|
50 |
-
history = [] # 4097 tokens limit
|
51 |
embedding_model_name = 'GanymedeNil/text2vec-large-chinese'
|
52 |
vec_path = 'cache'
|
53 |
embeddings = HuggingFaceEmbeddings(model_name=embedding_model_name)
|
54 |
-
|
55 |
-
if use_web:
|
56 |
-
web_content = search_web(input)
|
57 |
-
else:
|
58 |
-
web_content = None
|
59 |
-
web_content = None # 4097 tokens limit
|
60 |
-
if web_content:
|
61 |
-
prompt_template = f"""基于以下已知信息,简洁和专业的来回答用户的问题。
|
62 |
-
如果无法从中得到答案,请说 "根据已知信息无法回答该问题" 或 "没有提供足够的相关信息",不允许在答案中添加编造成分,答案请使用中文。
|
63 |
-
已知网络检索内容:{web_content}""" + """
|
64 |
-
已知内容:
|
65 |
-
{context}
|
66 |
-
问题:
|
67 |
-
{question}"""
|
68 |
-
else:
|
69 |
-
prompt_template = """基于以下已知信息,请简洁并专业地回答用户的问题。
|
70 |
-
如果无法从中得到答案,请说 "根据已知信息无法回答该问题" 或 "没有提供足够的相关信息"。不允许在答案中添加编造成分。另外,答案请使用中文。
|
71 |
-
已知内容:
|
72 |
-
{context}
|
73 |
-
问题:
|
74 |
-
{question}"""
|
75 |
-
|
76 |
-
prompt = PromptTemplate(template=prompt_template,input_variables=["context", "question"])
|
77 |
vector_store = FAISS.load_local(vec_path,embeddings)
|
|
|
|
|
|
|
|
|
78 |
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
return_source_documents=True
|
84 |
-
)
|
85 |
|
86 |
-
|
87 |
-
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
def predict(input,
|
91 |
large_language_model,
|
92 |
use_web,
|
|
|
93 |
openai_key,
|
94 |
history=None):
|
95 |
-
logger.
|
96 |
if openai_key is not None:
|
97 |
os.environ['OPENAI_API_KEY'] = openai_key
|
98 |
else:
|
@@ -101,11 +94,14 @@ def predict(input,
|
|
101 |
history = []
|
102 |
|
103 |
if large_language_model == "GPT-3.5-turbo":
|
104 |
-
resp = chat_gpt(input, use_web, history)
|
105 |
elif large_language_model == "ChatGLM-6B-int4":
|
106 |
-
resp = chat_glm(input, history)
|
|
|
107 |
elif large_language_model == "Search Web":
|
108 |
resp = search_web(input)
|
|
|
|
|
109 |
|
110 |
history.append((input, resp))
|
111 |
return '', history, history
|
@@ -125,12 +121,15 @@ with block as demo:
|
|
125 |
model_choose = gr.Accordion("模型选择")
|
126 |
with model_choose:
|
127 |
large_language_model = gr.Dropdown(
|
128 |
-
["ChatGLM-6B-int4","GPT-3.5-turbo","Search Web"],
|
129 |
label="large language model",
|
130 |
value="ChatGLM-6B-int4")
|
131 |
use_web = gr.Radio(["True", "False"],
|
132 |
label="Web Search",
|
133 |
value="False")
|
|
|
|
|
|
|
134 |
openai_key = gr.Textbox(label="请输入OpenAI API key", type="password")
|
135 |
with gr.Column(scale=4):
|
136 |
chatbot = gr.Chatbot(label='ChatLLM').style(height=600)
|
@@ -143,7 +142,7 @@ with block as demo:
|
|
143 |
|
144 |
send.click(predict,
|
145 |
inputs=[
|
146 |
-
message, large_language_model, use_web, openai_key, state
|
147 |
],
|
148 |
outputs=[message, chatbot, state])
|
149 |
clear_history.click(fn=clear_session,
|
@@ -153,7 +152,7 @@ with block as demo:
|
|
153 |
|
154 |
message.submit(predict,
|
155 |
inputs=[
|
156 |
-
message, large_language_model, use_web, openai_key, state
|
157 |
],
|
158 |
outputs=[message, chatbot, state])
|
159 |
gr.Markdown("""提醒:<br>
|
|
|
14 |
from langchain.embeddings import OpenAIEmbeddings
|
15 |
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
|
16 |
from langchain.vectorstores import FAISS
|
17 |
+
from langchain.chains import ConversationalRetrievalChain,RetrievalQA,LLMChain
|
18 |
from langchain.prompts import PromptTemplate
|
19 |
from langchain.prompts.prompt import PromptTemplate
|
20 |
from langchain.chat_models import ChatOpenAI
|
21 |
+
from langchain import OpenAI,VectorDBQA
|
22 |
|
23 |
def load_model():
|
24 |
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
|
25 |
+
# gpu:.half().cuda()
|
26 |
model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True).quantize(bits=4, compile_parallel_kernel=True, parallel_num=2).float()
|
27 |
model = model.eval()
|
28 |
return tokenizer,model
|
|
|
34 |
|
35 |
tokenizer,model = load_model()
|
36 |
response, history = model.chat(tokenizer, input, history)
|
37 |
+
logger.debug("chatglm:", input,response)
|
38 |
return history, history
|
39 |
|
40 |
def search_web(query):
|
41 |
+
logger.debug("searchweb:", query)
|
42 |
results = ddg(query)
|
43 |
web_content = ''
|
44 |
if results:
|
|
|
46 |
web_content += result['body']
|
47 |
return web_content
|
48 |
|
49 |
+
def search_vec(query):
|
50 |
+
logger.debug("searchvec:", query)
|
|
|
|
|
51 |
embedding_model_name = 'GanymedeNil/text2vec-large-chinese'
|
52 |
vec_path = 'cache'
|
53 |
embeddings = HuggingFaceEmbeddings(model_name=embedding_model_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
vector_store = FAISS.load_local(vec_path,embeddings)
|
55 |
+
|
56 |
+
qa = VectorDBQA.from_chain_type(llm=OpenAI(), chain_type="stuff", vectorstore=vector_store,return_source_documents=True)
|
57 |
+
result = qa({"query": query})
|
58 |
+
return result
|
59 |
|
60 |
+
def chat_gpt(input, use_web, use_vec, history=None):
|
61 |
+
if history is None:
|
62 |
+
history = []
|
63 |
+
# history = [] # 4097 tokens limit
|
|
|
|
|
64 |
|
65 |
+
context = "无"
|
66 |
+
if use_vec:
|
67 |
+
context = search_vec(input)['result']
|
68 |
+
prompt_template = f"""基于以下已知信息,请简洁并专业地回答用户的问题。
|
69 |
+
如果无法从中得到答案,请说 "根据已知信息无法回答该问题" 或 "没有提供足够的相关信息"。若答案中存在编造成分,请在该部分开头添加“据我推测”。另外,答案请使用中文。
|
70 |
+
已知内容:
|
71 |
+
{context}"""+"""
|
72 |
+
问题:
|
73 |
+
{question}"""
|
74 |
+
|
75 |
+
prompt = PromptTemplate(template=prompt_template,input_variables=["question"])
|
76 |
+
|
77 |
+
llm = OpenAI(temperature = 0.2)
|
78 |
+
chain = LLMChain(llm=llm, prompt=prompt)
|
79 |
+
result = chain.run(text)
|
80 |
+
return result
|
81 |
|
82 |
def predict(input,
|
83 |
large_language_model,
|
84 |
use_web,
|
85 |
+
use_vec,
|
86 |
openai_key,
|
87 |
history=None):
|
88 |
+
logger.debug("predict..",large_language_model,use_web)
|
89 |
if openai_key is not None:
|
90 |
os.environ['OPENAI_API_KEY'] = openai_key
|
91 |
else:
|
|
|
94 |
history = []
|
95 |
|
96 |
if large_language_model == "GPT-3.5-turbo":
|
97 |
+
resp = chat_gpt(input, use_web, use_vec, history)
|
98 |
elif large_language_model == "ChatGLM-6B-int4":
|
99 |
+
_,resp = chat_glm(input, history)
|
100 |
+
resp = resp[-1][1]
|
101 |
elif large_language_model == "Search Web":
|
102 |
resp = search_web(input)
|
103 |
+
elif large_language_model == "Search VectorStore":
|
104 |
+
resp = search_vec(input)
|
105 |
|
106 |
history.append((input, resp))
|
107 |
return '', history, history
|
|
|
121 |
model_choose = gr.Accordion("模型选择")
|
122 |
with model_choose:
|
123 |
large_language_model = gr.Dropdown(
|
124 |
+
["ChatGLM-6B-int4","GPT-3.5-turbo","Search Web","Search VectorStore"],
|
125 |
label="large language model",
|
126 |
value="ChatGLM-6B-int4")
|
127 |
use_web = gr.Radio(["True", "False"],
|
128 |
label="Web Search",
|
129 |
value="False")
|
130 |
+
use_vec = gr.Radio(["True", "False"],
|
131 |
+
label="VectorStore Search",
|
132 |
+
value="False")
|
133 |
openai_key = gr.Textbox(label="请输入OpenAI API key", type="password")
|
134 |
with gr.Column(scale=4):
|
135 |
chatbot = gr.Chatbot(label='ChatLLM').style(height=600)
|
|
|
142 |
|
143 |
send.click(predict,
|
144 |
inputs=[
|
145 |
+
message, large_language_model, use_web, use_vec, openai_key, state
|
146 |
],
|
147 |
outputs=[message, chatbot, state])
|
148 |
clear_history.click(fn=clear_session,
|
|
|
152 |
|
153 |
message.submit(predict,
|
154 |
inputs=[
|
155 |
+
message, large_language_model, use_web, use_vec, openai_key, state
|
156 |
],
|
157 |
outputs=[message, chatbot, state])
|
158 |
gr.Markdown("""提醒:<br>
|