style: 项目重构

1.项目改名为kilostar(千星)
2.后端部分进行大规模重构
3.node功能进行大规模重新设计
This commit is contained in:
2026-05-11 15:29:16 +00:00
parent 2d8571dee3
commit ee9bbbf676
134 changed files with 2190 additions and 2503 deletions
@@ -0,0 +1,17 @@
# Copyright 2026 zhaoxi826
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .regulatory_node import regulatoryNode
__all__ = ["regulatoryNode"]
@@ -0,0 +1,213 @@
# Copyright 2026 zhaoxi826
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import ray
from typing import Union, overload
from kilostar.api.platform.event import kilostarEvent
from kilostar.adapter.model_adapter.agent_factory import AgentFactory
from kilostar.core.global_state_machine.global_state_machine import GlobalStateMachine
from kilostar.core.global_state_machine.model_provider import Provider
from kilostar.core.individual.regulatory_node.template import (
ForConsciousnessNode,
ForUser,
regulatoryNodeDeps,
TerminationMessage,
)
from pydantic_ai import RunContext, Agent
from kilostar.utils.ray_hook import ray_actor_hook
@ray.remote
class RegulatoryNode:
"""regulatoryNode 核心组件类。
这是一个系统执行节点类,作为多智能体架构中的独立处理单元。它能够接收工作流上下文,根据内置的大模型策略进行意图理解和自主决策,从而驱动特定阶段的任务闭环。"""
def __init__(self) -> None:
from kilostar.utils.logger import get_logger
self.logger = get_logger("regulatory_node")
self.agent: None | Agent = None
async def create_agent(
self,
global_state_machine: GlobalStateMachine,
provider_title: str,
model_id: str,
tools_list: list[str] = None,
) -> None:
"""
create_agent方法,将agent对象装配到regulatoryNode的属性内
该方法通过provider_title从global_state_machine中获取provider对象,然后从provider对象中取出供应商形象,装配为pydantic_ai的Agent实例,
并挂载到self.agent属性
Args:
global_state_machine: 全局状态机
provider_title: 供应商名
model_id: 模型id
Returns:
无返回
"""
system_prompt: str = (
"你叫kilostar,是一个多智能体AI助手系统中的【监控节点 (regulatory Node)】。\n"
"你是系统的'前台接待''大脑皮层',负责接收用户的初始请求或工作流的最终报告。\n"
"你的核心职责是进行【意图识别与路由】。请仔细阅读用户的请求:\n"
"1. 如果用户只是进行简单的问候、闲聊或查询非常基础的信息,请直接生成友好的回复,使用 ForUser 格式。\n"
"2. 如果用户提出的是复杂任务(如需要编写代码、多步骤规划、数据处理等),请务必将其判定为需要工作流处理的任务,"
" 并使用 ForConsciousnessNode 格式将其移交意识节点处理。\n"
"3. 如果你收到的是 TerminationMessage(代表工作流已完成并生成了报告),请将报告内容转化为友好的面向用户的回复,使用 ForUser 格式。\n"
"请保持冷静、专业,并严格遵循上述路由规则。"
)
output_type = Union[ForConsciousnessNode, ForUser]
from kilostar.utils.get_tool import load_tools_from_list
provider: Provider = await global_state_machine.get_provider.remote(
provider_title
)
agent_factory = AgentFactory()
callables = load_tools_from_list(tools_list)
self.agent = agent_factory.create_agent(
provider=provider,
model_id=model_id,
output_type=output_type,
system_prompt=system_prompt,
deps_type=regulatoryNodeDeps,
agent_name="regulatory_node",
tools=callables,
)
@self.agent.system_prompt
async def dynamic_prompt(ctx: RunContext[regulatoryNodeDeps]):
"""执行与 dynamic prompt 相关的核心业务流转操作。
该方法封装了具体的算法策略或状态控制逻辑,确保操作能够在事务上下文中被原子且一致地执行。
Args: ctx (RunContext[regulatoryNodeDeps]): 参与 dynamic prompt 逻辑运算或数据构建的上下文依赖对象。
Returns: : 经由当前业务模型加工处理后所输出的具体数据实例或领域模型对象。"""
prompt = system_prompt + "\n\n"
prompt += (
f"=== 当前上下文 ===\n"
f"- 平台 (Platform): {ctx.deps.platform}\n"
f"- 用户名 (User): {ctx.deps.user_name}\n"
f"- 当前时间 (Time): {ctx.deps.time}\n"
)
# 修改 system_prompt 变量
prompt += (
"\n\n注意:你必须调用且只能调用一个函数(工具)来输出结果。"
"如果你想直接回复用户,请调用 ForUser;"
"如果你想移交给工作流,请调用 ForConsciousnessNode。"
"严禁返回纯文本,必须使用工具格式!"
)
if ctx.deps.error_history:
prompt += (
f"\n=== 错误重试指示 ===\n"
f"警告:前一次尝试失败,错误信息如下:\n{ctx.deps.error_history}\n"
f"请务必修正该错误并按照要求的 Pydantic 格式输出。"
)
return prompt
###工作函数
async def working(self, payload: Union[kilostarEvent, TerminationMessage]) -> str:
"""
working方法,是节点唯一的调用方法,对于_run函数的结果进行判断并实现最终回复
Args:
payload: 消息载荷,包含所有信息
Returns:
str,监控节点对于用户的回复
"""
try:
result = await self._run(payload)
if isinstance(result, ForConsciousnessNode):
self.logger.info("regulatoryNode: 任务已分配给工作流引擎处理")
if isinstance(payload, kilostarEvent):
try:
global_workflow_manager = ray_actor_hook(
"global_workflow_manager"
).global_workflow_manager
await global_workflow_manager.add_event.remote(payload)
workflow_running_engine = ray_actor_hook(
"workflow_running_engine"
).workflow_running_engine
await workflow_running_engine.put_event.remote(payload)
except Exception as e:
self.logger.error(
f"regulatoryNode: 无法将事件放入 WorkflowRunningEngine: {e}"
)
return "抱歉,任务提交失败,系统内部错误。"
return f"任务已创建,准备创建工作流。原因:{result.reasoning}"
elif isinstance(result, ForUser):
self.logger.info("regulatoryNode: 直接向用户返回简单回复。")
return result.context
else:
self.logger.error(f"regulatoryNode: 未知响应类型: {type(result)}")
return "抱歉,系统内部遇到未知错误,无法正确处理您的请求。"
except Exception:
self.logger.exception("regulatoryNode在处理请求时发生未捕获的严重错误")
return "抱歉,监控节点处理请求时发生严重错误,请联系管理员。"
@overload
async def _run(self, payload: kilostarEvent) -> Union[ForConsciousnessNode, ForUser]:
"""
_run方法
Args:
payload: kilostarEvent的实例,是用户输入时对于消息的封装
Returns:
ForUser对象,监控节点对于用户进行的简单回答
ForConsciousnessNode对象,监控节点将用户的请求判断为复杂任务,将kilostarEvent传递给意识节点
"""
...
@overload
async def _run(self, payload: TerminationMessage) -> ForUser:
"""
_run方法
Args:
payload: Termination的实例,是工作流结束后到达监控节点的最后结果
Returns:
ForUser对象,工作流结束后给用户的返回
"""
...
async def _run(
self, payload: Union[kilostarEvent, TerminationMessage]
) -> Union[ForConsciousnessNode, ForUser]:
"""
_run方法,将payload转化为对llm发送的消息并发送
Args:
payload: 消息载荷
Returns:
ForConsciousnessNode对象,对意识节点发送的消息
ForUser对象,对用户发送到消息
"""
platform = payload.platform
user_name = payload.user_name
message = payload.message
time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
try:
deps = regulatoryNodeDeps(
platform=platform, user_name=user_name, time=time_str
)
self.logger.debug("regulatoryNode 开始生成 (启用原生 Pydantic-AI 重试)")
prompt_message = message
if isinstance(payload, TerminationMessage):
prompt_message = f"【工作流执行结束报告】\n请将以下技术报告转化为对用户的友好回复:\n{message}"
self.agent.retries = 3
result = await self.agent.run(prompt_message, deps=deps)
return result.output
except Exception as e:
self.logger.exception(f"regulatoryNode 模型生成或解析最终失败: {str(e)}")
return ForUser(context="系统当前负载过高或遇到复杂内部错误,请稍后再试。")
@@ -0,0 +1,61 @@
# Copyright 2026 zhaoxi826
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pydantic import Field
from kilostar.utils.agent_model import ResponseModel, DepsModel
from pydantic import BaseModel
class regulatoryNodeResponse(ResponseModel):
"""regulatoryNodeResponse 核心组件类。
这是一个系统执行节点类,作为多智能体架构中的独立处理单元。它能够接收工作流上下文,根据内置的大模型策略进行意图理解和自主决策,从而驱动特定阶段的任务闭环。"""
pass
class ForUser(regulatoryNodeResponse):
"""ForUser 核心组件类。
这是一个领域数据模型或功能封装类,承载了 ForUser 相关的内聚属性定义与状态维护。它的存在隔离了局部的业务复杂性,并对外提供了类型安全的访问接口。"""
context: str = Field(
...,
description="对用户的回复,应当使用和蔼的语气进行回复。用于直接解答简单问题或返回最终报告。",
)
class ForConsciousnessNode(regulatoryNodeResponse):
"""ForConsciousnessNode 核心组件类。
这是一个系统执行节点类,作为多智能体架构中的独立处理单元。它能够接收工作流上下文,根据内置的大模型策略进行意图理解和自主决策,从而驱动特定阶段的任务闭环。"""
reasoning: str = Field(..., description="选择将任务移交意识节点的简短原因。")
class TerminationMessage(BaseModel):
"""TerminationMessage 核心组件类。
这是一个领域数据模型或功能封装类,承载了 TerminationMessage 相关的内聚属性定义与状态维护。它的存在隔离了局部的业务复杂性,并对外提供了类型安全的访问接口。"""
platform: str
user_name: str
message: str
class regulatoryNodeDeps(DepsModel):
"""regulatoryNodeDeps 核心组件类。
这是一个系统执行节点类,作为多智能体架构中的独立处理单元。它能够接收工作流上下文,根据内置的大模型策略进行意图理解和自主决策,从而驱动特定阶段的任务闭环。"""
platform: str
user_name: str
time: str
retry_count: int = 0
error_history: str = ""