#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/10/18 10:04 @File : AiBot.py @Desc : """ import sys sys.path.append("..") from config import ( get_logger, INTENT_ERROR, END, HANGUP, TRANSFER ) from fastapi import FastAPI import uvicorn from interface import reqRobot, ChatResponse from database import * from scene import Dialog,Msg from entity import Error import traceback from util import insert_log, timetic from prometheus_fastapi_instrumentator import Instrumentator, metrics #from prometheus_client import Summary logger=get_logger("log") app = FastAPI() # 服务监控,qps,latent, cpu利用率 Instrumentator().instrument(app).expose(app) @app.post("/botservice") @timetic def botservice(reqbot:reqRobot): bid, uid, code, asr = reqbot.taskId, reqbot.userId, reqbot.nodeId, reqbot.asrText session_id, record_id = reqbot.sessionId, reqbot.recordId logger.info("智能客服:botId: {},session:{}, uid: {}, nodeId: {}, ASR: {}".format(bid, session_id, uid, code, asr)) scene = get_status_cache(uid, bid, "status", session_id) #scene.case.code="1.00" if scene is None: scene = Dialog() try: cur_code = scene.get_current_code(bid) logger.info(f"智能客服:uid:{uid},sessionId:{session_id},code:{code}, cur_code:{cur_code}") if code == cur_code: option = scene.mapping_semantics(code, asr, bid, uid, session_id) logger.info(f"智能客服:uid:{uid},sessionId:{session_id},code:{code},opt:{option}") if not option: return ChatResponse(code=Error.error_intent.value, message=INTENT_ERROR).to_json_string() msg = scene.dialogue(Msg(code=code, option=option, asr=asr, session=session_id, record=record_id, ),bid, uid,session_id) if msg.code == END: with_status_cache(uid, bid, 'result', session_id, scene) del_cache(uid, bid, 'status', session_id) insert_log(bid, uid, session_id, scene) return ChatResponse(code=200, message="success").to_json_string() else: with_status_cache(uid, bid, 'status', session_id, scene) insert_log(bid, uid, session_id, scene) if msg.action in [HANGUP, TRANSFER]: del_cache(uid, bid, 'status', session_id) with_status_cache(uid, bid, 'result', session_id, scene) return ChatResponse().from_msg(msg).to_json_string() else: msg = scene.get_current_content(bid, uid) if code == "start" or code is None: scene.case.code = cur_code with_status_cache(uid, bid, 'status', session_id, scene) insert_log(bid, uid, session_id, scene) return ChatResponse().from_msg(msg).to_json_string() except Exception as e: logger.error(e) #del_cache(uid, bid, 'status', session_id) return ChatResponse(code=Error.error.value, message="internal error").to_json_string() if __name__ == '__main__': uvicorn.run("AiBot:app", host='0.0.0.0', port=40072,workers=4)