zhangqian
2024-11-15 c0d11dac469251c71b036c757c788615285c9683
app/api/agent.py
@@ -1,4 +1,8 @@
import json
import uuid
from fastapi import Depends, APIRouter, Query, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from sqlalchemy.orm import Session
@@ -12,16 +16,6 @@
from app.service.token import get_ragflow_token, get_bisheng_token
router = APIRouter()
# Pydantic 模型用于响应
class AgentResponse(BaseModel):
    id: str
    name: str
    agent_type: AgentType
    class Config:
        orm_mode = True
@router.get("/list", response_model=ResponseList)
@@ -38,7 +32,7 @@
        return ResponseList(code=404, msg="Agent not found")
    if agent.agent_type == AgentType.RAGFLOW:
        ragflow_service = RagflowService(base_url=settings.ragflow_base_url)
        ragflow_service = RagflowService(base_url=settings.fwr_base_url)
        try:
            token = get_ragflow_token(db, current_user.id)
            result = await ragflow_service.get_chat_sessions(token, agent_id)
@@ -47,7 +41,7 @@
        return ResponseList(code=200, msg="", data=result)
    elif agent.agent_type == AgentType.BISHENG:
        bisheng_service = BishengService(base_url=settings.bisheng_base_url)
        bisheng_service = BishengService(base_url=settings.sgb_base_url)
        try:
            token = get_bisheng_token(db, current_user.id)
            result = await bisheng_service.get_chat_sessions(token)
@@ -57,3 +51,87 @@
    else:
        return ResponseList(code=200, msg="Unsupported agent type")
@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()
    if not agent:
        return Response(code=404, msg="Agent not found")
    if agent.agent_type == AgentType.RAGFLOW:
        ragflow_service = RagflowService(base_url=settings.fwr_base_url)
        try:
            token = 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 = []
                last_question = None
                references = result['reference']
                reference_index = 0
                for session in result['session_log']:
                    if session['role'] == 'user':
                        last_question = session['message']
                    elif session['role'] == 'assistant' and last_question:
                        if reference_index < len(references):
                            reference = references[reference_index]
                        else:
                            reference = None
                        combined_logs.append({
                            'question': last_question,
                            'answer': session['message'],
                            'reference': reference
                        })
                        last_question = None
                        reference_index += 1
                return JSONResponse(status_code=200, content={"code": 200, "data": combined_logs})
            else:
                return JSONResponse(status_code=200, content={"code": 400, "message": "Invalid result structure"})
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))
    if agent.agent_type == AgentType.BISHENG:
        bisheng_service = BishengService(base_url=settings.sgb_base_url)
        try:
            token = get_bisheng_token(db, current_user.id)
            result = await bisheng_service.get_session_log(token, agent_id, conversation_id)
            combined_logs = []
            last_question = None
            for session in result:
                message = session['message']
                # 判断message是字符串还是json 对象,如果是json取其中的question字段,或者report_name字段赋值给message
                try:
                    message_json = json.loads(message)
                    if 'question' in message_json:
                        message = message_json['question']
                    elif 'query' in message_json:
                        message = message_json['query']
                    elif 'report_name' in message_json:
                        message = message_json['report_name']
                except json.JSONDecodeError:
                    pass
                if session['role'] == 'question':
                    last_question = message
                elif session['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})
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))
    else:
        return JSONResponse(status_code=200, content={"code": 200, "log": "Unsupported agent type"})
@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")
    return Response(code=200, msg="", data={"chat_id": uuid.uuid4().hex})