Skip to content

Commit 36d52df

Browse files
perf: Assistant dynamic certificate
1 parent b8e60ea commit 36d52df

File tree

10 files changed

+40
-30
lines changed

10 files changed

+40
-30
lines changed

backend/apps/chat/api/chat.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ async def start_chat(session: SessionDep, current_user: CurrentUser):
9696
@router.post("/recommend_questions/{chat_record_id}")
9797
async def recommend_questions(session: SessionDep, current_user: CurrentUser, chat_record_id: int, current_assistant: CurrentAssistant):
9898
try:
99-
record = session.query(ChatRecord).get(chat_record_id)
99+
record = session.get(ChatRecord, chat_record_id)
100100
if not record:
101101
raise HTTPException(
102102
status_code=400,

backend/apps/chat/models/chat_model.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,8 +151,6 @@ def filter_user_question(self):
151151
class ChatQuestion(AiModelQuestion):
152152
question: str = ''
153153
chat_id: int = 0
154-
assistant_certificate: Optional[str] = None
155-
156154

157155
class ChatMcp(ChatQuestion):
158156
token: str = ''

backend/apps/chat/task/llm.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@ class LLMService:
5353
session: SessionDep
5454
current_user: CurrentUser
5555
current_assistant: Optional[CurrentAssistant] = None
56-
assistant_certificate: str
5756
out_ds_instance: Optional[AssistantOutDs] = None
5857
change_title: bool = False
5958

@@ -63,8 +62,6 @@ def __init__(self, session: SessionDep, current_user: CurrentUser, chat_question
6362
self.session = session
6463
self.current_user = current_user
6564
self.current_assistant = current_assistant
66-
if chat_question.assistant_certificate:
67-
self.assistant_certificate = chat_question.assistant_certificate
6865
# chat = self.session.query(Chat).filter(Chat.id == chat_question.chat_id).first()
6966
chat_id = chat_question.chat_id
7067
chat: Chat = self.session.get(Chat, chat_id)

backend/apps/system/crud/assistant.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
from apps.system.models.system_model import AssistantModel
1212
from apps.system.schemas.auth import CacheName, CacheNamespace
13-
from apps.system.schemas.system_schema import AssistantOutDsSchema, UserInfoDTO
13+
from apps.system.schemas.system_schema import AssistantHeader, AssistantOutDsSchema, UserInfoDTO
1414
from common.core.sqlbot_cache import cache
1515
from common.core.db import engine
1616
from starlette.middleware.cors import CORSMiddleware
@@ -24,9 +24,8 @@ async def get_assistant_info(*, session: Session, assistant_id: int) -> Assistan
2424
def get_assistant_user(*, id: int):
2525
return UserInfoDTO(id=id, account="sqlbot-inner-assistant", oid=1, name="sqlbot-inner-assistant", email="[email protected]")
2626

27-
# def get_assistant_ds(*, session: Session, assistant: AssistantModel):
2827
def get_assistant_ds(llm_service) -> list[dict]:
29-
assistant: AssistantModel = llm_service.current_assistant
28+
assistant: AssistantHeader = llm_service.current_assistant
3029
session: Session = llm_service.session
3130
type = assistant.type
3231
if type == 0:
@@ -51,7 +50,7 @@ def get_assistant_ds(llm_service) -> list[dict]:
5150

5251
# filter private ds if offline
5352
return result_list
54-
out_ds_instance: AssistantOutDs = AssistantOutDsFactory.get_instance(assistant, llm_service.assistant_certificate)
53+
out_ds_instance: AssistantOutDs = AssistantOutDsFactory.get_instance(assistant)
5554
llm_service.out_ds_instance = out_ds_instance
5655
dslist = out_ds_instance.get_simple_ds_list()
5756
# format?
@@ -84,20 +83,20 @@ def init_dynamic_cors(app: FastAPI):
8483

8584

8685
class AssistantOutDs:
87-
assistant: AssistantModel
86+
assistant: AssistantHeader
8887
ds_list: Optional[list[AssistantOutDsSchema]] = None
8988
certificate: Optional[str] = None
90-
def __init__(self, assistant: AssistantModel, certificate: Optional[str] = None):
89+
def __init__(self, assistant: AssistantHeader):
9190
self.assistant = assistant
9291
self.ds_list = None
93-
self.certificate = certificate
94-
self.get_ds_from_api(certificate)
92+
self.certificate = assistant.certificate
93+
self.get_ds_from_api()
9594

9695
#@cache(namespace=CacheNamespace.EMBEDDED_INFO, cacheName=CacheName.ASSISTANT_DS, keyExpression="current_user.id")
97-
def get_ds_from_api(self, certificate: Optional[str] = None):
96+
def get_ds_from_api(self):
9897
config: dict[any] = json.loads(self.assistant.configuration)
9998
endpoint: str = config['endpoint']
100-
certificateList: list[any] = json.loads(certificate)
99+
certificateList: list[any] = json.loads(self.certificate)
101100
header = {}
102101
cookies = {}
103102
for item in certificateList:
@@ -155,8 +154,8 @@ def get_ds(self, ds_id: int):
155154

156155
class AssistantOutDsFactory:
157156
@staticmethod
158-
def get_instance(assistant: AssistantModel, certificate: Optional[str] = None) -> AssistantOutDs:
159-
return AssistantOutDs(assistant, certificate)
157+
def get_instance(assistant: AssistantHeader) -> AssistantOutDs:
158+
return AssistantOutDs(assistant)
160159

161160
def get_ds_engine(ds: AssistantOutDsSchema) -> Engine:
162161
timeout: int = 30

backend/apps/system/middleware/auth.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from common.core.db import engine
1010
from apps.system.crud.assistant import get_assistant_info, get_assistant_user
1111
from apps.system.crud.user import get_user_info
12-
from apps.system.schemas.system_schema import UserInfoDTO
12+
from apps.system.schemas.system_schema import AssistantHeader, UserInfoDTO
1313
from common.core import security
1414
from common.core.config import settings
1515
from common.core.schemas import TokenPayload
@@ -92,6 +92,7 @@ async def validateAssistant(self, assistantToken: Optional[str]) -> tuple[any]:
9292
session_user = get_assistant_user(id = token_data.id)
9393
assistant_info = await get_assistant_info(session=session, assistant_id=payload['assistant_id'])
9494
assistant_info = AssistantModel.model_validate(assistant_info)
95+
assistant_info = AssistantHeader.model_validate(assistant_info.model_dump(exclude_unset=True))
9596
return True, session_user, assistant_info
9697
except Exception as e:
9798
return False, e

backend/apps/system/schemas/system_schema.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,12 @@ class AssistantBase(BaseModel):
7171
class AssistantDTO(AssistantBase, BaseCreatorDTO):
7272
pass
7373

74+
class AssistantHeader(AssistantDTO):
75+
unique: Optional[str] = None
76+
certificate: Optional[str] = None
77+
online: bool = False
78+
79+
7480
class AssistantValidator(BaseModel):
7581
valid: bool = False
7682
id_match: bool = False

backend/common/core/deps.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1+
import base64
12
from typing import Annotated
3+
from urllib.parse import unquote
24

35
from fastapi import Depends, Request
46
from sqlmodel import Session
5-
from apps.system.models.system_model import AssistantModel
6-
from apps.system.schemas.system_schema import UserInfoDTO
7+
from apps.system.schemas.system_schema import AssistantHeader, UserInfoDTO
78
from common.core.db import get_session
89
from common.utils.locale import I18n
910

@@ -19,10 +20,14 @@ async def get_current_user(request: Request) -> UserInfoDTO:
1920

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

22-
async def get_current_assistant(request: Request) -> AssistantModel | None:
23-
return request.state.assistant if hasattr(request.state, "assistant") else None
23+
async def get_current_assistant(request: Request) -> AssistantHeader | None:
24+
base_assistant = request.state.assistant if hasattr(request.state, "assistant") else None
25+
if request.headers.get("X-SQLBOT-ASSISTANT-CERTIFICATE"):
26+
entry_certificate = request.headers['X-SQLBOT-ASSISTANT-CERTIFICATE']
27+
base_assistant.certificate = unquote(base64.b64decode(entry_certificate).decode('utf-8'))
28+
return base_assistant
2429

25-
CurrentAssistant = Annotated[AssistantModel, Depends(get_current_assistant)]
30+
CurrentAssistant = Annotated[AssistantHeader, Depends(get_current_assistant)]
2631

2732

2833

frontend/src/utils/request.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,11 @@ class HttpService {
7575
if (assistantStore.getToken) {
7676
config.headers['X-SQLBOT-ASSISTANT-TOKEN'] = `Assistant ${assistantStore.getToken}`
7777
if (config.headers['X-SQLBOT-TOKEN']) config.headers.delete('X-SQLBOT-TOKEN')
78+
if (assistantStore.getType && assistantStore.getCertificate) {
79+
config.headers['X-SQLBOT-ASSISTANT-CERTIFICATE'] = btoa(
80+
encodeURIComponent(assistantStore.getCertificate)
81+
)
82+
}
7883
}
7984
const locale = getLocale()
8085
if (locale) {
@@ -239,6 +244,11 @@ class HttpService {
239244
if (assistantStore.getToken) {
240245
heads['X-SQLBOT-ASSISTANT-TOKEN'] = `Assistant ${assistantStore.getToken}`
241246
if (heads['X-SQLBOT-TOKEN']) delete heads['X-SQLBOT-TOKEN']
247+
if (assistantStore.getType && assistantStore.getCertificate) {
248+
heads['X-SQLBOT-ASSISTANT-CERTIFICATE'] = btoa(
249+
encodeURIComponent(assistantStore.getCertificate)
250+
)
251+
}
242252
}
243253
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
244254
// @ts-ignore

frontend/src/views/chat/answer/ChartAnswer.vue

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
<script setup lang="ts">
22
import BaseAnswer from './BaseAnswer.vue'
33
import { Chat, chatApi, ChatInfo, type ChatMessage, ChatRecord, questionApi } from '@/api/chat.ts'
4-
import { useAssistantStore } from '@/stores/assistant'
54
import { computed, nextTick, onBeforeUnmount, ref } from 'vue'
6-
const assistantStore = useAssistantStore()
75
const props = withDefaults(
86
defineProps<{
97
chatList?: Array<ChatInfo>
@@ -102,10 +100,7 @@ const sendMessage = async () => {
102100
const param = {
103101
question: currentRecord.question,
104102
chat_id: _currentChatId.value,
105-
assistant_certificate: assistantStore.getCertificate,
106103
}
107-
console.log(assistantStore.getCertificate)
108-
console.log(param)
109104
const response = await questionApi.add(param, controller)
110105
const reader = response.body.getReader()
111106
const decoder = new TextDecoder()

frontend/src/views/embedded/assistant.vue

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,6 @@ const communicationCb = async (event: any) => {
109109
}
110110
if (event.data?.busi == 'certificate') {
111111
const certificate = event.data['certificate']
112-
console.log(certificate)
113112
assistantStore.setType(1)
114113
assistantStore.setCertificate(certificate)
115114
// store certificate to pinia

0 commit comments

Comments
 (0)