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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import _thread as thread
|
| 2 |
+
import base64
|
| 3 |
+
import datetime
|
| 4 |
+
import hashlib
|
| 5 |
+
import hmac
|
| 6 |
+
import json
|
| 7 |
+
from urllib.parse import urlparse
|
| 8 |
+
import ssl
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from time import mktime
|
| 11 |
+
from urllib.parse import urlencode
|
| 12 |
+
from wsgiref.handlers import format_date_time
|
| 13 |
+
# websocket-client
|
| 14 |
+
import websocket
|
| 15 |
+
|
| 16 |
+
## add
|
| 17 |
+
import gradio as gr
|
| 18 |
+
from gradio.components import Textbox
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
messages = [{"role": "system","question":"question", "content": "You are a helpful and kind AI Assistant."},]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Ws_Param(object):
|
| 25 |
+
# 初始化
|
| 26 |
+
def __init__(self, APPID, APIKey, APISecret, gpt_url):
|
| 27 |
+
self.APPID = APPID
|
| 28 |
+
self.APIKey = APIKey
|
| 29 |
+
self.APISecret = APISecret
|
| 30 |
+
self.host = urlparse(gpt_url).netloc
|
| 31 |
+
self.path = urlparse(gpt_url).path
|
| 32 |
+
self.gpt_url = gpt_url
|
| 33 |
+
|
| 34 |
+
# 生成url
|
| 35 |
+
def create_url(self):
|
| 36 |
+
# 生成RFC1123格式的时间戳
|
| 37 |
+
now = datetime.now()
|
| 38 |
+
date = format_date_time(mktime(now.timetuple()))
|
| 39 |
+
|
| 40 |
+
# 拼接字符串
|
| 41 |
+
signature_origin = "host: " + self.host + "\n"
|
| 42 |
+
signature_origin += "date: " + date + "\n"
|
| 43 |
+
signature_origin += "GET " + self.path + " HTTP/1.1"
|
| 44 |
+
|
| 45 |
+
# 进行hmac-sha256进行加密
|
| 46 |
+
signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
|
| 47 |
+
digestmod=hashlib.sha256).digest()
|
| 48 |
+
|
| 49 |
+
signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')
|
| 50 |
+
|
| 51 |
+
authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'
|
| 52 |
+
|
| 53 |
+
authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
|
| 54 |
+
|
| 55 |
+
# 将请求的鉴权参数组合为字典
|
| 56 |
+
v = {
|
| 57 |
+
"authorization": authorization,
|
| 58 |
+
"date": date,
|
| 59 |
+
"host": self.host
|
| 60 |
+
}
|
| 61 |
+
# 拼接鉴权参数,生成url
|
| 62 |
+
url = self.gpt_url + '?' + urlencode(v)
|
| 63 |
+
# 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
|
| 64 |
+
return url
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# 收到websocket错误的处理
|
| 68 |
+
def on_error(ws, error):
|
| 69 |
+
print("### error:", error)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# 收到websocket关闭的处理
|
| 73 |
+
def on_close(ws, status_code, reason):
|
| 74 |
+
print("")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# 收到websocket连接建立的处理
|
| 80 |
+
def on_open(ws):
|
| 81 |
+
thread.start_new_thread(run, (ws,))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def run(ws, *args):
|
| 85 |
+
data = json.dumps(gen_params(appid=ws.appid, question=ws.question))
|
| 86 |
+
ws.send(data)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# 收到websocket消息的处理
|
| 90 |
+
def on_message(ws, message):
|
| 91 |
+
data = json.loads(message)
|
| 92 |
+
code = data['header']['code']
|
| 93 |
+
if code != 0:
|
| 94 |
+
print(f'请求错误: {code}, {data}')
|
| 95 |
+
ws.close()
|
| 96 |
+
else:
|
| 97 |
+
choices = data["payload"]["choices"]
|
| 98 |
+
status = choices["status"]
|
| 99 |
+
content = choices["text"][0]["content"]
|
| 100 |
+
messages.append({"role": "assistant", "content": content})
|
| 101 |
+
#print(content, end='')
|
| 102 |
+
if status == 2:
|
| 103 |
+
ws.close()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def gen_params(appid, question):
|
| 109 |
+
"""
|
| 110 |
+
通过appid和用户的提问来生成请参数
|
| 111 |
+
"""
|
| 112 |
+
data = {
|
| 113 |
+
"header": {
|
| 114 |
+
"app_id": appid,
|
| 115 |
+
"uid": "1234"
|
| 116 |
+
},
|
| 117 |
+
"parameter": {
|
| 118 |
+
"chat": {
|
| 119 |
+
"domain": "general",
|
| 120 |
+
"random_threshold": 0.5,
|
| 121 |
+
"max_tokens": 2048,
|
| 122 |
+
"auditing": "default"
|
| 123 |
+
}
|
| 124 |
+
},
|
| 125 |
+
"payload": {
|
| 126 |
+
"message": {
|
| 127 |
+
"text": [
|
| 128 |
+
{"role": "user", "content": question}
|
| 129 |
+
]
|
| 130 |
+
}
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
return data
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def main(appid, api_key, api_secret, gpt_url, question):
|
| 137 |
+
wsParam = Ws_Param(appid, api_key, api_secret, gpt_url)
|
| 138 |
+
websocket.enableTrace(False)
|
| 139 |
+
wsUrl = wsParam.create_url()
|
| 140 |
+
ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)
|
| 141 |
+
ws.appid = appid
|
| 142 |
+
ws.question = question
|
| 143 |
+
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def ChatGPT_Bot(input):
|
| 147 |
+
global messages
|
| 148 |
+
if input:
|
| 149 |
+
main(appid="28831c57",
|
| 150 |
+
api_secret="YzAwZTY0ZjRjMGExYTJjYzU3OWUyZTA1",
|
| 151 |
+
api_key="98dd35bacd2f3b92d00b9ee9d86d8450",
|
| 152 |
+
gpt_url="ws://spark-api.xf-yun.com/v1.1/chat",question="提取这段内容的摘要"+input)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
result =""
|
| 156 |
+
for m in messages[1:]:
|
| 157 |
+
if m["role"] == 'assistant':
|
| 158 |
+
result += m["content"]
|
| 159 |
+
if len(messages)>1:
|
| 160 |
+
messages= [{"role": "system","question":"question", "content": "You are a helpful and kind AI Assistant."},]
|
| 161 |
+
|
| 162 |
+
return result
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
if __name__ == "__main__":
|
| 166 |
+
inputs = Textbox(lines=7, label="请输入你的问题,可以提取摘要了")
|
| 167 |
+
outputs = Textbox(lines=7, label="来自ChatGPT的回答")
|
| 168 |
+
gr.Interface(fn=ChatGPT_Bot, inputs=inputs, outputs=outputs, title="万家知识小助手",description="我是您的AI助理,您可以问任何你想知道的问题",theme=gr.themes.Default()).launch()
|