消息处理

@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,并处理openid格式
msg = request.json.get('msg')
openid = request.json.get('openid')
msgcache= request.json.get('msgcache')
conversationid = request.json.get('conversationid')
openid1 = openid.replace("_", "").replace("-", "")[-16:]

# 输出当前工作模式及用户发送的消息
print ('当前工作模式:文字')
print("[Text USER "+openid+"] : "+msg+"\n")
 
try:
    # 向OpenAI的API发送请求,获取回复
    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:
        # 请求成功,获取回复并进行敏感词检测
        reqdic = json.loads(req.text)
        print(reqdic)
        reqdicbk=reqdic

        answ = reqdic['choices'][0]['message']['content']
        # stau = infocheck(answ,openid)
        # if not stau:
        #     return errout('回复内容包含敏感词!')
        print("[Text BOT "+openid+"] : "+answ+"\n")

        # 将用户的消息和机器人的回复存入数据库
        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()

        # 将回复信息封装为返回结果
        reqdic['choices'] = []
        reqdic['choices'].append({'text': answ})

        res = {
            "resmsg": reqdic,
            "num": usernum,
            "code": 200
        }
        return res
    else:
        # 请求失败,根据错误码进行处理
        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:
    # 发生异常,返回错误信息
    print(e)

    return errout('openai官方请求错误,请稍后重试')
# 消息处理approutemessage methods=POSTdef mess2 api1 = ApiPollqueryfilter ApiPollstatu == True ApiPollcheckstatu == Trueall api = randomchoiceapi1 msg = requestjsongetmsg openid = requestjs

原文地址: https://www.cveoy.top/t/topic/H7R 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录