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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 |
+
import websocket
|
| 14 |
+
|
| 15 |
+
# 以下密钥信息从控制台获取
|
| 16 |
+
appid = "91a34125" # 填写控制台中获取的 APPID 信息
|
| 17 |
+
api_secret = "NzllYTYxZDk4NGZkOWNkOTBlODRkN2M0" # 填写控制台中获取的 APISecret 信息
|
| 18 |
+
api_key = "6f008fde7d363d0d3a2c2e60d2fe23aa" # 填写控制台中获取的 APIKey 信息
|
| 19 |
+
|
| 20 |
+
# 用于配置大模型版本,默认“general/generalv2”
|
| 21 |
+
domain = "general" # v1.5版本
|
| 22 |
+
# domain = "generalv2" # v2.0版本
|
| 23 |
+
|
| 24 |
+
# 云端环境的服务地址
|
| 25 |
+
Spark_url = "ws://spark-api.xf-yun.com/v1.1/chat" # v1.5环境的地址
|
| 26 |
+
# Spark_url = "ws://spark-api.xf-yun.com/v2.1/chat" # v2.0环境的地址
|
| 27 |
+
temperature=0.5
|
| 28 |
+
text = []
|
| 29 |
+
|
| 30 |
+
class Ws_Param(object):
|
| 31 |
+
#初始化
|
| 32 |
+
def __init__(self, APPID, APIKey, APISecret, Spark_url):
|
| 33 |
+
self.APPID = APPID
|
| 34 |
+
self.APIKey = APIKey
|
| 35 |
+
self.APISecret = APISecret
|
| 36 |
+
self.host = urlparse(Spark_url).netloc
|
| 37 |
+
self.path = urlparse(Spark_url).path
|
| 38 |
+
self.Spark_url = Spark_url
|
| 39 |
+
|
| 40 |
+
class ChatModel:
|
| 41 |
+
|
| 42 |
+
answer = ""
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def __init__(self, appid, api_key, api_secret, Spark_url, domain, temperature):
|
| 46 |
+
self.appid = appid
|
| 47 |
+
self.api_key = api_key
|
| 48 |
+
self.api_secret = api_secret
|
| 49 |
+
self.Spark_url = Spark_url
|
| 50 |
+
self.domain = domain
|
| 51 |
+
self.temperature = temperature
|
| 52 |
+
self.answer = ""
|
| 53 |
+
# 生成url
|
| 54 |
+
def create_url(self):
|
| 55 |
+
# 生成RFC1123格式的时间戳
|
| 56 |
+
now = datetime.now()
|
| 57 |
+
date = format_date_time(mktime(now.timetuple()))
|
| 58 |
+
|
| 59 |
+
# 拼接字符串
|
| 60 |
+
signature_origin = "host: " + self.host + "\n"
|
| 61 |
+
signature_origin += "date: " + date + "\n"
|
| 62 |
+
signature_origin += "GET " + self.path + " HTTP/1.1"
|
| 63 |
+
|
| 64 |
+
# 进行hmac-sha256进行加密
|
| 65 |
+
signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
|
| 66 |
+
digestmod=hashlib.sha256).digest()
|
| 67 |
+
|
| 68 |
+
signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')
|
| 69 |
+
|
| 70 |
+
authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'
|
| 71 |
+
|
| 72 |
+
authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
|
| 73 |
+
|
| 74 |
+
# 将请求的鉴权参数组合为字典
|
| 75 |
+
v = {
|
| 76 |
+
"authorization": authorization,
|
| 77 |
+
"date": date,
|
| 78 |
+
"host": self.host
|
| 79 |
+
}
|
| 80 |
+
# 拼接鉴权参数,生成url
|
| 81 |
+
url = self.Spark_url + '?' + urlencode(v)
|
| 82 |
+
return url
|
| 83 |
+
|
| 84 |
+
# 收到websocket错误的处理
|
| 85 |
+
def on_error(ws, error):
|
| 86 |
+
print("### error:", error)
|
| 87 |
+
|
| 88 |
+
# 收到websocket关闭的处理
|
| 89 |
+
def on_close(ws, one, two):
|
| 90 |
+
print(" ")
|
| 91 |
+
|
| 92 |
+
# 收到websocket连接建立的处理
|
| 93 |
+
def on_open(ws):
|
| 94 |
+
thread.start_new_thread(run, (ws,))
|
| 95 |
+
|
| 96 |
+
def run(ws, *args):
|
| 97 |
+
data = json.dumps(gen_params(appid=ws.appid, domain=ws.domain, conversation=ws.conversation))
|
| 98 |
+
ws.send(data)
|
| 99 |
+
|
| 100 |
+
# 收到websocket消息的处理
|
| 101 |
+
def on_message(ws, message):
|
| 102 |
+
data = json.loads(message)
|
| 103 |
+
code = data['header']['code']
|
| 104 |
+
if code != 0:
|
| 105 |
+
print(f'请求错误: {code}, {data}')
|
| 106 |
+
ws.close()
|
| 107 |
+
else:
|
| 108 |
+
choices = data["payload"]["choices"]
|
| 109 |
+
status = choices["status"]
|
| 110 |
+
content = choices["text"][0]["content"]
|
| 111 |
+
print(content, end="")
|
| 112 |
+
global answer
|
| 113 |
+
answer += content
|
| 114 |
+
if status == 2:
|
| 115 |
+
ws.close()
|
| 116 |
+
|
| 117 |
+
def gen_params(appid, domain, conversation, temperature):
|
| 118 |
+
# 通过appid、用户的提问、和历史对话来生成参数,包括温度
|
| 119 |
+
data = {
|
| 120 |
+
"header": {
|
| 121 |
+
"app_id": appid,
|
| 122 |
+
"uid": "1234"
|
| 123 |
+
},
|
| 124 |
+
"parameter": {
|
| 125 |
+
"chat": {
|
| 126 |
+
"domain": domain,
|
| 127 |
+
"temperature": temperature,
|
| 128 |
+
"max_tokens": 2048,
|
| 129 |
+
"auditing": "default"
|
| 130 |
+
}
|
| 131 |
+
},
|
| 132 |
+
"payload": {
|
| 133 |
+
"message": {
|
| 134 |
+
"text": conversation
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
return data
|
| 139 |
+
|
| 140 |
+
def main(appid, api_key, api_secret, Spark_url, domain, conversation, temperature):
|
| 141 |
+
wsParam = Ws_Param(appid, api_key, api_secret, Spark_url)
|
| 142 |
+
websocket.enableTrace(False)
|
| 143 |
+
wsUrl = wsParam.create_url()
|
| 144 |
+
ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)
|
| 145 |
+
ws.appid = appid
|
| 146 |
+
ws.conversation = conversation
|
| 147 |
+
ws.domain = domain
|
| 148 |
+
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def create_conversation():
|
| 153 |
+
# 创建历史对话,它包含了三条固定的消息,当用户输入消息并与助手交互时,消息会被添加到历史对话中
|
| 154 |
+
conversation = [
|
| 155 |
+
{"role": "user", "content": "你是谁"},
|
| 156 |
+
{"role": "assistant", "content": "我是聊天助手"},
|
| 157 |
+
{"role": "user", "content": "你会做什么"}
|
| 158 |
+
]
|
| 159 |
+
return conversation
|
| 160 |
+
|
| 161 |
+
def clear_text():
|
| 162 |
+
text.clear()
|
| 163 |
+
|
| 164 |
+
# if __name__ == '__main__':
|
| 165 |
+
# # def api():
|
| 166 |
+
# clear_text()
|
| 167 |
+
# # text.clear()
|
| 168 |
+
# conversation = create_conversation()
|
| 169 |
+
# while True:
|
| 170 |
+
# user_input = input("\n" + "用户:")
|
| 171 |
+
# if user_input == "退出":
|
| 172 |
+
# print("对话结束。")
|
| 173 |
+
# break
|
| 174 |
+
# conversation.append({"role": "user", "content": user_input})
|
| 175 |
+
# answer = ""
|
| 176 |
+
# print("助手:", end="")
|
| 177 |
+
# main(appid, api_key, api_secret, Spark_url, domain, conversation, temperature=0.5)
|
| 178 |
+
# conversation.append({"role": "assistant", "content": answer})
|