KashiwaByte commited on
Commit
b994311
·
1 Parent(s): 0a1500d

Upload 12 files

Browse files
README.md CHANGED
@@ -1,13 +1,12 @@
1
  ---
2
- title: SparkDebate V2.0
3
- emoji: 👁
4
- colorFrom: yellow
5
  colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 3.43.2
8
  app_file: app.py
9
  pinned: false
10
- license: apache-2.0
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: SparkDebate
3
+ emoji: 🌖
4
+ colorFrom: pink
5
  colorTo: yellow
6
  sdk: gradio
7
+ sdk_version: 3.39.0
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.memory import ConversationSummaryBufferMemory
2
+ from langchain.chains import ConversationChain
3
+ from langchain.chains import RetrievalQA
4
+ from utils.API import Spark_forlangchain
5
+ import gradio as gr
6
+ from langchain.prompts import ChatPromptTemplate
7
+ from langchain.document_loaders import TextLoader
8
+ from langchain.embeddings.huggingface import HuggingFaceEmbeddings
9
+ from langchain.vectorstores import FAISS
10
+ import sentence_transformers
11
+
12
+
13
+ def init_knowledge_vector_store(filepath):
14
+ EMBEDDING_MODEL = "model/text2vec_ernie/"
15
+ embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
16
+ embeddings.client = sentence_transformers.SentenceTransformer(
17
+ embeddings.model_name, device='cuda')
18
+ loader = TextLoader(filepath)
19
+ docs = loader.load()
20
+ vector_store = FAISS.from_documents(docs, embeddings)
21
+ return vector_store
22
+
23
+
24
+ template_1 = """
25
+ 你是一个资深辩手,你的辩论风格是{style},你确定辩论战略需要考虑以下10个方面:
26
+ 1. 分析辩题性质
27
+ 判断辩题是判断型还是比较型,明确需要论证的核心观点。回答中必须包含题是判断型还是比较型。
28
+ 2. 判断正反方定位
29
+ 大致判断哪一方更容易证成立,存在明显优劣势。回答中必须需给出谁更主流,更容易成立。
30
+ 3. 设想核心争议点
31
+ 思考双方可能存在分歧和交锋的主要争议点。回答中需要明确给出至少三个争议点。
32
+ 4. 论证框架
33
+ 设计初步的论证框架,包括定义、标准、论点等。回答中需要明确按以下格式给出论证框架:正方:标准是XXX,论点1是XXX,论点2是XXX。反方:标准是XXX,论点1是XXX,论点2是XXX。(论点至少要两个)
34
+ 5. 优势论域
35
+ 确定自己方更容易取得优势的论域的诠释点。回答中必须详细给出双方的优势论域并给出理由。
36
+ 6. 数据准备
37
+ 提前准备论证所需的证据数据。回答中必须给出对论证起作用的数据,如相关国家合法化情况与对社会影响的数据
38
+ 7. 情境假设
39
+ 设想场景和例子以备交锋时使用。回答中必须至少给出正反双方情境,各三个。
40
+ 8. 语境处理
41
+ 考虑如何处理语境环境,为自己创造有利条件。回答中必须举出正反方的语境,各三个。
42
+ 9. 质询角度
43
+ 提前想好可能的质询角度,对应对方的论点。回答中需要给出详细的分析并试着举出例子,各三个。
44
+ 10. 重点突破
45
+ 找到对方可能论证的薄弱点,准备重点突破。回答中需要举出正反双方薄弱点分别在哪里,应该如何突破。
46
+ 通过上述分析,可以确定一个明确有针对性的辩论战略.
47
+ 接下来我会给你一个具体的辩题,你需要基于以上10个原则依次回答。
48
+ ///辩题内容如下:{text}///
49
+ """
50
+ template_2 = """
51
+ 你是一个资深辩手,你的辩论风格是{style},你立论会遵循以下的立论原则,总共5个原则:
52
+ 1.定义明确
53
+ 对关键词进行明确且合理的定义,这是展开论证的基础。
54
+ 2.标准清晰
55
+ 设置公正合理的判断标准,标准要具体明确,为论点比较提供依据。你的回答中必须包含标准。
56
+ 3.论点匹配
57
+ 论点要能有效支撑并印证标准,与标准和立场高度契合。你的回答中必须包含支撑印证标准的论点。
58
+ 4.论据具体
59
+ 提供具体可信的论据支撑每个论点,使之更有说服力。你的论点必须要论据支撑。
60
+ 5.情境适用
61
+ 引入情境和例子,使复杂观点容易被听众接受。你的回答可以适当包含情境
62
+ 接下来会给你一个题目和持方。
63
+ ///题目与持方如下:{text}///
64
+ 你需要遵循以上五个立论原则立论,并且立论稿有以下要求:
65
+ 1.以一个专业辩手的口吻做开场白。
66
+ 2.总字数为1200字。
67
+ 3.第一段需要包含以下三个部分 给出持方,对名词做出简单解释,给出标准,标准只能有一个。
68
+ 4.第二段是第一个论点,论点需要围绕标准,阐述完论点后需要提出论据,最好是数据论据和学理论据,提出论据后需要做出解释来进行论证。参照以下流程:论点1+数据论据+数据论据的论证+学理论据+学理论据的论证。本段需要非常详细。
69
+ 5.第三段是第二个论点,论点需要围绕标准,本段第一句话就要阐明论点是什么,阐述完论点后需要提出论据,最好是数据论据和学理论据,提出论据后需要做出解释来进行论证。参照以下流程:论点2+数据论据+数据论据的论证+学理论据+学理论据的论证。本段需要非常详细。
70
+ 6.最后一段只需要用一句话再重复一遍己方的立场:“综上我方坚定认为XXX”。XXX为立场。
71
+ 7.立论稿中需要把上述内容衔接流畅。
72
+ """
73
+ template_3 = """
74
+ 你是一个资深的逻辑性很强的顶级辩手,你的辩论风格是{style},请对我的陈述进行反驳,越详细越好,反驳需要逐条反驳观点和论据,并且要给出详细的理由,质疑数据论据要用上常用的方法和句式,从数据合理性,样本代表性,统计方法,数据解读等多个角度进行考虑。质疑学理论据要从权威性,解读方式,是否有对抗学理等多个角度进行考虑。
75
+ ///如下是我们的话题以及我的观点:{text}///
76
+ """
77
+ template_4 = """
78
+ 你是一个资深辩手,你的辩论风格是{style},你需要根据我给出的话题提出观点并且要有数据论据和学理论据作为论证且总字数不少于400字,你的发言格式为:我们的话题是什么,我持什么观点,我的理由是XXX,因为某某数据,又因为某某学理。参照如下范例:||
79
+ 我们的话题是人工智能对人类工作的影响。我持的观点是,人工智能将导致大量的就业机会减少。我的理由是,根据国际数据公司(IDC)的报告,到2025年,全球约有3.75亿个工作岗位将被自动化技术取代。同时,人工智能的发展也将带来新的就业机会,如AI工程师、数据科学家等。
80
+ 首先,让我们从数据角度来看。根据美国劳工统计局(BLS)的数据,自20世纪90年代以来,美国的工作岗位流失率一直在上升。其中,自动化和计算机化在一定程度上对就业市场产生了负面影响。此外,根据麦肯锡全球研究院的预测,到2030年,人工智能可能会在全球范围内导致8000万至1.6亿个工作岗位的消失。
81
+ 其次,从学理角度来看,人工智能的发展是基于算法和大数据的。然而,这些算法和数据往往受到人为因素的影响,可能导致错误的决策和预测。例如,2016年在美国总统选举期间,一家名为“剑桥分析”的公司利用大数据分析和选民心理研究,为特朗普竞选团队提供了策略支持。这一事件表明,人工智能在某些情况下可能会被用于不道德的目的。||
82
+ ///我们本次讨论的话题是{text}///
83
+ """
84
+ template_5 = """
85
+ 你是一个资深的逻辑性很强的顶级辩手,你的辩论风格是{style},可以与我进行辩论训练,你很擅长质询总是一针见血,而且也很擅长使用类比来归谬我的观点,你熟练的掌握各种数据质询的技巧。现在你要与我进行对辩
86
+ 我的陈述如下:///{text}///
87
+ 请对我的陈述进行反驳,越详细越好,反驳需要逐条反驳观点和论据,并且要给出详细的理由,质疑数据论据要用上常用的方法和句式,从数据合理性,样本代表性,统计方法,数据解读等多个角度进行考虑。质疑学理论据要从权威性,解读方式,是否有对抗学理等多个角度进行考虑。
88
+ """
89
+ end_prompt = """
90
+ 请你对我们的对辩过程进行总结,总结需要包括以下部分:1.对辩主要针对什么进行讨论。2.评价我的对辩能力,需要根据评级原则给出评级,并且给出具体理由。评级原则如下:等级一,缺乏论证的反驳;等级二,自说自话的反驳;等级三,针锋相对的反驳;等级四,正中要害的反驳。3.根据我的对辩能力提出一定的建议。
91
+ 示例如下:
92
+ 好的,我来对我们的对辩过程进行总结。
93
+ 在我们的对辩过程中,我们主要讨论了动物园是否应该被禁止。我认为动物园对动物的福利和权利造成了负面影响,而您则提出了一些质疑,认为动物园中的动物可以享受比野外更安全的生活条件。
94
+ 我认为您的对辩能力属于等级三,即针锋相对的反驳。您能够对我的观点提出一些质疑和反驳,并且能够给出一些合理的理由。但是,在某些情况下,您可能会使用一些不太恰当的类比来归谬我的观点,这可能会影响到对辩的质量和效果。
95
+ 鉴于您的对辩能力,我认为您可以进一步提高自己的辩论技巧。您可以通过更多的阅读和学习,提高自己的知识水平和思维能力,从而更好地进行论证和反驳。此外,在使用类比和比喻时,需要更加谨慎,确保它们能够恰当地表达您的观点,而不会歪曲或归谬对方的观点。
96
+ """
97
+ prompt_1 = ChatPromptTemplate.from_template(template_1)
98
+ prompt_2 = ChatPromptTemplate.from_template(template_2)
99
+ prompt_3 = ChatPromptTemplate.from_template(template_3)
100
+ prompt_4 = ChatPromptTemplate.from_template(template_4)
101
+ prompt_5 = ChatPromptTemplate.from_template(template_5)
102
+
103
+
104
+ def init_(app_id, api_key, api_secret):
105
+ global llm
106
+ llm = Spark_forlangchain(n=10, app_id=app_id, api_key=api_key,
107
+ api_secret=api_secret)
108
+ memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=4096)
109
+ global conversation_1
110
+ global conversation_2
111
+ global conversation_3
112
+ conversation_1 = ConversationChain(llm=llm)
113
+ conversation_2 = ConversationChain(llm=llm, memory=memory)
114
+ print("初始化成功!")
115
+
116
+
117
+ def shortDebate_(type, style, prompt, help):
118
+ if type == "破题":
119
+ msg = prompt_1.format_prompt(text=prompt, style=style).to_string()
120
+ elif type == "立论":
121
+ msg = prompt_2.format_prompt(text=prompt, style=style).to_string()
122
+ elif type == "对辩先发":
123
+ msg = prompt_3.format_prompt(text=prompt, style=style).to_string()
124
+ elif type == "对辩后发":
125
+ msg = prompt_4.format_prompt(text=prompt, style=style).to_string()
126
+ else:
127
+ msg = prompt
128
+ print(msg)
129
+ response = conversation_1.run(msg)
130
+ print(response)
131
+ help.append((prompt, response))
132
+ return help, help
133
+
134
+
135
+ def longDebate_(style, prompt, help):
136
+ msg = prompt_5.format_prompt(text=prompt, style=style).to_string()
137
+ response = conversation_2.run(msg)
138
+ help.append((prompt, response))
139
+ return help, help
140
+
141
+
142
+ def end_talk(style, prompt, help):
143
+ msg = end_prompt
144
+ response = conversation_2.run(msg)
145
+ help.append((prompt, response))
146
+ return help, help
147
+
148
+
149
+ def Debatebytext_(prompt, help):
150
+ msg = prompt
151
+ response = QA_chain.run(msg)
152
+ help.append((prompt, response))
153
+ return help, help
154
+
155
+
156
+ def upload_file(files):
157
+ vector_store = init_knowledge_vector_store(files.name)
158
+ memory_text = ConversationSummaryBufferMemory(
159
+ llm=llm, max_token_limit=4096)
160
+ global QA_chain
161
+ QA_chain = RetrievalQA.from_llm(llm=llm, retriever=vector_store.as_retriever(
162
+ search_kwargs={"k": 2}), memory=memory_text)
163
+ file_paths = [file.name for file in files]
164
+ return file_paths
165
+
166
+
167
+ with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as init:
168
+ with gr.Row():
169
+ app_id = gr.Textbox(
170
+ lines=1, placeholder="app_id Here...", label="app_id")
171
+ api_key = gr.Textbox(
172
+ lines=1, placeholder="api_key Here...", label="api_key")
173
+ api_secret = gr.Textbox(
174
+ lines=1, placeholder="api_secret Here...", label="api_secret")
175
+ temperature = gr.Slider(minimum=0, maximum=1,
176
+ step=0.1, value=0.3, interactive=True)
177
+ btn = gr.Button(value="初始化")
178
+ btn.click(init_, inputs=[app_id, api_key, api_secret])
179
+
180
+ with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as shortDebate:
181
+ chatbot = gr.Chatbot(elem_id="chatbot")
182
+ state = gr.State([])
183
+ drop1 = gr.Radio(["破题", "立论", "对辩先发", "对辩后发"],
184
+ label="功能选择", info="选择你想要的功能") # 单选
185
+ with gr.Row():
186
+ txt = gr.Textbox(show_label="在这里开始聊天吧", placeholder="请输入你的问题")
187
+ send = gr.Button("🚀 发送")
188
+ style = gr.Textbox(lines=1, placeholder="style Here... ",
189
+ label="辩论风格", value="犀利", interactive=True)
190
+ send.click(shortDebate_, [drop1, style, txt, state], [chatbot, state])
191
+
192
+ with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as longDebate:
193
+ chatbot = gr.Chatbot(elem_id="chatbot")
194
+ state = gr.State([])
195
+ with gr.Row():
196
+ txt = gr.Textbox(show_label="在这里开始长辩论吧", placeholder="请输入你的问题")
197
+ send = gr.Button("🚀 发送")
198
+ end = gr.Button("🤠 总结")
199
+ style = gr.Textbox(lines=1, placeholder="style Here... ",
200
+ label="辩论风格", value="犀利", interactive=True)
201
+ send.click(longDebate_, [style, txt, state], [chatbot, state])
202
+ end.click(end_talk, [style, txt, state], [chatbot, state])
203
+
204
+ with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as Debatebytext:
205
+ chatbot = gr.Chatbot(elem_id="chatbot")
206
+ state = gr.State([])
207
+ file_output = gr.File(label='请上传文件, 目前支持txt、docx、md格式',
208
+ file_types=['.txt', '.md', '.docx'])
209
+ with gr.Row():
210
+ txt = gr.Textbox(show_label="在这里从你给出的资料里学习吧", placeholder="请输入你的问题")
211
+ send = gr.Button("🚀 发送")
212
+ upload_button = gr.UploadButton("Click to Upload a File", scale=1, file_types=[
213
+ "text"])
214
+ upload_button.upload(upload_file, upload_button, file_output)
215
+ send.click(Debatebytext_, [txt, state], [chatbot, state])
216
+ demo = gr.TabbedInterface([init, shortDebate, longDebate, Debatebytext], [
217
+ "初始化", "辅助辩论", "对辩练习", "辩论技巧学习"])
218
+ demo.launch()
demo.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from utils.API import SparkAPI
2
+ app_id = input("app_id here :")
3
+ api_key = input("api_key here :")
4
+ api_secret = input("api_secret here :")
5
+ bot = SparkAPI(app_id=app_id ,api_key=api_key ,api_secret=api_secret)
6
+ bot.chat_stream()
model/text2vec_ernie/config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attention_probs_dropout_prob": 0.1,
3
+ "hidden_act": "gelu",
4
+ "hidden_dropout_prob": 0.1,
5
+ "intermediate_size": 4096,
6
+ "hidden_size": 1024,
7
+ "initializer_range": 0.02,
8
+ "max_position_embeddings": 2048,
9
+ "num_attention_heads": 16,
10
+ "num_hidden_layers": 20,
11
+ "task_type_vocab_size": 16,
12
+ "type_vocab_size": 4,
13
+ "use_task_id": true,
14
+ "vocab_size": 40000,
15
+ "layer_norm_eps": 1e-05,
16
+ "model_type": "ernie",
17
+ "architectures": [
18
+ "ErnieForMaskedLM"
19
+ ]
20
+ }
model/text2vec_ernie/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio==3.39.0
2
+ langchain==0.0.252
3
+ sentence_transformers==2.2.2
4
+ websocket_client==1.6.1
utils/API.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import base64
3
+ import hmac
4
+ import json
5
+ from datetime import datetime, timezone
6
+ from urllib.parse import urlencode, urlparse
7
+ from websocket import create_connection, WebSocketConnectionClosedException
8
+ from utils.tools import get_prompt, process_response, init_script, create_script
9
+
10
+
11
+ class SparkAPI:
12
+ __api_url = 'ws(s)://spark-api.xf-yun.com/v2.1/chat'
13
+ __max_token = 4096
14
+
15
+ def __init__(self, app_id, api_key, api_secret):
16
+ self.__app_id = app_id
17
+ self.__api_key = api_key
18
+ self.__api_secret = api_secret
19
+
20
+ def __set_max_tokens(self, token):
21
+ if isinstance(token, int) is False or token < 0:
22
+ print("set_max_tokens() error: tokens should be a positive integer!")
23
+ return
24
+ self.__max_token = token
25
+
26
+ def __get_authorization_url(self):
27
+ authorize_url = urlparse(self.__api_url)
28
+ # 1. generate data
29
+ date = datetime.now(timezone.utc).strftime('%a, %d %b %Y %H:%M:%S %Z')
30
+
31
+ """
32
+ Generation rule of Authorization parameters
33
+ 1) Obtain the APIKey and APISecret parameters from the console.
34
+ 2) Use the aforementioned date to dynamically concatenate a string tmp. Here we take Huobi's URL as an example,
35
+ the actual usage requires replacing the host and path with the specific request URL.
36
+ """
37
+ signature_origin = "host: {}\ndate: {}\nGET {} HTTP/1.1".format(
38
+ authorize_url.netloc, date, authorize_url.path
39
+ )
40
+ signature = base64.b64encode(
41
+ hmac.new(
42
+ self.__api_secret.encode(),
43
+ signature_origin.encode(),
44
+ digestmod='sha256'
45
+ ).digest()
46
+ ).decode()
47
+ authorization_origin = \
48
+ 'api_key="{}",algorithm="{}",headers="{}",signature="{}"'.format(
49
+ self.__api_key, "hmac-sha256", "host date request-line", signature
50
+ )
51
+ authorization = base64.b64encode(
52
+ authorization_origin.encode()).decode()
53
+ params = {
54
+ "authorization": authorization,
55
+ "date": date,
56
+ "host": authorize_url.netloc
57
+ }
58
+
59
+ ws_url = self.__api_url + "?" + urlencode(params)
60
+ return ws_url
61
+
62
+ def __build_inputs(
63
+ self,
64
+ message: dict,
65
+ user_id: str = "001",
66
+ domain: str = "general",
67
+ temperature: float = 0.5,
68
+ max_tokens: int = 4096
69
+ ):
70
+ input_dict = {
71
+ "header": {
72
+ "app_id": self.__app_id,
73
+ "uid": user_id,
74
+ },
75
+ "parameter": {
76
+ "chat": {
77
+ "domain": domain,
78
+ "temperature": temperature,
79
+ "max_tokens": max_tokens,
80
+ }
81
+ },
82
+ "payload": {
83
+ "message": message
84
+ }
85
+ }
86
+ return json.dumps(input_dict)
87
+
88
+ def chat(
89
+ self,
90
+ query: str,
91
+ history: list = None, # store the conversation history
92
+ user_id: str = "001",
93
+ domain: str = "general",
94
+ max_tokens: int = 4096,
95
+ temperature: float = 0.5,
96
+ ):
97
+ if history is None:
98
+ history = []
99
+
100
+ # the max of max_length is 4096
101
+ max_tokens = min(max_tokens, 4096)
102
+ url = self.__get_authorization_url()
103
+ ws = create_connection(url)
104
+ message = get_prompt(query, history)
105
+ input_str = self.__build_inputs(
106
+ message=message,
107
+ user_id=user_id,
108
+ domain=domain,
109
+ temperature=temperature,
110
+ max_tokens=max_tokens,
111
+ )
112
+ ws.send(input_str)
113
+ response_str = ws.recv()
114
+ try:
115
+ while True:
116
+ response, history, status = process_response(
117
+ response_str, history)
118
+ """
119
+ The final return result, which means a complete conversation.
120
+ doc url: https://www.xfyun.cn/doc/spark/Web.html#_1-%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
121
+ """
122
+ if len(response) == 0 or status == 2:
123
+ break
124
+ response_str = ws.recv()
125
+ return response
126
+
127
+ except WebSocketConnectionClosedException:
128
+ print("Connection closed")
129
+ finally:
130
+ ws.close()
131
+ # Stream output statement, used for terminal chat.
132
+
133
+ def streaming_output(
134
+ self,
135
+ query: str,
136
+ history: list = None, # store the conversation history
137
+ user_id: str = "001",
138
+ domain: str = "general",
139
+ max_tokens: int = 4096,
140
+ temperature: float = 0.5,
141
+ ):
142
+ if history is None:
143
+ history = []
144
+ # the max of max_length is 4096
145
+ max_tokens = min(max_tokens, 4096)
146
+ url = self.__get_authorization_url()
147
+ ws = create_connection(url)
148
+
149
+ message = get_prompt(query, history)
150
+ input_str = self.__build_inputs(
151
+ message=message,
152
+ user_id=user_id,
153
+ domain=domain,
154
+ temperature=temperature,
155
+ max_tokens=max_tokens,
156
+ )
157
+ # print(input_str)
158
+ # send question or prompt to url, and receive the answer
159
+ ws.send(input_str)
160
+ response_str = ws.recv()
161
+
162
+ # Continuous conversation
163
+ try:
164
+ while True:
165
+ response, history, status = process_response(
166
+ response_str, history)
167
+ yield response, history
168
+ if len(response) == 0 or status == 2:
169
+ break
170
+ response_str = ws.recv()
171
+
172
+ except WebSocketConnectionClosedException:
173
+ print("Connection closed")
174
+ finally:
175
+ ws.close()
176
+
177
+ def chat_stream(self):
178
+ history = []
179
+ try:
180
+ print("输入init来初始化剧本,输入create来创作剧本,输入exit或stop来终止对话\n")
181
+ while True:
182
+ query = input("Ask: ")
183
+ if query == 'init':
184
+ jsonfile = input("请输入剧本文件路径:")
185
+ script_data = init_script(history, jsonfile)
186
+ print(
187
+ f"正在导入剧本{script_data['name']},角色信息:{script_data['characters']},剧情介绍:{script_data['summary']}")
188
+ query = f"我希望你能够扮演这个剧本杀游戏的主持人,我希望你能够逐步引导玩家到达最终结局,同时希望你在游戏中设定一些随机事件,需要玩家依靠自身的能力解决,当玩家做出偏离主线的行为或者与剧本无关的行为时,你需要委婉地将玩家引导至正常游玩路线中,对于玩家需要决策的事件,你需要提供一些行动推荐,下面是剧本介绍:{script_data}"
189
+ if query == 'create':
190
+ name = input('请输入剧本名称:')
191
+ characters = input('请输入角色信息:')
192
+ summary = input('请输入剧情介绍:')
193
+ details = input('请输入剧本细节')
194
+ create_script(name, characters, summary, details)
195
+ print('剧本创建成功!')
196
+ continue
197
+ if query == "exit" or query == "stop":
198
+ break
199
+ for response, _ in self.streaming_output(query, history):
200
+ print("\r" + response, end="")
201
+ print("\n")
202
+ finally:
203
+ print("\nThank you for using the SparkDesk AI. Welcome to use it again!")
204
+
205
+
206
+ from langchain.llms.base import LLM
207
+ from typing import Any, List, Mapping, Optional
208
+ class Spark_forlangchain(LLM):
209
+
210
+ # 类的成员变量,类型为整型
211
+ n: int
212
+ app_id: str
213
+ api_key: str
214
+ api_secret: str
215
+ # 用于指定该子类对象的类型
216
+
217
+ @property
218
+ def _llm_type(self) -> str:
219
+ return "Spark"
220
+
221
+ # 重写基类方法,根据用户输入的prompt来响应用户,返回字符串
222
+ def _call(
223
+ self,
224
+ query: str,
225
+ history: list = None, # store the conversation history
226
+ user_id: str = "001",
227
+ domain: str = "general",
228
+ max_tokens: int = 4096,
229
+ temperature: float = 0.7,
230
+ stop: Optional[List[str]] = None,
231
+ ) -> str:
232
+ if stop is not None:
233
+ raise ValueError("stop kwargs are not permitted.")
234
+ bot = SparkAPI(app_id=self.app_id, api_key=self.api_key,
235
+ api_secret=self.api_secret)
236
+ response = bot.chat(query, history, user_id,
237
+ domain, max_tokens, temperature)
238
+ return response
239
+
240
+ # 返回一个字典类型,包含LLM的唯一标识
241
+ @property
242
+ def _identifying_params(self) -> Mapping[str, Any]:
243
+ """Get the identifying parameters."""
244
+ return {"n": self.n}
utils/__pycache__/API.cpython-310.pyc ADDED
Binary file (6.6 kB). View file
 
