chore: api layer refactoring
Browse files- app/api/chat_api.py +3 -56
- app/service/chat_service.py +6 -7
- main.py +3 -1
app/api/chat_api.py
CHANGED
|
@@ -2,9 +2,7 @@
|
|
| 2 |
|
| 3 |
from typing import Any, List, Optional
|
| 4 |
from fastapi import APIRouter, HTTPException, Depends, Request
|
| 5 |
-
from pydantic import BaseModel
|
| 6 |
from app.schema.chat_schema import ChatCompletionRequest, ChatCompletionResponse, ChatMessageResponse
|
| 7 |
-
from app.schema.conversation_schema import ConversationResponse, ConversationItemResponse
|
| 8 |
from app.service.chat_service import ChatService
|
| 9 |
from app.security.auth_service import AuthService
|
| 10 |
from loguru import logger
|
|
@@ -14,16 +12,6 @@ service = ChatService()
|
|
| 14 |
auth_service = AuthService()
|
| 15 |
|
| 16 |
|
| 17 |
-
class VersionResponse(BaseModel):
|
| 18 |
-
version: str = "0.0.1"
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
# version api from pyproject.toml
|
| 22 |
-
@router.get("/version", response_model=VersionResponse)
|
| 23 |
-
async def get_version():
|
| 24 |
-
return VersionResponse()
|
| 25 |
-
|
| 26 |
-
|
| 27 |
################
|
| 28 |
# chat completion api list
|
| 29 |
################
|
|
@@ -99,7 +87,9 @@ async def list_messages(completion_id: str, request: Request, username: str = De
|
|
| 99 |
################
|
| 100 |
# get a plot for a message
|
| 101 |
@router.get(
|
| 102 |
-
"/chat/completions/{completion_id}/messages/{message_id}/plot",
|
|
|
|
|
|
|
| 103 |
)
|
| 104 |
async def retrieve_plot(completion_id: str, message_id: str, request: Request, username: str = Depends(auth_service.verify_credentials)):
|
| 105 |
"""
|
|
@@ -110,46 +100,3 @@ async def retrieve_plot(completion_id: str, message_id: str, request: Request, u
|
|
| 110 |
return await service.find_plot_by_message(completion_id, message_id)
|
| 111 |
except Exception as e:
|
| 112 |
raise HTTPException(status_code=500, detail=str(e))
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
################
|
| 116 |
-
# conversation api list
|
| 117 |
-
################
|
| 118 |
-
# GET https://chatgpt.com/backend-api/conversations
|
| 119 |
-
# GET https://chatgpt.com/backend-api/conversations/{completion_id}
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
# get all conversations
|
| 123 |
-
@router.get("/conversations", response_model=ConversationResponse, response_model_exclude_none=True)
|
| 124 |
-
async def list_conversations(
|
| 125 |
-
request: Request,
|
| 126 |
-
username: str = Depends(auth_service.verify_credentials),
|
| 127 |
-
):
|
| 128 |
-
"""
|
| 129 |
-
Get all conversations
|
| 130 |
-
"""
|
| 131 |
-
logger.debug(f"Listing conversations for username: {username}")
|
| 132 |
-
try:
|
| 133 |
-
return await service.find_all_conversations(username)
|
| 134 |
-
except Exception as e:
|
| 135 |
-
logger.error(f"Error in list_conversations: {str(e)}")
|
| 136 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
# get a conversation by id
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
@router.get("/conversations/{completion_id}", response_model=ConversationItemResponse, response_model_exclude_none=True)
|
| 143 |
-
async def retrieve_conversation(
|
| 144 |
-
completion_id: str,
|
| 145 |
-
request: Request,
|
| 146 |
-
username: str = Depends(auth_service.verify_credentials),
|
| 147 |
-
):
|
| 148 |
-
"""
|
| 149 |
-
Get a conversation by id
|
| 150 |
-
"""
|
| 151 |
-
logger.debug(f"Retrieving conversation with completion_id: {completion_id}")
|
| 152 |
-
try:
|
| 153 |
-
return await service.find_conversation_by_id(completion_id)
|
| 154 |
-
except Exception as e:
|
| 155 |
-
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
| 2 |
|
| 3 |
from typing import Any, List, Optional
|
| 4 |
from fastapi import APIRouter, HTTPException, Depends, Request
|
|
|
|
| 5 |
from app.schema.chat_schema import ChatCompletionRequest, ChatCompletionResponse, ChatMessageResponse
|
|
|
|
| 6 |
from app.service.chat_service import ChatService
|
| 7 |
from app.security.auth_service import AuthService
|
| 8 |
from loguru import logger
|
|
|
|
| 12 |
auth_service = AuthService()
|
| 13 |
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
################
|
| 16 |
# chat completion api list
|
| 17 |
################
|
|
|
|
| 87 |
################
|
| 88 |
# get a plot for a message
|
| 89 |
@router.get(
|
| 90 |
+
"/chat/completions/{completion_id}/messages/{message_id}/plot",
|
| 91 |
+
response_model=Optional[dict[str, Any]],
|
| 92 |
+
response_model_exclude_none=True,
|
| 93 |
)
|
| 94 |
async def retrieve_plot(completion_id: str, message_id: str, request: Request, username: str = Depends(auth_service.verify_credentials)):
|
| 95 |
"""
|
|
|
|
| 100 |
return await service.find_plot_by_message(completion_id, message_id)
|
| 101 |
except Exception as e:
|
| 102 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/service/chat_service.py
CHANGED
|
@@ -8,7 +8,7 @@ from app.mapper.chat_mapper import ChatMapper
|
|
| 8 |
from app.mapper.conversation_mapper import ConversationMapper
|
| 9 |
import uuid
|
| 10 |
from loguru import logger
|
| 11 |
-
from app.schema.conversation_schema import ConversationResponse
|
| 12 |
from app.service.chat_validation import ChatValidation
|
| 13 |
from app.agent.chat_agent_client import ChatAgentClient
|
| 14 |
|
|
@@ -57,19 +57,18 @@ class ChatService:
|
|
| 57 |
return ConversationResponse(items=result, total=len(result), limit=100, offset=0)
|
| 58 |
|
| 59 |
# conversation service
|
| 60 |
-
async def find_conversation_by_id(self, completion_id: str) ->
|
| 61 |
"""Find a conversation by its completion ID."""
|
| 62 |
logger.debug(f"BEGIN SERVICE: find_conversation_by_id for completion_id: {completion_id}")
|
| 63 |
projection = {"messages": 0, "_id": 0}
|
| 64 |
entity = await self.chat_repository.find_by_id(completion_id, projection=projection)
|
| 65 |
-
logger.debug(f"END SERVICE: find_conversation_by_id for completion_id: {completion_id}, entity: {entity}")
|
| 66 |
|
| 67 |
if entity:
|
| 68 |
conversation_item = self.conversation_mapper.to_schema(entity)
|
| 69 |
-
|
| 70 |
-
return
|
| 71 |
-
|
| 72 |
-
|
| 73 |
|
| 74 |
async def find_plot_by_message(self, completion_id: str, message_id: str) -> dict[str, Any]:
|
| 75 |
logger.debug(f"BEGIN SERVICE: find_plot_by_message for completion_id: {completion_id}, message_id: {message_id}")
|
|
|
|
| 8 |
from app.mapper.conversation_mapper import ConversationMapper
|
| 9 |
import uuid
|
| 10 |
from loguru import logger
|
| 11 |
+
from app.schema.conversation_schema import ConversationItemResponse, ConversationResponse
|
| 12 |
from app.service.chat_validation import ChatValidation
|
| 13 |
from app.agent.chat_agent_client import ChatAgentClient
|
| 14 |
|
|
|
|
| 57 |
return ConversationResponse(items=result, total=len(result), limit=100, offset=0)
|
| 58 |
|
| 59 |
# conversation service
|
| 60 |
+
async def find_conversation_by_id(self, completion_id: str) -> ConversationItemResponse | None:
|
| 61 |
"""Find a conversation by its completion ID."""
|
| 62 |
logger.debug(f"BEGIN SERVICE: find_conversation_by_id for completion_id: {completion_id}")
|
| 63 |
projection = {"messages": 0, "_id": 0}
|
| 64 |
entity = await self.chat_repository.find_by_id(completion_id, projection=projection)
|
|
|
|
| 65 |
|
| 66 |
if entity:
|
| 67 |
conversation_item = self.conversation_mapper.to_schema(entity)
|
| 68 |
+
logger.debug(f"END SERVICE: find_conversation_by_id for completion_id: {completion_id}, entity: {conversation_item}")
|
| 69 |
+
return conversation_item
|
| 70 |
+
|
| 71 |
+
return None
|
| 72 |
|
| 73 |
async def find_plot_by_message(self, completion_id: str, message_id: str) -> dict[str, Any]:
|
| 74 |
logger.debug(f"BEGIN SERVICE: find_plot_by_message for completion_id: {completion_id}, message_id: {message_id}")
|
main.py
CHANGED
|
@@ -3,7 +3,7 @@ from fastapi import FastAPI
|
|
| 3 |
from fastapi.responses import RedirectResponse, JSONResponse
|
| 4 |
from fastapi.staticfiles import StaticFiles
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
-
from app.api import chat_api
|
| 7 |
from app.config.log import log_config
|
| 8 |
from loguru import logger
|
| 9 |
from environs import Env
|
|
@@ -116,6 +116,8 @@ app.add_middleware(
|
|
| 116 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 117 |
app.mount("/.well-known", StaticFiles(directory=".well-known"), name="well-known")
|
| 118 |
app.include_router(chat_api.router)
|
|
|
|
|
|
|
| 119 |
|
| 120 |
# Build and mount Gradio app
|
| 121 |
demo = build_gradio_app()
|
|
|
|
| 3 |
from fastapi.responses import RedirectResponse, JSONResponse
|
| 4 |
from fastapi.staticfiles import StaticFiles
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
from app.api import chat_api, conversation_api, management_api
|
| 7 |
from app.config.log import log_config
|
| 8 |
from loguru import logger
|
| 9 |
from environs import Env
|
|
|
|
| 116 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 117 |
app.mount("/.well-known", StaticFiles(directory=".well-known"), name="well-known")
|
| 118 |
app.include_router(chat_api.router)
|
| 119 |
+
app.include_router(management_api.router)
|
| 120 |
+
app.include_router(conversation_api.router)
|
| 121 |
|
| 122 |
# Build and mount Gradio app
|
| 123 |
demo = build_gradio_app()
|