154 lines
6.2 KiB
Python
154 lines
6.2 KiB
Python
#!/usr/bin/env python
|
|
# 后端
|
|
# WS server example that synchronizes state across clients
|
|
import pymysql
|
|
import asyncio
|
|
import json
|
|
import websockets
|
|
import re
|
|
import datetime
|
|
# from zhipuai import ZhipuAI
|
|
from openai import OpenAI
|
|
# sk-DTZqvmzL5FHpfQXRpmL9PY6VvV3Vrzr8cAWXvrnms6l2BKUP
|
|
# from openai import OpenAI
|
|
#
|
|
# client = OpenAI(
|
|
# api_key = "$MOONSHOT_API_KEY",
|
|
# base_url = "https://api.moonshot.cn/v1",
|
|
# )
|
|
#
|
|
# completion = client.chat.completions.create(
|
|
# model = "moonshot-v1-8k",
|
|
# messages = [
|
|
# {"role": "system", "content": "你是 Kimi,由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的回答。同时,你会拒绝一切涉及恐怖主义,种族歧视,黄色暴力等问题的回答。Moonshot AI 为专有名词,不可翻译成其他语言。"},
|
|
# {"role": "user", "content": "你好,我叫李雷,1+1等于多少?"}
|
|
# ],
|
|
# temperature = 0.3,
|
|
# )
|
|
#
|
|
# print(completion.choices[0].message.content)
|
|
conversation_history = []
|
|
async def gml_chat(messages,conversation_history,USERS):
|
|
if len(conversation_history) >= 4:
|
|
conversation_history.pop(0)
|
|
print("-==========================---")
|
|
print(conversation_history)
|
|
client = OpenAI(
|
|
api_key = "sk-K0XGkZR2jsEY573bgwxxg1G2etPY2mdcqFtWz2FO693nAu2S",
|
|
base_url = "https://api.moonshot.cn/v1",
|
|
)
|
|
conversation_history.append({"role": "user", "content": messages})
|
|
# conversation_history.extend(messages)
|
|
# response = client.chat.completions.create(
|
|
# model="glm-3-turbo",
|
|
# # messages=[
|
|
# # {
|
|
# # "role": "user",
|
|
# # "content": prompt
|
|
# # }
|
|
# # ],
|
|
# messages = conversation_history,
|
|
# top_p=0.7,
|
|
# temperature=0.95,
|
|
# max_tokens=1024,
|
|
# stream=True,
|
|
# )
|
|
completion = client.chat.completions.create(
|
|
model = "moonshot-v1-8k",
|
|
messages = conversation_history,
|
|
temperature = 0.3,
|
|
)
|
|
print(completion.choices[0].message.content)
|
|
content = completion.choices[0].message.content
|
|
# for trunk in completion:
|
|
# # print(trunk.choices[0].delta)
|
|
# content = content + trunk.choices[0].delta.content
|
|
conversation_history.append({"role": "assistant", "content": content})
|
|
robot_message = json.dumps(
|
|
{"type": "user", "content": content, "from": "机器人"})
|
|
await asyncio.wait([user.send(robot_message) for user in USERS.values()])
|
|
return content
|
|
# print(gml_chat("你好"))
|
|
|
|
# 名字:websockets
|
|
USERS = {}
|
|
async def chat(websocket, path):
|
|
# 握手
|
|
await websocket.send(json.dumps({"type": "handshake"}))
|
|
async for message in websocket:
|
|
data = json.loads(message)
|
|
print("---------------------")
|
|
print(data)
|
|
print(data['content'])
|
|
message = ''
|
|
|
|
# 用户发信息
|
|
if data["type"] == 'send':
|
|
name = '404'
|
|
for k, v in USERS.items():
|
|
if v == websocket:
|
|
name = k
|
|
pattern = r"@机器人"
|
|
matches = re.findall(pattern, data['content'])
|
|
# 建立数据库连接
|
|
conn = pymysql.connect(
|
|
host='localhost', # 主机名(或IP地址)
|
|
port=3306, # 端口号,默认为3306
|
|
user='root', # 用户名
|
|
password='guoan123', # 密码
|
|
charset='utf8mb4' # 设置字符编码
|
|
)
|
|
# 创建数据库游标对象
|
|
cursor = conn.cursor()
|
|
# 选择数据表
|
|
conn.select_db("jira3")
|
|
sql = "INSERT INTO chat_tb (chat_content,user_chat_name,chat_time) VALUES ('%s','%s','%s')" %(data['content'], name,datetime.datetime.now())
|
|
cursor.execute(sql)
|
|
conn.commit()
|
|
# 关闭游标和连接
|
|
cursor.close()
|
|
conn.close()
|
|
if len(USERS) != 0:
|
|
if len(matches):
|
|
question_rebot = re.sub(pattern, "", data['content'])
|
|
# robot_reply = await gml_chat(question_rebot) # 获取机器人的回复
|
|
message = json.dumps(
|
|
{"type": "user", "content": data["content"], "from": name})
|
|
await asyncio.wait([user.send(message) for user in USERS.values()])
|
|
robot_reply = await gml_chat(question_rebot,conversation_history) # 获取机器人的回复
|
|
# await asyncio.wait([user.send(message) for user in USERS.values()])
|
|
# robot_message = json.dumps(
|
|
# {"type": "user", "content": robot_reply, "from": "机器人"})
|
|
# # await asyncio.wait([user.send(robot_message) for user in USERS.values()])
|
|
else:
|
|
message = json.dumps(
|
|
{"type": "user", "content": data["content"], "from": name})
|
|
await asyncio.wait([user.send(message) for user in USERS.values()])
|
|
|
|
# if len(USERS) != 0: # asyncio.wait doesn't accept an empty list
|
|
# message = json.dumps(
|
|
# {"type": "user", "content": data["content"], "from": name})
|
|
|
|
#用户登录
|
|
elif data["type"] == 'login':
|
|
USERS[data["content"]] = websocket
|
|
if len(USERS) != 0: # asyncio.wait doesn't accept an empty list
|
|
message = json.dumps(
|
|
{"type": "login", "content": data["content"], "user_list": list(USERS.keys())})
|
|
await asyncio.wait([user.send(message) for user in USERS.values()])
|
|
#用户退出
|
|
elif data["type"] == 'logout':
|
|
del USERS[data["content"]]
|
|
if len(USERS) != 0: # asyncio.wait doesn't accept an empty list
|
|
message = json.dumps(
|
|
{"type": "logout", "content": data["content"], "user_list": list(USERS.keys())})
|
|
await asyncio.wait([user.send(message) for user in USERS.values()])
|
|
|
|
# 群发
|
|
# await asyncio.wait([user.send(message) for user in USERS.values()])
|
|
|
|
|
|
start_server = websockets.serve(chat, "0.0.0.0", 9001)
|
|
|
|
asyncio.get_event_loop().run_until_complete(start_server)
|
|
asyncio.get_event_loop().run_forever() |