utils/__pycache__/tools.cpython-310.pyc ADDED
Binary file (3.7 kB). View file
 
utils/__pycache__/tools.cpython-37.pyc ADDED
Binary file (1.93 kB). View file
 
utils/tools.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import shutil
4
+ from glob import glob
5
+
6
+ def read_json_file(file_path):
7
+ file_path = "./script/"+file_path
8
+ with open(file_path, 'r', encoding='utf-8') as file:
9
+ data = json.load(file)
10
+ return data
11
+
12
+
13
+ def get_prompt(query: str, history: list):
14
+ use_message = {"role": "user", "content": query}
15
+ if history is None:
16
+ history = []
17
+ history.append(use_message)
18
+ message = {"text": history}
19
+ return message
20
+
21
+
22
+ def process_response(response_str: str, history: list):
23
+ res_dict: dict = json.loads(response_str)
24
+ code = res_dict.get("header", {}).get("code")
25
+ status = res_dict.get("header", {}).get("status", 2)
26
+
27
+ if code == 0:
28
+ res_dict = res_dict.get("payload", {}).get(
29
+ "choices", {}).get("text", [{}])[0]
30
+ res_content = res_dict.get("content", "")
31
+
32
+ if len(res_dict) > 0 and len(res_content) > 0:
33
+ # Ignore the unnecessary data
34
+ if "index" in res_dict:
35
+ del res_dict["index"]
36
+ response = res_content
37
+
38
+ if status == 0:
39
+ history.append(res_dict)
40
+ else:
41
+ history[-1]["content"] += response
42
+ response = history[-1]["content"]
43
+
44
+ return response, history, status
45
+ else:
46
+ return "", history, status
47
+ else:
48
+ print("error code ", code)
49
+ print("you can see this website to know code detail")
50
+ print("https://www.xfyun.cn/doc/spark/%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E.html")
51
+ return "", history, status
52
+
53
+
54
+ def init_script(history: list, jsonfile):
55
+ script_data = read_json_file(jsonfile)
56
+ return script_data
57
+
58
+
59
+ def create_script(name, characters, summary, details):
60
+
61
+ import os
62
+ if not os.path.exists("script"):
63
+ os.mkdir("script")
64
+ data = {
65
+ "name": name,
66
+ "characters": characters,
67
+ "summary": summary,
68
+ "details": details
69
+ }
70
+ json_data = json.dumps(data, ensure_ascii=False)
71
+ print(json_data)
72
+ with open(f"./script/{name}.json", "w", encoding='utf-8') as file:
73
+ file.write(json_data)
74
+ pass
75
+
76
+
77
+ def txt2vec(name: str, file_path: str):
78
+ from langchain.document_loaders import TextLoader
79
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
80
+ loader = TextLoader(file_path)
81
+ data = loader.load()
82
+ text_splitter = RecursiveCharacterTextSplitter(
83
+ chunk_size=256, chunk_overlap=128)
84
+ split_docs = text_splitter.split_documents(data)
85
+ from langchain.embeddings.huggingface import HuggingFaceEmbeddings
86
+ import sentence_transformers
87
+ EMBEDDING_MODEL = "model/text2vec_ernie/"
88
+ embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
89
+ embeddings.client = sentence_transformers.SentenceTransformer(
90
+ embeddings.model_name, device='cuda')
91
+ from langchain.vectorstores import FAISS
92
+ db = FAISS.from_documents(split_docs, embeddings)
93
+ db.save_local(f"data/faiss/{name}/")
94
+
95
+
96
+ def pdf2vec(name: str, file_path: str):
97
+ from langchain.document_loaders import PyPDFLoader
98
+ loader = PyPDFLoader(file_path)
99
+ split_docs = loader.load_and_split()
100
+ from langchain.embeddings.huggingface import HuggingFaceEmbeddings
101
+ import sentence_transformers
102
+ EMBEDDING_MODEL = "model/text2vec_ernie/"
103
+ embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
104
+ embeddings.client = sentence_transformers.SentenceTransformer(
105
+ embeddings.model_name, device='cuda')
106
+ from langchain.vectorstores import FAISS
107
+ db = FAISS.from_documents(split_docs, embeddings)
108
+ db.save_local(f"data/faiss/{name}/")
109
+ def mycopyfile(srcfile, dstpath): # 复制函数
110
+ if not os.path.isfile(srcfile):
111
+ print("%s not exist!" % (srcfile))
112
+ else:
113
+ fpath, fname = os.path.split(srcfile)
114
+ print(fpath)
115
+ print(fname) # 分离文件名和路径
116
+ if not os.path.exists(dstpath):
117
+ os.makedirs(dstpath) # 创建路径
118
+ shutil.copy(srcfile, dstpath + fname) # 复制文件
119
+ print("copy %s -> %s" % (srcfile, dstpath + fname))