From 5a11a870e2abb5201f62c253ca811e52035864ed Mon Sep 17 00:00:00 2001
From: zhaoqingang <zhaoqg0118@163.com>
Date: 星期五, 10 一月 2025 18:25:13 +0800
Subject: [PATCH] 知识库选择返回自己创建的
---
app/api/agent.py | 96 +++++++++++++++++++++++++++++++++---------------
1 files changed, 66 insertions(+), 30 deletions(-)
diff --git a/app/api/agent.py b/app/api/agent.py
index a9efc92..88cd114 100644
--- a/app/api/agent.py
+++ b/app/api/agent.py
@@ -6,9 +6,10 @@
from pydantic import BaseModel
from sqlalchemy.orm import Session
-from app.api import Response, get_current_user, ResponseList
+from app.api import Response, get_current_user, ResponseList, process_files
from app.api.user import reset_user_pwd
from app.config.config import settings
+from app.models import DialogModel, MenuCapacityModel
from app.models.agent_model import AgentType, AgentModel
from app.models.base_model import get_db
from app.models.session_model import SessionModel
@@ -17,6 +18,7 @@
from app.service.dialog import get_session_history
from app.service.ragflow import RagflowService
from app.service.service_token import get_ragflow_token, get_bisheng_token
+from app.task.fetch_agent import initialize_agents
router = APIRouter()
@@ -35,37 +37,39 @@
limit: int = Query(1000, ge=1, le=1000),
db: Session = Depends(get_db),
current_user: UserModel = Depends(get_current_user)):
- agent = db.query(AgentModel).filter(AgentModel.id == agent_id).first()
+ # agent = db.query(AgentModel).filter(AgentModel.id == agent_id).first()
+ agent = db.query(MenuCapacityModel).filter(MenuCapacityModel.chat_id == agent_id).first()
if not agent:
return ResponseList(code=404, msg="Agent not found")
-
- if agent.agent_type == AgentType.RAGFLOW:
+ agent_type = int(agent.capacity_type)
+ if agent_type == AgentType.RAGFLOW:
ragflow_service = RagflowService(base_url=settings.fwr_base_url)
try:
- token = get_ragflow_token(db, current_user.id)
+ token = await get_ragflow_token(db, current_user.id)
result = await ragflow_service.get_chat_sessions(token, agent_id)
if not result:
- result = await get_session_history(db, current_user.id, agent_id)
+ result = await get_session_history(db, current_user.id, agent_id, page, limit)
except Exception as e:
+ print(e)
raise HTTPException(status_code=500, detail=str(e))
return ResponseList(code=200, msg="", data=result)
- elif agent.agent_type == AgentType.BISHENG:
+ elif agent_type == AgentType.BISHENG:
bisheng_service = BishengService(base_url=settings.sgb_base_url)
try:
- token = get_bisheng_token(db, current_user.id)
+ token = await get_bisheng_token(db, current_user.id)
result = await bisheng_service.get_chat_sessions(token, agent_id, page, limit)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return ResponseList(code=200, msg="", data=result)
- elif agent.agent_type == AgentType.BASIC:
+ elif agent_type == AgentType.BASIC:
offset = (page - 1) * limit
records = db.query(SessionModel).filter(SessionModel.agent_id == agent_id, SessionModel.tenant_id==current_user.id).order_by(SessionModel.create_date.desc()).offset(offset).limit(limit).all()
result = [item.to_dict() for item in records]
return ResponseList(code=200, msg="", data=result)
- elif agent.agent_type == AgentType.DIFY:
+ elif agent_type == AgentType.DIFY:
offset = (page - 1) * limit
records = db.query(SessionModel).filter(SessionModel.agent_id == agent_id, SessionModel.tenant_id==current_user.id).order_by(SessionModel.create_date.desc()).offset(offset).limit(limit).all()
result = [item.to_dict() for item in records]
@@ -77,14 +81,18 @@
@router.get("/{agent_id}/{conversation_id}/session_log")
async def session_log(agent_id: str, conversation_id: str, db: Session = Depends(get_db), current_user: UserModel = Depends(get_current_user)):
- agent = db.query(AgentModel).filter(AgentModel.id == agent_id).first()
+ # agent = db.query(AgentModel).filter(AgentModel.id == agent_id).first()
+ # if not agent:
+ # return Response(code=404, msg="Agent not found")
+ agent = db.query(MenuCapacityModel).filter(MenuCapacityModel.chat_id == agent_id).first()
if not agent:
- return Response(code=404, msg="Agent not found")
+ return ResponseList(code=404, msg="Agent not found")
+ agent_type = int(agent.capacity_type)
- if agent.agent_type == AgentType.RAGFLOW:
+ if agent_type == AgentType.RAGFLOW:
ragflow_service = RagflowService(base_url=settings.fwr_base_url)
try:
- token = get_ragflow_token(db, current_user.id)
+ token = await get_ragflow_token(db, current_user.id)
result = await ragflow_service.get_session_log(token, conversation_id)
if 'session_log' in result and 'reference' in result:
combined_logs = []
@@ -112,16 +120,20 @@
return JSONResponse(status_code=200, content={"code": 400, "message": "Invalid result structure"})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
- elif agent.agent_type == AgentType.BISHENG:
+ elif agent_type == AgentType.BISHENG:
+ is_join = False
+ if agent.name == "鎶ュ憡鐢熸垚":
+ is_join = True
bisheng_service = BishengService(base_url=settings.sgb_base_url)
try:
- token = get_bisheng_token(db, current_user.id)
+ token = await get_bisheng_token(db, current_user.id)
result = await bisheng_service.get_session_log(token, agent_id, conversation_id)
combined_logs = []
last_question = None
-
+ answer_str = ""
+ files = []
for session in result:
- print(session)
+ # print(session)
# 妫�鏌� session 鏄惁涓� None
if session is None:
continue
@@ -138,22 +150,41 @@
message = message_json['query']
elif 'report_name' in message_json:
message = message_json['report_name']
- except json.JSONDecodeError:
+
+ except Exception as e:
+ pass # 闈� JSON 瀛楃涓诧紝缁х画浣跨敤鍘熷 message
+ if session.get('files') and isinstance(session.get('files'), str):
+ try:
+ files = json.loads(session.get('files'))
+ process_files(files, agent_id)
+
+ except Exception as e:
pass # 闈� JSON 瀛楃涓诧紝缁х画浣跨敤鍘熷 message
# 妫�鏌� message 鏄惁涓� None
if message is None:
continue
+ if is_join:
+ ...
+ if session.get('role') == 'question':
+ last_question = message
+ elif session.get('role') == 'answer':
+ answer_str += message
- if session.get('role') == 'question':
- last_question = message
- elif session.get('role') == 'answer' and last_question:
- combined_logs.append(last_question + "\n" + message)
- last_question = None
- return JSONResponse(status_code=200, content={"code": 200, "data": {"question":"", "answer": "\n".join(combined_logs)}})
+ else:
+ if session.get('role') == 'question':
+ last_question = message
+ elif session.get('role') == 'answer' and last_question:
+ combined_logs.append({
+ 'question': last_question,
+ 'answer': message
+ })
+ last_question = None
+ return JSONResponse(status_code=200, content={"code": 200, "data": combined_logs if combined_logs else [{'question': last_question,
+ 'answer': answer_str, 'files': files}]})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
- elif agent.agent_type == AgentType.BASIC:
+ elif agent_type == AgentType.BASIC:
data = []
session = db.query(SessionModel).filter(SessionModel.id == conversation_id).first()
if session:
@@ -161,6 +192,8 @@
for i in session.log_to_json().get("message", []):
if i.get("role") == "user":
tmp_data["question"]=i.get("content")
+ if i.get("download_url") is not None:
+ tmp_data["download_url"] = i.get("download_url")
elif i.get("role") == "assistant":
if isinstance(i.get("content"), dict):
@@ -192,7 +225,7 @@
data.append(tmp_data)
return JSONResponse(status_code=200, content={"code": 200, "data": data})
- elif agent.agent_type == AgentType.DIFY:
+ elif agent_type == AgentType.DIFY:
data = []
session = db.query(SessionModel).filter(SessionModel.id == conversation_id).first()
if session:
@@ -208,6 +241,9 @@
"file_url": i.get("content", {}).get("file_url")}]
if "images" in i.get("content", {}):
tmp_data["images"] = i.get("content", {}).get("images")
+
+ if "download_url" in i.get("content", {}):
+ tmp_data["download_url"] = i.get("content", {}).get("download_url")
else:
tmp_data["answer"] = i.get("content")
data.append(tmp_data)
@@ -224,8 +260,8 @@
@router.get("/get-chat-id/{agent_id}", response_model=Response)
async def get_chat_id(agent_id: str, db: Session = Depends(get_db)):
- agent = db.query(AgentModel).filter(AgentModel.id == agent_id).first()
- if not agent:
- return Response(code=404, msg="Agent not found")
+ # agent = db.query(AgentModel).filter(AgentModel.id == agent_id).first()
+ # if not agent:
+ # return Response(code=404, msg="Agent not found")
return Response(code=200, msg="", data={"chat_id": uuid.uuid4().hex})
--
Gitblit v1.8.0