mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-14 16:49:59 +08:00
♻️ refactor(core): 重构 AI 编排框架与记忆及 RAG 子系统 (#2149)
* ♻️ refactor(core): 重构 AI 编排框架与记忆及 RAG 子系统 - 【重构】重构 `BaseRunnable` 并引入统一的 `RunIntent` 意图载体,规范 Agent、Team 和 Workflow 的执行流 - 【解耦】将中期记忆槽和长期向量记忆从 `MemoryConfig` 中解耦,转为独立的能力组件与工具箱进行管理 - 【记忆】移除 `MemoryReader` 和 `MemoryWriter`,统一封装为 `SessionMemoryContext` 会话记忆门面 - 【RAG】重构检索器与存储后端接口,统一采用 `QueryRequest` 进行多维度联合检索,并引入 `InMemoryScorer` 提升打分性能 - 【事件】优化 `EventBus` 异步事件分发机制,引入队列机制确保事件按序处理,避免并发竞态问题 - 【依赖注入】移除 `memory` 注入项,优化 `DependencyInjector` 的签名解析缓存以提升性能 * 🚨 auto fix by pre-commit hooks --------- Co-authored-by: webjoin111 <455457521@qq.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
webjoin111
pre-commit-ci[bot]
parent
922d092650
commit
52f7dbdedf
@@ -12,6 +12,7 @@ from .hooks import Hooks
|
||||
from .models import (
|
||||
AgentRunResult,
|
||||
AgentTask,
|
||||
RunIntent,
|
||||
StreamedRunResult,
|
||||
)
|
||||
from .session import session_manager
|
||||
@@ -28,6 +29,7 @@ __all__ = [
|
||||
"Inject",
|
||||
"NoneBotDeps",
|
||||
"RunContext",
|
||||
"RunIntent",
|
||||
"StreamedRunResult",
|
||||
"UIController",
|
||||
"get_current_run_context",
|
||||
|
||||
@@ -8,6 +8,9 @@ from typing import TYPE_CHECKING, Any, Generic, cast, get_origin
|
||||
from typing_extensions import TypeVar
|
||||
import uuid
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from zhenxun.services.ai.context.memory.types import SessionMetadata
|
||||
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.matcher import Matcher, current_bot, current_event, current_matcher
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
@@ -19,16 +22,12 @@ from zhenxun.services.ai.core.models import CancellationToken
|
||||
from zhenxun.services.ai.core.protocols.tool import ToolExecutable
|
||||
from zhenxun.services.ai.core.stream_events import AgentStreamEvent, EventBus
|
||||
from zhenxun.services.ai.utils import ContextUtils
|
||||
from zhenxun.services.ai.utils.scope import ScopeSelector
|
||||
from zhenxun.services.scheduler.types import ScheduleContext
|
||||
from zhenxun.utils.platform import PlatformUtils
|
||||
from zhenxun.utils.utils import infer_plugin_namespace
|
||||
|
||||
from .blackboard import BlackboardManager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from zhenxun.services.ai.context.memory.facades import AgentSessionFacade
|
||||
|
||||
AgentDepsT = TypeVar("AgentDepsT", default=Any)
|
||||
"""泛型类型变量:外部环境依赖对象 (Agent Dependencies)。"""
|
||||
ProviderFunc = Callable[["RunContext"], Any | Awaitable[Any]]
|
||||
@@ -114,31 +113,8 @@ class SessionContext(Generic[AgentDepsT]):
|
||||
"""触发事件的插件命名空间"""
|
||||
append_only_manager: Any = dataclasses.field(default=None)
|
||||
"""用于大模型前缀缓存命中优化的追加写入管理器。"""
|
||||
|
||||
@property
|
||||
def memory(self) -> "AgentSessionFacade":
|
||||
"""
|
||||
获取当前会话的持久化记忆访问门面 (AgentSessionFacade)。
|
||||
提供极简的 history 和 slots 操作 API。
|
||||
"""
|
||||
from zhenxun.services.ai.context.memory.facades import AgentSessionFacade
|
||||
from zhenxun.services.ai.context.memory.manager import memory_manager
|
||||
from zhenxun.services.ai.context.memory.types import SessionMetadata
|
||||
|
||||
user_id = ContextUtils.extract_user_id(self.deps)
|
||||
group_id = ContextUtils.extract_group_id(self.deps)
|
||||
platform = ContextUtils.extract_platform(self.deps)
|
||||
|
||||
meta = SessionMetadata(
|
||||
session_id=self.session_id,
|
||||
selector=ScopeSelector(
|
||||
user_id=user_id,
|
||||
group_id=group_id,
|
||||
platform=platform,
|
||||
namespace=self.namespace,
|
||||
),
|
||||
)
|
||||
return AgentSessionFacade(memory_manager, meta)
|
||||
session_meta: "SessionMetadata | None" = dataclasses.field(default=None)
|
||||
"""隔离会话的元信息(Session ID, 命名空间, 权限等),在状态流转中生成"""
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
@@ -324,7 +300,7 @@ class RunContext(Generic[AgentDepsT]):
|
||||
self.deps.get("namespace") if isinstance(self.deps, dict) else None
|
||||
)
|
||||
if not ns:
|
||||
ns = infer_plugin_namespace(default="global")
|
||||
ns = infer_plugin_namespace()
|
||||
|
||||
self.session = SessionContext(
|
||||
session_id=self.session_id or "default_session",
|
||||
|
||||
@@ -1,14 +1,27 @@
|
||||
from collections import defaultdict
|
||||
from collections.abc import Awaitable, Callable
|
||||
from functools import lru_cache
|
||||
import inspect
|
||||
from typing import Annotated, Any, ClassVar, cast
|
||||
|
||||
|
||||
@lru_cache(maxsize=2048)
|
||||
def _get_signature_cached(func: Callable) -> inspect.Signature:
|
||||
return inspect.signature(func)
|
||||
|
||||
|
||||
def get_signature(func: Callable) -> inspect.Signature:
|
||||
try:
|
||||
return _get_signature_cached(func)
|
||||
except TypeError:
|
||||
return inspect.signature(func)
|
||||
|
||||
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.utils import is_coroutine_callable
|
||||
from nonebot_plugin_session import EventSession, extract_session
|
||||
|
||||
from zhenxun.services.ai.context.memory.facades import AgentSessionFacade
|
||||
from zhenxun.utils.utils import infer_plugin_namespace
|
||||
|
||||
from .blackboard import BlackboardManager
|
||||
@@ -59,7 +72,7 @@ CurrentEventPayload = Annotated[Any, Hidden(), _InjectMarker("stream_event")]
|
||||
CurrentBlackboard = Annotated[
|
||||
BlackboardManager | None, Hidden(), _InjectMarker("blackboard")
|
||||
]
|
||||
CurrentMemory = Annotated[AgentSessionFacade, Hidden(), _InjectMarker("memory")]
|
||||
|
||||
CurrentSandbox = Annotated[Any, Hidden(), _InjectMarker("sandbox")]
|
||||
|
||||
|
||||
@@ -160,9 +173,6 @@ class Inject:
|
||||
Blackboard = CurrentBlackboard
|
||||
"""自动注入:当前工作流/团队挂载的强类型黑板 (BlackboardManager) 实例"""
|
||||
|
||||
Memory = CurrentMemory
|
||||
"""自动注入:当前会话的持久化记忆存取门面 (AgentSessionFacade) 实例"""
|
||||
|
||||
Sandbox = CurrentSandbox
|
||||
"""自动注入:当前沙箱环境管理器实例"""
|
||||
|
||||
@@ -314,7 +324,7 @@ class DependencyInjector:
|
||||
context: RunContext,
|
||||
) -> Any:
|
||||
"""统一执行带有依赖注入的函数 (支持同步/异步)"""
|
||||
sig = inspect.signature(func)
|
||||
sig = get_signature(func)
|
||||
resolved_kwargs = await cls.resolve_all(sig, call_kwargs, context)
|
||||
filtered_kwargs = {
|
||||
k: v for k, v in resolved_kwargs.items() if k in sig.parameters
|
||||
@@ -354,7 +364,6 @@ Inject.register_provider(
|
||||
Inject.register_provider(
|
||||
"shared_state", lambda ctx: ctx.session.shared_state, scope="global"
|
||||
)
|
||||
Inject.register_provider("memory", lambda ctx: ctx.session.memory, scope="global")
|
||||
|
||||
|
||||
def _resolve_blackboard(ctx: RunContext):
|
||||
|
||||
@@ -4,16 +4,15 @@ from __future__ import annotations
|
||||
运行时(Run)相关核心类型定义
|
||||
"""
|
||||
|
||||
from collections.abc import AsyncIterator, Callable
|
||||
from collections.abc import AsyncIterator
|
||||
import json
|
||||
from typing import Any, Generic, cast
|
||||
from typing_extensions import TypeVar
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr
|
||||
|
||||
from zhenxun.services.ai.core.messages import AgentMessage, LLMMessage, UsageInfo
|
||||
from zhenxun.services.ai.core.messages.types import OutputDataT
|
||||
from zhenxun.services.ai.core.options import BaseOutputDefinition
|
||||
from zhenxun.services.ai.core.protocols.tool import ToolResolvable
|
||||
from zhenxun.services.ai.core.stream_events import (
|
||||
AgentStreamEvent,
|
||||
EventBus,
|
||||
@@ -21,7 +20,6 @@ from zhenxun.services.ai.core.stream_events import (
|
||||
ToolStreamChunkEvent,
|
||||
)
|
||||
from zhenxun.services.ai.guardrails import BaseGuardrail, GuardrailSource
|
||||
from zhenxun.services.ai.tools.core.tool import BaseTool
|
||||
from zhenxun.utils.pydantic_compat import model_dump, model_validator
|
||||
|
||||
|
||||
@@ -71,9 +69,6 @@ class HandoffPayload(BaseModel):
|
||||
"""随移交传递的上下文数据"""
|
||||
|
||||
|
||||
OutputDataT = TypeVar("OutputDataT", default=str)
|
||||
|
||||
|
||||
class AgentRunResult(BaseModel, Generic[OutputDataT]):
|
||||
"""Agent 单次无状态运行的结果"""
|
||||
|
||||
@@ -238,9 +233,7 @@ class AgentTask(BaseModel):
|
||||
"""强制要求返回的强类型结构 (Pydantic Model) 或
|
||||
OutputDefinition,为空则返回普通文本"""
|
||||
|
||||
tools: list[str | Callable | dict[str, Any] | BaseTool | ToolResolvable] | None = (
|
||||
None
|
||||
)
|
||||
tools: list[Any] | None = None
|
||||
"""针对此特定任务动态追加或覆盖的工具列表"""
|
||||
|
||||
guardrails: list[GuardrailSource] | None = None
|
||||
@@ -259,9 +252,74 @@ class AgentTask(BaseModel):
|
||||
return self
|
||||
|
||||
|
||||
class RunIntent(BaseModel):
|
||||
"""标准化且归一化的运行时意图载体"""
|
||||
|
||||
text: str = ""
|
||||
"""提取出的纯文本指令(用于路由、日志和并发控制判断)"""
|
||||
original_input: Any = None
|
||||
"""用户最原始的输入对象(如 UniMessage 等,用于多模态图像/音频数据提取)"""
|
||||
payload_to_render: Any = None
|
||||
"""将要被压入 MessageBuilder 渲染为大模型 Prompt 的实际载体"""
|
||||
task_obj: AgentTask | None = None
|
||||
"""如果是强类型任务契约,存储其原始对象引用"""
|
||||
response_model: type[BaseModel] | BaseOutputDefinition | None = None
|
||||
"""提取出的强类型输出约束"""
|
||||
extra_tools: list[Any] = Field(default_factory=list)
|
||||
"""提取出的附加工具集"""
|
||||
guardrails: list[BaseGuardrail] = Field(default_factory=list)
|
||||
"""提取出的安全护栏集"""
|
||||
|
||||
model_config = ConfigDict(arbitrary_types_allowed=True)
|
||||
|
||||
@classmethod
|
||||
def from_input(cls, prompt: Any) -> "RunIntent":
|
||||
task_obj = None
|
||||
text_content = ""
|
||||
extra_tools = []
|
||||
response_model = None
|
||||
guardrails = []
|
||||
payload_to_render = prompt
|
||||
|
||||
if isinstance(prompt, AgentTask):
|
||||
task_obj = prompt
|
||||
response_model = task_obj.response_model
|
||||
if task_obj.tools:
|
||||
extra_tools.extend(task_obj.tools)
|
||||
if hasattr(task_obj, "_parsed_guardrails"):
|
||||
guardrails.extend(task_obj._parsed_guardrails)
|
||||
|
||||
prompt_parts = [
|
||||
f"### 📋 [任务指令]\n{task_obj.description}",
|
||||
f"### 🎯 [预期产出要求]\n{task_obj.expected_output}",
|
||||
]
|
||||
text_content = "\n\n".join(prompt_parts)
|
||||
payload_to_render = text_content
|
||||
elif prompt is not None:
|
||||
text_content = getattr(prompt, "description", None) or (
|
||||
getattr(prompt, "extract_plain_text", lambda: str(prompt))()
|
||||
if prompt
|
||||
else str(prompt)
|
||||
)
|
||||
else:
|
||||
text_content = ""
|
||||
payload_to_render = None
|
||||
|
||||
return cls(
|
||||
text=text_content,
|
||||
original_input=prompt,
|
||||
payload_to_render=payload_to_render,
|
||||
task_obj=task_obj,
|
||||
response_model=response_model,
|
||||
extra_tools=extra_tools,
|
||||
guardrails=guardrails,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AgentRunResult",
|
||||
"AgentTask",
|
||||
"OutputDataT",
|
||||
"RunIntent",
|
||||
"StreamedRunResult",
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user