From 3c1f2e9885cdb01c1690013802249ca3f68eeb1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B9=E5=8D=9A?= <1016318004@qq.com> Date: Wed, 5 Feb 2025 10:40:07 +0800 Subject: [PATCH 1/4] =?UTF-8?q?=E4=BF=AE=E6=94=B9plugin=E5=88=B0app?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/common/queue.py | 11 ++++++----- apps/entities/plugin.py | 4 ++-- apps/scheduler/scheduler/scheduler.py | 13 ++++++++----- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/apps/common/queue.py b/apps/common/queue.py index 0aac111dc..eab5b7aab 100644 --- a/apps/common/queue.py +++ b/apps/common/queue.py @@ -65,7 +65,7 @@ class MessageQueue: if not history_ids: # 如果new_history为空,则说明是第一次执行,创建一个空值 flow = MessageFlow( - appId=tcb.flow_state.plugin_id, + appId=tcb.flow_state.app_id, flowId=tcb.flow_state.name, stepId="start", stepStatus=StepStatus.RUNNING, @@ -75,7 +75,8 @@ class MessageQueue: history = tcb.flow_context[tcb.flow_state.step_id] flow = MessageFlow( - appId=history.plugin_id, + # TODO:appId 和 flowId 暂时使用flow_id + appId=history.flow_id, flowId=history.flow_id, stepId=history.step_id, stepStatus=history.status, @@ -86,9 +87,9 @@ class MessageQueue: message = MessageBase( event=event_type, id=tcb.record.id, - group_id=tcb.record.group_id, - conversation_id=tcb.record.conversation_id, - task_id=tcb.record.task_id, + groupId=tcb.record.group_id, + conversationId=tcb.record.conversation_id, + taskId=tcb.record.task_id, metadata=metadata, flow=flow, content=data, diff --git a/apps/entities/plugin.py b/apps/entities/plugin.py index af3082082..52074931a 100644 --- a/apps/entities/plugin.py +++ b/apps/entities/plugin.py @@ -7,7 +7,7 @@ from typing import Any from pydantic import BaseModel, Field from apps.common.queue import MessageQueue -from apps.entities.task import FlowHistory, RequestDataPlugin +from apps.entities.task import FlowHistory, RequestDataApp class SysCallVars(BaseModel): @@ -42,7 +42,7 @@ class SysExecVars(BaseModel): question: str = Field(description="当前Agent的目标") task_id: str = Field(description="当前Executor关联的TaskID") session_id: str = Field(description="当前用户的Session ID") - plugin_data: RequestDataPlugin = Field(description="传递给Executor中Call的参数") + App_data: RequestDataApp = Field(description="传递给Executor中Call的参数") background: ExecutorBackground = Field(description="当前Executor的背景信息") class Config: diff --git a/apps/scheduler/scheduler/scheduler.py b/apps/scheduler/scheduler/scheduler.py index 4c078d079..f1ed5eb1b 100644 --- a/apps/scheduler/scheduler/scheduler.py +++ b/apps/scheduler/scheduler/scheduler.py @@ -19,7 +19,7 @@ from apps.entities.plugin import ExecutorBackground, SysExecVars from apps.entities.rag_data import RAGQueryReq from apps.entities.record import RecordDocument from apps.entities.request_data import RequestData -from apps.entities.task import RequestDataPlugin +from apps.entities.task import RequestDataApp from apps.manager import ( DocumentManager, RecordManager, @@ -73,7 +73,8 @@ class Scheduler: # 捕获所有异常:出现问题就输出日志,并停止queue try: # 根据用户的请求,返回插件ID列表,选择Flow - self._plugin_id, user_selected_flow = await choose_flow(self._task_id, post_body.question, post_body.plugins) + # self._plugin_id, user_selected_flow = await choose_flow(self._task_id, post_body.question, post_body.apps) + user_selected_flow = None # 获取当前问答可供关联的文档 docs, doc_ids = await self._get_docs(user_sub, post_body) # 获取上下文;最多20轮 @@ -89,7 +90,7 @@ class Scheduler: question=post_body.question, language=post_body.language, document_ids=doc_ids, - kb_sn=None if not user_info.kb_id else user_info.kb_id, + kb_sn=None if user_info is None or not user_info.kb_id else user_info.kb_id, history=context, top_k=5, ) @@ -139,7 +140,7 @@ class Scheduler: await self._queue.close() - async def run_executor(self, session_id: str, post_body: RequestData, background: ExecutorBackground, user_selected_flow: RequestDataPlugin) -> bool: + async def run_executor(self, session_id: str, post_body: RequestData, background: ExecutorBackground, user_selected_flow: RequestDataApp) -> bool: """构造FlowExecutor,并执行所选择的流""" # 获取当前Task task = await TaskManager.get_task(self._task_id) @@ -201,7 +202,9 @@ class Scheduler: user_sub=user_sub, data=encrypt_data, key=encrypt_config, - facts=self._facts, + # facts=self._facts, + #TODO:暂时不使用facts + facts=[], metadata=task.record.metadata, created_at=task.record.created_at, flow=task.new_context, -- Gitee From 7dcc883a1988598c35cb73d1dcdd96a15ae47a7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B9=E5=8D=9A?= <1016318004@qq.com> Date: Wed, 5 Feb 2025 10:40:41 +0800 Subject: [PATCH 2/4] =?UTF-8?q?=E5=AF=B9=E8=AF=9D=E7=9B=B8=E5=85=B3bug=20f?= =?UTF-8?q?ix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/entities/request_data.py | 8 +- apps/manager/conversation.py | 19 ++-- apps/routers/chat.py | 3 + apps/routers/conversation.py | 4 +- apps/scheduler/scheduler/flow.py | 62 +---------- apps/service/suggestion.py | 185 ++++++++++++++++--------------- 6 files changed, 119 insertions(+), 162 deletions(-) diff --git a/apps/entities/request_data.py b/apps/entities/request_data.py index 9061c4b68..50ab6a676 100644 --- a/apps/entities/request_data.py +++ b/apps/entities/request_data.py @@ -22,11 +22,11 @@ class RequestData(BaseModel): """POST /api/chat 请求的总的数据结构""" question: str = Field(max_length=2000, description="用户输入") - conversation_id: str - group_id: str + conversation_id: str = Field(default=None, alias="conversationId", description="会话ID") + group_id: Optional[str] = Field(default=None, alias="groupId", description="群组ID") language: str = Field(default="zh", description="语言") - files: list[str] = Field(default=[]) - apps: list[RequestDataApp] = Field(default=[]) + files: list[str] = Field(default=[], description="文件列表") + app: list[RequestDataApp] = Field(default=[], description="应用列表") features: RequestDataFeatures = Field(description="消息功能设置") diff --git a/apps/manager/conversation.py b/apps/manager/conversation.py index f595d0c5b..9672196fd 100644 --- a/apps/manager/conversation.py +++ b/apps/manager/conversation.py @@ -56,16 +56,17 @@ class ConversationManager: update_data: dict[str, dict[str, Any]] = { "$push": {"conversations": conversation_id}, } + if app_id: # 非调试模式下更新应用使用情况 - if not is_debug: - update_data["$set"] = {f"app_usage.{app_id}.last_used": round(datetime.now(timezone.utc).timestamp(), 3)} - update_data["$inc"] = {f"app_usage.{app_id}.count": 1} - await user_collection.update_one( - {"_id": user_sub}, - update_data, - session=session, - ) - await session.commit_transaction() + if not is_debug: + update_data["$set"] = {f"app_usage.{app_id}.last_used": round(datetime.now(timezone.utc).timestamp(), 3)} + update_data["$inc"] = {f"app_usage.{app_id}.count": 1} + await user_collection.update_one( + {"_id": user_sub}, + update_data, + session=session, + ) + await session.commit_transaction() return conv except Exception as e: LOGGER.info(f"[ConversationManager] Add conversation by user_sub failed: {e}") diff --git a/apps/routers/chat.py b/apps/routers/chat.py index ded2007c6..7d06a6041 100644 --- a/apps/routers/chat.py +++ b/apps/routers/chat.py @@ -27,6 +27,7 @@ from apps.manager import ( TaskManager, UserBlacklistManager, ) +from apps.manager.appcenter import AppCenterManager from apps.scheduler.scheduler import Scheduler from apps.service.activity import Activity @@ -129,6 +130,8 @@ async def chat( if await Activity.is_active(user_sub): raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many requests") + if post_body.app and post_body.app[0].app_id: + await AppCenterManager.update_recent_app(user_sub, post_body.app[0].app_id) res = chat_generator(post_body, user_sub, session_id) return StreamingResponse( content=res, diff --git a/apps/routers/conversation.py b/apps/routers/conversation.py index 80f36d7ef..9f3f8ba23 100644 --- a/apps/routers/conversation.py +++ b/apps/routers/conversation.py @@ -62,7 +62,7 @@ async def create_new_conversation( # 新建对话 if create_new: - if not AppManager.validate_user_app_access(user_sub, app_id): + if app_id and not await AppManager.validate_user_app_access(user_sub, app_id): err = "Invalid app_id." raise RuntimeError(err) new_conv = await ConversationManager.add_conversation_by_user_sub(user_sub, @@ -134,6 +134,8 @@ async def add_conversation( # 尝试创建新对话 try: app_id = appId if appId else "" + if appId: + conversations = [] is_debug = isDebug if isDebug is not None else False new_conv = await create_new_conversation(user_sub, conversations, app_id=app_id, is_debug=is_debug) diff --git a/apps/scheduler/scheduler/flow.py b/apps/scheduler/scheduler/flow.py index c03978fb4..155203268 100644 --- a/apps/scheduler/scheduler/flow.py +++ b/apps/scheduler/scheduler/flow.py @@ -9,7 +9,7 @@ from apps.llm.patterns import Select from apps.scheduler.pool.pool import Pool -async def choose_flow(task_id: str, question: str, origin_app_list: list[RequestDataApp]) -> tuple[str, Optional[RequestDataApp]]: +async def choose_flow(task_id: str, question: str, origin_app: RequestDataApp) -> tuple[str, Optional[RequestDataApp]]: """依据用户的输入和选择,构造对应的Flow。 - 当用户没有选择任何Plugin时,直接进行智能问答 @@ -17,60 +17,8 @@ async def choose_flow(task_id: str, question: str, origin_app_list: list[Request - 当用户选择Plugin时,在plugin内挑选最适合的flow :param question: 用户输入(用户问题) - :param origin_plugin_list: 用户选择的插件,可以一次选择多个 - :result: 经LLM选择的Plugin ID和Flow ID + :param origin_app: 用户选择的app信息 + :result: 经LLM选择的App ID和Flow ID """ - # 去掉无效的插件选项:plugin_id为空 - app_ids = [] - flow_ids = [] - for item in origin_app_list: - if not item.app_id: - continue - app_ids.append(item.app_id) - if item.flow_id: - flow_ids.append(item) - - # 用户什么都不选,直接智能问答 - if len(app_ids) == 0: - return "", None - - # 用户只选了auto - if len(app_ids) == 1 and app_ids[0] == "auto": - # 用户要求自动识别 - plugin_top = Pool().get_k_plugins(question) - # 聚合插件的Flow - plugin_ids = [str(plugin.name) for plugin in plugin_top] - - # 用户固定了Flow的ID - if len(flow_ids) > 0: - # 直接使用对应的Flow,不选择 - return plugin_ids[0], flow_ids[0] - - # 用户选了插件 - flows = Pool().get_k_flows(question, plugin_ids) - - # 使用大模型选择Top1 Flow - flow_list = [{ - "name": str(item.plugin) + "/" + str(item.name), - "description": str(item.description), - } for item in flows] - - if len(plugin_ids) == 1 and plugin_ids[0] == "auto": - # 用户选择自动识别时,包含智能问答 - flow_list += [{ - "name": "KnowledgeBase", - "description": "当上述工具无法直接解决用户问题时,使用知识库进行回答。", - }] - - # 返回top1 Flow的ID - selected_id = await Select().generate(task_id=task_id, choices=flow_list, question=question) - if selected_id == "KnowledgeBase": - return "", None - - app_id = selected_id.split("/")[0] - flow_id = selected_id.split("/")[1] - return app_id, RequestDataApp( - app_id=app_id, - flow_id=flow_id, - params={}, - ) + # TODO: 根据用户选择的App,选一次top_k flow + return "", None \ No newline at end of file diff --git a/apps/service/suggestion.py b/apps/service/suggestion.py index b23e95e02..4e4deb9d5 100644 --- a/apps/service/suggestion.py +++ b/apps/service/suggestion.py @@ -11,7 +11,7 @@ from apps.constants import LOGGER from apps.entities.collection import RecordContent from apps.entities.enum_var import EventType from apps.entities.message import SuggestContent -from apps.entities.task import RequestDataPlugin +from apps.entities.task import RequestDataApp from apps.llm.patterns.recommend import Recommend from apps.manager import ( RecordManager, @@ -28,7 +28,7 @@ USER_TOP_DOMAINS_NUM = 5 HISTORY_QUESTIONS_NUM = 4 -async def plan_next_flow(user_sub: str, task_id: str, queue: MessageQueue, user_selected_plugins: list[RequestDataPlugin]) -> None: # noqa: C901, PLR0912 +async def plan_next_flow(user_sub: str, task_id: str, queue: MessageQueue, user_selected_plugins: RequestDataApp) -> None: # noqa: C901, PLR0912 """生成用户“下一步”Flow的推荐。 - 若Flow的配置文件中已定义`next_flow[]`字段,则直接使用该字段给定的值 @@ -69,99 +69,102 @@ async def plan_next_flow(user_sub: str, task_id: str, queue: MessageQueue, user_ generated_questions += f"{question}\n" content = SuggestContent( question=question, - plugin_id="", - flow_id="", - flow_description="", + appId="", + flowId="", + flowDescription="", ) await queue.push_output(event_type=EventType.SUGGEST, data=content.model_dump(exclude_none=True, by_alias=True)) return # 当前使用了Flow flow_id = task.flow_state.name - plugin_id = task.flow_state.plugin_id - _, flow_data = Pool().get_flow(flow_id, plugin_id) - if flow_data is None: - err = "Flow数据不存在" - raise ValueError(err) - - if flow_data.next_flow is None: - # 根据用户选择的插件,选一次top_k flow - plugin_ids = [] - for plugin in user_selected_plugins: - if plugin.plugin_id and plugin.plugin_id not in plugin_ids: - plugin_ids.append(plugin.plugin_id) - result = Pool().get_k_flows(task.record.content.question, plugin_ids) - for i, flow in enumerate(result): - if i >= MAX_RECOMMEND: - break - # 改写问题 - rewrite_question = await Recommend().generate( - task_id=task_id, - action_description=flow.description, - history_questions=last_n_questions, - recent_question=current_record, - user_preference=str(user_domain), - shown_questions=generated_questions, - ) - generated_questions += f"{rewrite_question}\n" - - content = SuggestContent( - plugin_id=plugin_id, - flow_id=flow_id, - flow_description=str(flow.description), - question=rewrite_question, - ) - await queue.push_output(event_type=EventType.SUGGEST, data=content.model_dump(exclude_none=True, by_alias=True)) - return - - # 当前有next_flow - for i, next_flow in enumerate(flow_data.next_flow): - # 取前MAX_RECOMMEND个Flow,保持顺序 - if i >= MAX_RECOMMEND: - break - - if next_flow.plugin is not None: - next_flow_plugin_id = next_flow.plugin - else: - next_flow_plugin_id = plugin_id - - flow_metadata, _ = Pool().get_flow( - next_flow.id, - next_flow_plugin_id, - ) - - # flow不合法 - if flow_metadata is None: - LOGGER.error(f"Flow {next_flow.id} in {next_flow_plugin_id} not found") - continue - - # 如果设置了question,直接使用这个question - if next_flow.question is not None: - content = SuggestContent( - plugin_id=next_flow_plugin_id, - flow_id=next_flow.id, - flow_description=str(flow_metadata.description), - question=next_flow.question, - ) - await queue.push_output(event_type=EventType.SUGGEST, data=content.model_dump(exclude_none=True, by_alias=True)) - continue - - # 没有设置question,则需要生成问题 - rewrite_question = await Recommend().generate( - task_id=task_id, - action_description=flow_metadata.description, - history_questions=last_n_questions, - recent_question=current_record, - user_preference=str(user_domain), - shown_questions=generated_questions, - ) - generated_questions += f"{rewrite_question}\n" - content = SuggestContent( - plugin_id=next_flow_plugin_id, - flow_id=next_flow.id, - flow_description=str(flow_metadata.description), - question=rewrite_question, - ) - await queue.push_output(event_type=EventType.SUGGEST, data=content.model_dump(exclude_none=True, by_alias=True)) - continue + app_id = task.flow_state.app_id return + # TODO: 推荐flow待完善 + # _, flow_data = Pool().get_flow(flow_id, app_id) + # if flow_data is None: + # err = "Flow数据不存在" + # raise ValueError(err) + + # if flow_data.next_flow is None: + # # 根据用户选择的插件,选一次top_k flow + # app_ids = [] + # for plugin in user_selected_plugins: + # if plugin.app_id and plugin.app_id not in app_ids: + # app_ids.append(plugin.app_id) + # result = Pool().get_k_flows(task.record.content.question, app_ids) + # for i, flow in enumerate(result): + # if i >= MAX_RECOMMEND: + # break + # # 改写问题 + # rewrite_question = await Recommend().generate( + # task_id=task_id, + # action_description=flow.description, + # history_questions=last_n_questions, + # recent_question=current_record, + # user_preference=str(user_domain), + # shown_questions=generated_questions, + # ) + # generated_questions += f"{rewrite_question}\n" + + # content = SuggestContent( + # app_id=app_id, + # flow_id=flow_id, + # flow_description=str(flow.description), + # question=rewrite_question, + # ) + # await queue.push_output(event_type=EventType.SUGGEST, data=content.model_dump(exclude_none=True, by_alias=True)) + # return + + # # 当前有next_flow + # for i, next_flow in enumerate(flow_data.next_flow): + # # 取前MAX_RECOMMEND个Flow,保持顺序 + # if i >= MAX_RECOMMEND: + # break + + # if next_flow.plugin is not None: + # next_flow_app_id = next_flow.plugin + # else: + # next_flow_app_id = app_id + + # flow_metadata, _ = next_flow.id, next_flow_app_id, + # # flow_metadata, _ = Pool().get_flow( + # # next_flow.id, + # # next_flow_app_id, + # # ) + + # # flow不合法 + # if flow_metadata is None: + # LOGGER.error(f"Flow {next_flow.id} in {next_flow_app_id} not found") + # continue + + # # 如果设置了question,直接使用这个question + # if next_flow.question is not None: + # content = SuggestContent( + # appId=next_flow_app_id, + # flowId=next_flow.id, + # flowDescription=str(flow_metadata.description), + # question=next_flow.question, + # ) + # await queue.push_output(event_type=EventType.SUGGEST, data=content.model_dump(exclude_none=True, by_alias=True)) + # continue + + # # 没有设置question,则需要生成问题 + # rewrite_question = await Recommend().generate( + # task_id=task_id, + # action_description=flow_metadata.description, + # history_questions=last_n_questions, + # recent_question=current_record, + # user_preference=str(user_domain), + # shown_questions=generated_questions, + # ) + # generated_questions += f"{rewrite_question}\n" + # content = SuggestContent( + # appId=next_flow_app_id, + # flowId=next_flow.id, + # flowDescription=str(flow_metadata.description), + # question=rewrite_question, + # ) + # await queue.push_output(event_type=EventType.SUGGEST, data=content.model_dump(exclude_none=True, by_alias=True)) + # continue + # return -- Gitee From 0cb319e19a0daff6b547f4a433577c8a5d158382 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B9=E5=8D=9A?= <1016318004@qq.com> Date: Wed, 5 Feb 2025 10:41:20 +0800 Subject: [PATCH 3/4] appcenter bug fix --- apps/entities/response_data.py | 9 +++++-- apps/manager/appcenter.py | 46 ++++++++++++++++++++++++++++++++-- apps/routers/appcenter.py | 13 +++++----- 3 files changed, 58 insertions(+), 10 deletions(-) diff --git a/apps/entities/response_data.py b/apps/entities/response_data.py index e2c558004..ae685d19e 100644 --- a/apps/entities/response_data.py +++ b/apps/entities/response_data.py @@ -9,7 +9,12 @@ from pydantic import BaseModel, Field from apps.entities.appcenter import AppCenterCardItem, AppData from apps.entities.collection import Blacklist, Document, NodeMetaData from apps.entities.enum_var import DocumentStatus -from apps.entities.flow_topology import FlowItem, NodeMetaDataItem, PositionItem, ServiceItem +from apps.entities.flow_topology import ( + FlowItem, + NodeMetaDataItem, + PositionItem, + ServiceItem, +) from apps.entities.record import RecordData @@ -284,7 +289,7 @@ class GetAppListMsg(BaseModel): """GET /api/app Result数据结构""" page_number: int = Field(..., alias="currentPage", description="当前页码") - page_count: int = Field(..., alias="totalPages", description="总页数") + app_count: int = Field(..., alias="total", description="总页数") applications: list[AppCenterCardItem] = Field(..., description="应用列表") diff --git a/apps/manager/appcenter.py b/apps/manager/appcenter.py index f94866bb3..1d5c3bf73 100644 --- a/apps/manager/appcenter.py +++ b/apps/manager/appcenter.py @@ -3,6 +3,7 @@ Copyright (c) Huawei Technologies Co., Ltd. 2024-2025. All rights reserved. """ import uuid +from datetime import datetime, timezone from enum import Enum from typing import Any, Optional @@ -197,7 +198,7 @@ class AppCenterManager: } if published_false_needed: update_data["published"] = False - await app_collection.update_one({"_id": app_id}, {"$set": update_data}) + await app_collection.update_one({"_id": app_id}, {"$set": jsonable_encoder(update_data)}) return True except Exception as e: LOGGER.error(f"[AppCenterManager] Update app failed: {e}") @@ -329,7 +330,7 @@ class AppCenterManager: try: app_collection = MongoDB.get_collection("app") total_apps = await app_collection.count_documents(search_conditions) - total_pages = (total_apps + page_size - 1) // page_size + total_pages = total_apps db_data = await app_collection.find(search_conditions) \ .sort("created_at", -1) \ .skip((page - 1) * page_size) \ @@ -351,3 +352,44 @@ class AppCenterManager: except Exception as e: LOGGER.info(f"[AppCenterManager] Get favorite app ids by user_sub failed: {e}") return [] + + @staticmethod + async def update_recent_app(user_sub: str, app_id: str) -> bool: + """更新用户的最近使用应用列表 + + :param user_sub: 用户唯一标识 + :param app_id: 应用唯一标识 + :return: 更新是否成功 + """ + try: + # 获取 user 集合 + user_collection = MongoDB.get_collection("user") + + # 获取当前时间戳 + current_time = round(datetime.now(tz=timezone.utc).timestamp(), 3) + + # 更新用户的 app_usage 字段 + result = await user_collection.update_one( + {"_id": user_sub}, # 查询条件 + { + "$set": { + f"app_usage.{app_id}.last_used": current_time, # 更新最后使用时间 + }, + "$inc": { + f"app_usage.{app_id}.count": 1, # 增加使用次数 + }, + }, + upsert=True, # 如果 app_usage 字段或 app_id 不存在,则创建 + ) + + # 检查更新是否成功 + if result.modified_count > 0 or result.upserted_id is not None: + LOGGER.info(f"[AppCenterManager] Updated recent app for user {user_sub}: {app_id}") + return True + else: + LOGGER.warning(f"[AppCenterManager] No changes made for user {user_sub}") + return False + + except Exception as e: + LOGGER.error(f"[AppCenterManager] Failed to update recent app: {e}") + return False \ No newline at end of file diff --git a/apps/routers/appcenter.py b/apps/routers/appcenter.py index 8ba2f16c3..f9c1255fc 100644 --- a/apps/routers/appcenter.py +++ b/apps/routers/appcenter.py @@ -5,6 +5,7 @@ Copyright (c) Huawei Technologies Co., Ltd. 2024-2025. All rights reserved. from typing import Annotated, Optional, Union from fastapi import APIRouter, Body, Depends, Path, Query, status +from fastapi.requests import HTTPConnection from fastapi.responses import JSONResponse from apps.dependency.csrf import verify_csrf_token @@ -53,17 +54,17 @@ async def get_applications( # noqa: ANN201, PLR0913 result={}, ) - app_cards, total_pages = [], -1 + app_cards, total_apps = [], -1 if my_app: # 筛选我创建的 - app_cards, total_pages = await AppCenterManager.fetch_user_apps( + app_cards, total_apps = await AppCenterManager.fetch_user_apps( user_sub, search_type, keyword, page, page_size) elif my_fav: # 筛选已收藏的 - app_cards, total_pages = await AppCenterManager.fetch_favorite_apps( + app_cards, total_apps = await AppCenterManager.fetch_favorite_apps( user_sub, search_type, keyword, page, page_size) else: # 获取所有应用 - app_cards, total_pages = await AppCenterManager.fetch_all_apps( + app_cards, total_apps = await AppCenterManager.fetch_all_apps( user_sub, search_type, keyword, page, page_size) - if total_pages == -1: + if total_apps == -1: return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content=ResponseData( code=status.HTTP_500_INTERNAL_SERVER_ERROR, message="查询失败", @@ -74,7 +75,7 @@ async def get_applications( # noqa: ANN201, PLR0913 message="查询成功", result=GetAppListMsg( currentPage=page, - totalPages=total_pages, + total=total_apps, applications=app_cards, ), ).model_dump(exclude_none=True, by_alias=True)) -- Gitee From 85ed88b2e56a4caa63225302c4287b3d3b663dac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B9=E5=8D=9A?= <1016318004@qq.com> Date: Wed, 5 Feb 2025 10:52:13 +0800 Subject: [PATCH 4/4] fixed --- apps/entities/plugin.py | 2 +- apps/manager/appcenter.py | 15 +++++++-------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/apps/entities/plugin.py b/apps/entities/plugin.py index 52074931a..658624dda 100644 --- a/apps/entities/plugin.py +++ b/apps/entities/plugin.py @@ -42,7 +42,7 @@ class SysExecVars(BaseModel): question: str = Field(description="当前Agent的目标") task_id: str = Field(description="当前Executor关联的TaskID") session_id: str = Field(description="当前用户的Session ID") - App_data: RequestDataApp = Field(description="传递给Executor中Call的参数") + app_data: RequestDataApp = Field(description="传递给Executor中Call的参数") background: ExecutorBackground = Field(description="当前Executor的背景信息") class Config: diff --git a/apps/manager/appcenter.py b/apps/manager/appcenter.py index 1d5c3bf73..bd0a34115 100644 --- a/apps/manager/appcenter.py +++ b/apps/manager/appcenter.py @@ -46,7 +46,7 @@ class AppCenterManager: search_type, keyword, ) if keyword and search_type != SearchType.AUTHOR else {} - apps, total_pages = await AppCenterManager._search_apps_by_filter(filters, page, page_size) + apps, total_apps = await AppCenterManager._search_apps_by_filter(filters, page, page_size) return [ AppCenterCardItem( appId=app.id, @@ -58,7 +58,7 @@ class AppCenterManager: published=app.published, ) for app in apps - ], total_pages + ], total_apps except Exception as e: LOGGER.error(f"[AppCenterManager] Get app list failed: {e}") return [], -1 @@ -80,7 +80,7 @@ class AppCenterManager: search_type, keyword, ) if keyword and search_type != SearchType.AUTHOR else base_filter - apps, total_pages = await AppCenterManager._search_apps_by_filter(filters, page, page_size) + apps, total_apps= await AppCenterManager._search_apps_by_filter(filters, page, page_size) return [ AppCenterCardItem( appId=app.id, @@ -92,7 +92,7 @@ class AppCenterManager: published=app.published, ) for app in apps - ], total_pages + ], total_apps except Exception as e: LOGGER.info(f"[AppCenterManager] Get app list by user failed: {e}") return [], -1 @@ -118,7 +118,7 @@ class AppCenterManager: search_type, keyword, ) if keyword else base_filter - apps, total_pages = await AppCenterManager._search_apps_by_filter(filters, page, page_size) + apps, total_apps = await AppCenterManager._search_apps_by_filter(filters, page, page_size) return [ AppCenterCardItem( appId=app.id, @@ -130,7 +130,7 @@ class AppCenterManager: published=app.published, ) for app in apps - ], total_pages + ], total_apps except Exception as e: LOGGER.info(f"[AppCenterManager] Get favorite app list failed: {e}") return [], -1 @@ -330,14 +330,13 @@ class AppCenterManager: try: app_collection = MongoDB.get_collection("app") total_apps = await app_collection.count_documents(search_conditions) - total_pages = total_apps db_data = await app_collection.find(search_conditions) \ .sort("created_at", -1) \ .skip((page - 1) * page_size) \ .limit(page_size) \ .to_list(length=page_size) apps = [AppPool.model_validate(doc) for doc in db_data] - return apps, total_pages + return apps, total_apps except Exception as e: LOGGER.info(f"[AppCenterManager] Search apps by filter failed: {e}") return [], -1 -- Gitee