zhangqian
2024-10-25 7ee38c3bbcdd563ab941cf6a7dfa7165abb35460
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import uuid
 
from fastapi import Depends, APIRouter, Query, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
 
from app.api import Response, get_current_user, ResponseList
from app.config.config import settings
from app.models.agent_model import AgentType, AgentModel
from app.models.base_model import get_db
from app.models.user_model import UserModel
from app.service.bisheng import BishengService
from app.service.ragflow import RagflowService
from app.service.token import get_ragflow_token, get_bisheng_token
 
router = APIRouter()
 
 
@router.get("/list", response_model=ResponseList)
async def agent_list(db: Session = Depends(get_db)):
    agents = db.query(AgentModel).order_by(AgentModel.sort.asc()).all()
    result = [item.to_dict() for item in agents]
    return ResponseList(code=200, msg="", data=result)
 
 
@router.get("/{agent_id}/sessions", response_model=ResponseList)
async def chat_list(agent_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 ResponseList(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_chat_sessions(token, agent_id)
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))
        return ResponseList(code=200, msg="", data=result)
 
    elif 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_chat_sessions(token)
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))
        return ResponseList(code=200, msg="", data=result)
 
    else:
        return ResponseList(code=200, msg="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})