Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import random | |
| import time | |
| from typing import List | |
| from langchain.embeddings.openai import OpenAIEmbeddings | |
| from langchain.vectorstores import FAISS | |
| from langchain.chains import RetrievalQA | |
| from langchain.chat_models import ChatOpenAI | |
| enable_chat = False # 初始化为False | |
| def toggle_enable_chat(): | |
| global enable_chat | |
| enable_chat = not enable_chat | |
| return f"Enable Chat set to {enable_chat}" | |
| def initialize_aliyun_qa_bot(vector_store_dir: str="aliyun_qa"): | |
| print(vector_store_dir) | |
| db = FAISS.load_local(vector_store_dir, OpenAIEmbeddings()) | |
| print(db) | |
| llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0) | |
| global ALIYUN_BOT | |
| ALIYUN_BOT = RetrievalQA.from_chain_type(llm, | |
| retriever=db.as_retriever(search_type="similarity_score_threshold", | |
| search_kwargs={"score_threshold": 0.8})) | |
| # 返回向量数据库的检索结果 | |
| ALIYUN_BOT.return_source_documents = True | |
| return ALIYUN_BOT | |
| def aliyun_chat(message, history): | |
| print(f"[message]{message}") | |
| print(f"[history]{history}") | |
| # TODO: 从命令行参数中获取 | |
| global enable_chat | |
| ans = ALIYUN_BOT({"query": message}) | |
| # 如果检索出结果,或者开了大模型聊天模式 | |
| # 返回 RetrievalQA combine_documents_chain 整合的结果 | |
| if ans["source_documents"] or enable_chat: | |
| print(f"[result]{ans['result']}") | |
| print(f"[source_documents]{ans['source_documents']}") | |
| return ans["result"] | |
| # 否则输出套路话术 | |
| else: | |
| return "基于现有文档数据,无法回答你的问题,请您联系对应的阿里云企业咨询顾问。" | |
| def launch_gradio(): | |
| # 创建 ChatInterface 和其他组件 | |
| chat_interface = gr.ChatInterface( | |
| fn=aliyun_chat, | |
| title="企业数字化转型咨询顾问(aliyun)问答机器人", | |
| examples=["阿里云有没有成熟的方法或者模板能够供我们去把业务价值和底座组件对应起来?","我们要建设中交二航局的数字化底座,阿里云有什么建议","公共云上,EMR和MaxCompute的使用量多少?","阿里公共云上能用maxcompute吗?"], | |
| description='<div style="font-family: \'KaiTi\', \'楷体\', serif; font-size: 18px; color: red;text-align: center;">问答数据基于<a href="https://kdocs.cn/l/cszrR7raahdS" style="font-family: \'KaiTi\', \'楷体\', serif; font-size: 18px; color: blue;">阿里云咨询QA文档</a> 请以官方文档为准。</div>'+'<div style="text-align: center;">\ | |
| <img src="https://i.postimg.cc/y8T53gjr/logo.png" alt="精益价值logo" style="height: 80px; margin:0px auto;"></div>', | |
| # cache_examples=True, | |
| # retry_btn=None, | |
| # undo_btn=None, | |
| chatbot=gr.Chatbot(height=450), | |
| ) | |
| # 创建一个简单的按钮界面来触发 toggle_enable_chat 函数 | |
| toggle_chat_interface = gr.Interface( | |
| fn=toggle_enable_chat, | |
| inputs=gr.Button("Toggle Chat"), | |
| outputs="text" | |
| ) | |
| # 使用 TabbedInterface 来组合聊天界面和设置界面 | |
| demo = gr.TabbedInterface([chat_interface, toggle_chat_interface], | |
| ["Chat", "Settings"]) | |
| demo.launch(auth=("admin", "leanvalue")) | |
| demo.deploy() | |
| if __name__ == "__main__": | |
| # 初始化机器人 | |
| initialize_aliyun_qa_bot("aliyun_qa") | |
| # 启动 Gradio 服务 | |
| launch_gradio() | |