Commit e4fdecce authored by 何家明's avatar 何家明

记录请求ip

parent a8552474
......@@ -97,7 +97,7 @@ async def chat(request: Request, message: str):
yield ServerSentEvent(event="error")
return EventSourceResponse(error_generator())
return EventSourceResponse(mcp_client_instance.process_query(message, id_str.split("-")[0]),
return EventSourceResponse(mcp_client_instance.process_query(message, get_client_ip(request), id_str.split("-")[0]),
media_type="text/event-stream", headers={"Cache-Control": "no-cache"})
@router.post(path="/chat", description="AI对话")
......@@ -108,9 +108,25 @@ async def chat(request: Request, param: AiChatParam):
yield ServerSentEvent(event="error")
return EventSourceResponse(error_generator())
return EventSourceResponse(mcp_client_instance.process_query(param.message, id_str.split("-")[0]),
return EventSourceResponse(mcp_client_instance.process_query(param.message, get_client_ip(request), id_str.split("-")[0]),
media_type="text/event-stream", headers={"Cache-Control": "no-cache"})
def get_client_ip(request: Request) -> str:
"""获取客户端真实 IP(兼容反向代理)"""
# 优先从 X-Forwarded-For 获取(格式:client_ip, proxy1_ip, proxy2_ip...)
x_forwarded_for = request.headers.get("X-Forwarded-For")
if x_forwarded_for:
return x_forwarded_for.split(",")[0].strip() # 取第一个 IP 作为真实客户端 IP
# 其次从 X-Real-IP 获取
x_real_ip = request.headers.get("X-Real-IP")
if x_real_ip:
return x_real_ip
# 最后从 request.client 获取(无代理时)
return request.client.host if request.client else "unknown"
if __name__ == "__main__":
cors = config.get("cors", {})
api.add_middleware(CORSMiddleware, allow_origins=cors.get("allow_origins", ["*"]),
......
......@@ -151,19 +151,20 @@ class McpClient:
客户名:{customer[0]['customerName']}
客户全称:{customer[0]['customerFullname']}"""
async def process_query(self, message: str, customer_id: str):
async def process_query(self, message: str, ip: str, customer_id: str):
"""
处理查询逻辑
:param message: 用户原始问题
:param customer_id: 客户id
:param ip: ip地址
:return: 经过mcp加工后的ai回答
"""
# 插入AI对话记录
chat_record_entity = AiChatRecordEntity(customer_id=int(customer_id), question=message,
chat_record_entity = AiChatRecordEntity(customer_id=int(customer_id), question=message, ip=ip,
ask_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
chat_record_entity = await db_util.add(chat_record_entity)
logger.info(f"--> user origin query, message: {message}, customer_id: {customer_id}")
logger.info(f"--> user origin query, message: {message}, customer_id: {customer_id}, ip: {ip}")
db_question = await db_util.get_by_filter(
AiChatRecommendQuestionEntity,
......
......@@ -9,4 +9,5 @@ class AiChatRecordEntity(BaseEntity):
question = Column(String)
answer = Column(String)
ask_time = Column(String)
answer_time = Column(String)
\ No newline at end of file
answer_time = Column(String)
ip = Column(String)
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment