Skip to content

Commit bb5c046

Browse files
perf: Assistant chat history
1 parent 942f79c commit bb5c046

File tree

8 files changed

+43
-11
lines changed

8 files changed

+43
-11
lines changed

backend/apps/chat/curd/chat.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import orjson
55
from sqlalchemy import and_
66
from sqlalchemy.orm import load_only
7+
from sqlmodel import select
78

89
from apps.chat.models.chat_model import Chat, ChatRecord, CreateChat, ChatInfo, RenameChat, ChatQuestion
910
from apps.datasource.models.datasource import CoreDatasource
@@ -12,8 +13,7 @@
1213

1314

1415
def list_chats(session: SessionDep, current_user: CurrentUser) -> List[Chat]:
15-
chart_list = session.query(Chat).filter(Chat.create_by == current_user.id).order_by(
16-
Chat.create_time.desc()).all()
16+
chart_list = session.exec(select(Chat).where(Chat.create_by == current_user.id).order_by(Chat.create_time.desc())).all()
1717
return chart_list
1818

1919

backend/apps/system/api/assistant.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,14 @@
1414
router = APIRouter(tags=["system/assistant"], prefix="/system/assistant")
1515

1616
@router.get("/validator/{id}", response_model=AssistantValidator)
17-
async def info(session: SessionDep, id: int):
18-
db_model = get_assistant_info(session, id)
17+
async def info(session: SessionDep, id: str):
18+
as_id, flag = id.split('-')
19+
db_model = get_assistant_info(session, as_id)
1920
if not db_model:
2021
return AssistantValidator()
2122
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
2223
assistantDict = {
23-
"id": 1, "account": 'admin', "oid": 1, "assistant_id": id
24+
"id": flag, "account": 'sqlbot-inner-assistant', "oid": 1, "assistant_id": id
2425
}
2526
access_token = create_access_token(
2627
assistantDict, expires_delta=access_token_expires

backend/apps/system/crud/assistant.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,14 @@
33
from sqlmodel import Session
44
from apps.system.models.system_model import AssistantModel
55
from apps.system.schemas.auth import CacheName, CacheNamespace
6+
from apps.system.schemas.system_schema import UserInfoDTO
67
from common.core.sqlbot_cache import cache
78

89

910
@cache(namespace=CacheNamespace.EMBEDDED_INFO, cacheName=CacheName.ASSISTANT_INFO, keyExpression="assistant_id")
1011
async def get_assistant_info(*, session: Session, assistant_id: int) -> AssistantModel | None:
1112
db_model = session.get(AssistantModel, assistant_id)
12-
return db_model
13+
return db_model
14+
15+
def get_assistant_user(*, id: int):
16+
return UserInfoDTO(id=id, account="sqlbot-inner-assistant", oid=1, name="sqlbot-inner-assistant", email="[email protected]")

backend/apps/system/middleware/auth.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from sqlmodel import Session
77
from starlette.middleware.base import BaseHTTPMiddleware
88
from common.core.db import engine
9-
from apps.system.crud.assistant import get_assistant_info
9+
from apps.system.crud.assistant import get_assistant_info, get_assistant_user
1010
from apps.system.crud.user import get_user_info
1111
from apps.system.schemas.system_schema import UserInfoDTO
1212
from common.core import security
@@ -80,8 +80,9 @@ async def validateAssistant(self, assistantToken: Optional[str]):
8080
return False, f"Miss assistant payload error!"
8181
try:
8282
with Session(engine) as session:
83-
session_user = await get_user_info(session = session, user_id = token_data.id)
84-
session_user = UserInfoDTO.model_validate(session_user)
83+
""" session_user = await get_user_info(session = session, user_id = token_data.id)
84+
session_user = UserInfoDTO.model_validate(session_user) """
85+
session_user = get_assistant_user(id = token_data.id)
8586
assistant_info = get_assistant_info(session, payload['assistant_id'])
8687
return True, session_user, assistant_info
8788
except Exception as e:

backend/common/core/deps.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from fastapi import Depends, Request
44
from sqlmodel import Session
5+
from apps.system.models.system_model import AssistantModel
56
from apps.system.schemas.system_schema import UserInfoDTO
67
from common.core.db import get_session
78
from common.utils.locale import I18n
@@ -18,5 +19,10 @@ async def get_current_user(request: Request) -> UserInfoDTO:
1819

1920
CurrentUser = Annotated[UserInfoDTO, Depends(get_current_user)]
2021

22+
async def get_current_assistant(request: Request) -> AssistantModel:
23+
return request.state.assistant
24+
25+
CurrentAssistant = Annotated[AssistantModel, Depends(get_current_assistant)]
26+
2127

2228

frontend/src/stores/assistant.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,22 @@
11
import { defineStore } from 'pinia'
22
import { store } from './index'
33
import { chatApi, ChatInfo } from '@/api/chat'
4+
import { useCache } from '@/utils/useCache'
45

6+
const { wsCache } = useCache()
7+
const flagKey = 'sqlbit-assistant-flag'
58
interface AssistantState {
69
token: string
710
assistant: boolean
11+
flag: number
812
}
913

1014
export const AssistantStore = defineStore('assistant', {
1115
state: (): AssistantState => {
1216
return {
1317
token: '',
1418
assistant: false,
19+
flag: 0,
1520
}
1621
},
1722
getters: {
@@ -21,6 +26,9 @@ export const AssistantStore = defineStore('assistant', {
2126
getAssistant(): boolean {
2227
return this.assistant
2328
},
29+
getFlag(): number {
30+
return this.flag
31+
},
2432
},
2533
actions: {
2634
setToken(token: string) {
@@ -29,6 +37,14 @@ export const AssistantStore = defineStore('assistant', {
2937
setAssistant(assistant: boolean) {
3038
this.assistant = assistant
3139
},
40+
setFlag(flag: number) {
41+
if (wsCache.get(flagKey)) {
42+
this.flag = wsCache.get(flagKey)
43+
} else {
44+
this.flag = flag
45+
wsCache.set(flagKey, flag)
46+
}
47+
},
3248
async setChat() {
3349
if (!this.assistant) {
3450
return null
@@ -38,6 +54,7 @@ export const AssistantStore = defineStore('assistant', {
3854
return chat
3955
},
4056
clear() {
57+
wsCache.delete(flagKey)
4158
this.$reset()
4259
},
4360
},

frontend/src/utils/request.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ class HttpService {
238238
}
239239
if (assistantStore.getToken) {
240240
heads['X-SQLBOT-ASSISTANT-TOKEN'] = `Assistant ${assistantStore.getToken}`
241-
if (heads['X-SQLBOT-TOKEN']) heads.delete('X-SQLBOT-TOKEN')
241+
if (heads['X-SQLBOT-TOKEN']) delete heads['X-SQLBOT-TOKEN']
242242
}
243243
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
244244
// @ts-ignore

frontend/src/views/embedded/assistant.vue

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,10 @@ const validator = ref({
9696
const loading = ref(true)
9797
onBeforeMount(async () => {
9898
const assistantId = route.params.id
99-
validator.value = await assistantApi.validate(assistantId)
99+
const now = Date.now()
100+
assistantStore.setFlag(now)
101+
const id = `${assistantId}-${assistantStore.getFlag}`
102+
validator.value = await assistantApi.validate(id)
100103
assistantStore.setToken(validator.value.token)
101104
assistantStore.setAssistant(true)
102105
loading.value = false

0 commit comments

Comments
 (0)