消息处理API接口 - 使用OpenAI模型实现智能聊天功能
消息处理API接口 - 使用OpenAI模型实现智能聊天功能
该API接口使用OpenAI的GPT-3.5-turbo模型实现智能聊天功能,用户通过POST请求发送消息内容,接口将调用OpenAI API获取回复并返回给用户。同时,接口还记录用户提问和模型回复信息,并管理API密钥使用次数和用户剩余提问次数。
接口定义
/message (POST)
请求参数
msg: 用户发送的消息内容openid: 用户唯一标识符msgcache: 消息缓存conversationid: 会话ID
返回参数
resmsg: OpenAI模型生成的回复内容num: 用户剩余提问次数code: 状态码- 200: 成功
- 其他: 错误
接口实现
@app.route('/message', methods=['POST'])
def mess2():
# 从数据库中获取可用的API密钥
api1 = ApiPoll.query.filter(
ApiPoll.statu == True, ApiPoll.checkstatu == True).all()
api = random.choice(api1)
# 获取请求中的消息内容、用户openid、消息缓存、会话id等参数
msg = request.json.get('msg')
openid = request.json.get('openid')
msgcache= request.json.get('msgcache')
conversationid = request.json.get('conversationid')
# 将用户openid中的下划线和破折号删除,并只保留后16位作为新的openid
openid1 = openid.replace('_', '').replace('-', '')[-16:]
# 打印当前工作模式为文字,并打印用户发送的消息内容
print ('当前工作模式:文字')
print('[Text USER ' + openid + '] : ' + msg + '\n')
try:
# 构造请求openai官方api的url,并发送post请求,获取回复内容
urltmp=myurl + '/v1/chat/completions'
req = requests.post(urltmp,
json={"messages": [{"role": "user", "content": msg}], "max_tokens": 2048, "model": "gpt-3.5-turbo", "temperature": 0.8}, headers={
'content-type': 'application/json', 'Authorization': 'Bearer ' + api.apikey, "conversationid": conversationid, "userid": openid1}, timeout=120)
# 从数据库中获取用户信息
user1 = User.query.filter(User.openid == openid).first()
print(urltmp)
print('reqstatu', req.status_code)
if req.status_code == 200:
# 解析回复内容,获取openai生成的答案
reqdic = json.loads(req.text)
print(reqdic)
reqdicbk=reqdic
answ = reqdic['choices'][0]['message']['content']
# TODO: 检查回复内容是否包含敏感词,如果包含则返回错误信息
# stau = infocheck(answ, openid)
# if not stau:
# return errout('回复内容包含敏感词!')
# 打印openai生成的答案
print('[Text BOT ' + openid + '] : ' + answ + '\n')
# 将用户的问题和openai生成的答案存储到数据库中
ask1 = AskHis(ask=msg, answ=answ, openid=user1.id)
# 更新使用API密钥的调用次数
ApiPoll.query.filter(ApiPoll.apikey == api.apikey).update(
{'callnum': ApiPoll.callnum + 1})
# 更新用户的剩余提问次数
usernum = user1.num - 1
User.query.filter(User.openid == openid).update({'num': usernum})
db.session.add(ask1)
db.session.commit()
# 将openai生成的答案封装成json格式返回给前端
reqdic['choices'] = []
reqdic['choices'].append({'text': answ})
res = {
"resmsg": reqdic,
"num": usernum,
"code": 200
}
return res
else:
# 处理openai官方api请求错误的情况
reqdic = json.loads(req.text)
errmsg = reqdic['error']['message']
errcode = reqdic['error']['code']
errtype = reqdic['error']['type']
print(reqdic)
if errcode == 'invalid_api_key' or errtype == "insufficient_quota":
# 如果API密钥无效或者配额不足,则将API密钥状态设为不可用,并记录日志
api = ApiPoll.query.filter(ApiPoll.apikey == api.apikey).update({
'statu': False, 'lastlog': errmsg})
db.session.commit()
if errmsg:
# 返回错误信息
print ('服务器快冒烟了,等会再试')
return errout('服务器快冒烟了,等会再试')
else:
# 返回错误信息
print('服务器快Boom了,先缓一缓')
return errout('服务器快Boom了,先缓一缓')
else:
# 返回错误信息
print('官方请求错误,稍后再试')
return errout('官方请求错误,稍后再试')
except Exception as e:
# 处理openai官方api请求错误的情况
print(e)
return errout('openai官方请求错误,请稍后重试')
使用方法
- 准备用户发送的消息内容、openid、消息缓存、会话ID等参数
- 发送POST请求到
/message接口,请求参数包含准备好的参数 - 接口将调用OpenAI API获取回复并返回给用户
示例
{
"msg": "你好,今天天气怎么样?",
"openid": "1234567890abcdef",
"msgcache": null,
"conversationid": "1234567890"
}
返回示例
{
"resmsg": {
"choices": [
{
"text": "今天天气不错,阳光明媚,温度适宜。"
}
]
},
"num": 9,
"code": 200
}
原文地址: https://www.cveoy.top/t/topic/lYZe 著作权归作者所有。请勿转载和采集!