2026-03-16 16:10:39 +08:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
from dataclasses import dataclass
|
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
|
from typing import TYPE_CHECKING, Any
|
2026-03-16 18:32:09 +08:00
|
|
|
from uuid import UUID
|
2026-03-16 16:10:39 +08:00
|
|
|
|
|
|
|
|
from ag_ui.core.types import RunAgentInput
|
|
|
|
|
from agentscope.formatter import OpenAIChatFormatter
|
|
|
|
|
from agentscope.memory import InMemoryMemory
|
|
|
|
|
from agentscope.message import Msg
|
|
|
|
|
from agentscope.model import OpenAIChatModel
|
2026-03-19 18:42:35 +08:00
|
|
|
from core.agentscope.prompts.agent_prompt import build_worker_contract_prompt
|
2026-03-16 16:10:39 +08:00
|
|
|
from core.agentscope.prompts.system_prompt import build_system_prompt
|
2026-03-19 18:42:35 +08:00
|
|
|
from core.agentscope.runtime.pipeline_registry import build_default_pipeline_spec
|
2026-03-16 18:32:09 +08:00
|
|
|
from core.agentscope.runtime.json_react_agent import JsonReActAgent
|
|
|
|
|
from core.agentscope.runtime.model_tracking import TrackingChatModel
|
|
|
|
|
from core.agentscope.runtime.stage_emitter import PipelineStageEmitter
|
2026-03-19 00:52:05 +08:00
|
|
|
from core.agentscope.runtime.tool_selection_registry import TOOL_SELECTION_REGISTRY
|
2026-03-16 18:32:09 +08:00
|
|
|
from core.agentscope.tools.toolkit import build_stage_toolkit
|
2026-03-19 18:42:35 +08:00
|
|
|
from core.agentscope.utils import (
|
|
|
|
|
finalize_json_response,
|
|
|
|
|
patch_agentscope_json_repair_compat,
|
|
|
|
|
)
|
2026-03-17 18:05:49 +08:00
|
|
|
from core.config.settings import config
|
2026-03-16 16:10:39 +08:00
|
|
|
from core.db.session import AsyncSessionLocal
|
|
|
|
|
from models.llm import Llm
|
2026-03-17 18:05:49 +08:00
|
|
|
from models.llm_factory import LlmFactory
|
2026-03-16 16:10:39 +08:00
|
|
|
from models.system_agents import SystemAgents
|
2026-03-17 00:13:41 +08:00
|
|
|
from schemas.agent.forwarded_props import (
|
|
|
|
|
ClientTimeContext,
|
|
|
|
|
parse_forwarded_props_client_time,
|
|
|
|
|
)
|
2026-03-19 18:42:35 +08:00
|
|
|
from schemas.automation.config import AutomationJobConfig
|
|
|
|
|
from schemas.agent.runtime_models import (
|
|
|
|
|
AgentOutput,
|
|
|
|
|
RouterAgentOutput,
|
|
|
|
|
WorkerAgentOutputLite,
|
|
|
|
|
resolve_worker_output_model,
|
|
|
|
|
)
|
|
|
|
|
from schemas.agent.system_agent import (
|
|
|
|
|
AgentType,
|
|
|
|
|
ContextMessagesConfig,
|
|
|
|
|
ContextBuildStrategy,
|
|
|
|
|
SystemAgentLLMConfig,
|
|
|
|
|
)
|
2026-03-16 16:10:39 +08:00
|
|
|
from schemas.user import UserContext
|
|
|
|
|
from services.litellm.service import LiteLLMService
|
|
|
|
|
from sqlalchemy import select
|
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
|
from core.agentscope.runtime.orchestrator import PipelineLike
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
|
|
|
class SystemAgentRuntimeConfig:
|
|
|
|
|
agent_type: AgentType
|
|
|
|
|
model_code: str
|
2026-03-17 18:05:49 +08:00
|
|
|
api_base_url: str
|
|
|
|
|
api_key: str
|
2026-03-16 16:10:39 +08:00
|
|
|
llm_config: SystemAgentLLMConfig
|
2026-03-19 18:42:35 +08:00
|
|
|
extra_context: str | None = None
|
2026-03-16 16:10:39 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
|
|
|
class StageExecutionResult:
|
|
|
|
|
message: Msg
|
|
|
|
|
payload: dict[str, Any]
|
|
|
|
|
response_metadata: dict[str, Any]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class AgentScopeRunner:
|
|
|
|
|
def __init__(self, *, litellm_service: LiteLLMService | None = None) -> None:
|
2026-03-16 18:32:09 +08:00
|
|
|
patch_agentscope_json_repair_compat()
|
2026-03-17 18:05:49 +08:00
|
|
|
self._litellm_service: LiteLLMService = litellm_service or LiteLLMService()
|
2026-03-16 16:10:39 +08:00
|
|
|
|
|
|
|
|
async def execute(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
user_context: UserContext,
|
|
|
|
|
context_messages: list[Msg],
|
|
|
|
|
pipeline: PipelineLike,
|
|
|
|
|
run_input: RunAgentInput,
|
2026-03-19 00:52:05 +08:00
|
|
|
system_agent_mode: str,
|
2026-03-19 18:42:35 +08:00
|
|
|
memory_job_config: AutomationJobConfig | None = None,
|
2026-03-16 16:10:39 +08:00
|
|
|
) -> dict[str, Any]:
|
|
|
|
|
owner_id = UUID(user_context.id)
|
2026-03-17 00:13:41 +08:00
|
|
|
runtime_client_time = self._resolve_runtime_client_time(run_input=run_input)
|
2026-03-19 18:42:35 +08:00
|
|
|
pipeline_spec = build_default_pipeline_spec(mode=system_agent_mode)
|
|
|
|
|
stage_agent_types = [
|
|
|
|
|
self._parse_agent_type(stage_name=stage.stage_name)
|
|
|
|
|
for stage in pipeline_spec.stages
|
|
|
|
|
]
|
2026-03-16 16:10:39 +08:00
|
|
|
|
|
|
|
|
async with AsyncSessionLocal() as session:
|
2026-03-19 18:42:35 +08:00
|
|
|
if stage_agent_types == [AgentType.ROUTER, AgentType.WORKER]:
|
|
|
|
|
router_config = await self._load_stage_config(
|
|
|
|
|
session=session,
|
|
|
|
|
agent_type=AgentType.ROUTER,
|
|
|
|
|
)
|
|
|
|
|
worker_config = await self._load_stage_config(
|
|
|
|
|
session=session,
|
|
|
|
|
agent_type=AgentType.WORKER,
|
|
|
|
|
)
|
|
|
|
|
worker_toolkit = self._build_stage_toolkit(
|
|
|
|
|
session=session,
|
|
|
|
|
owner_id=owner_id,
|
|
|
|
|
stage_config=worker_config,
|
|
|
|
|
)
|
|
|
|
|
router_output = await self._execute_router_step(
|
|
|
|
|
pipeline=pipeline,
|
|
|
|
|
run_input=run_input,
|
|
|
|
|
user_context=user_context,
|
|
|
|
|
context_messages=context_messages,
|
|
|
|
|
stage_config=router_config,
|
|
|
|
|
runtime_client_time=runtime_client_time,
|
|
|
|
|
)
|
|
|
|
|
worker_output = await self._execute_worker_step(
|
|
|
|
|
pipeline=pipeline,
|
|
|
|
|
run_input=run_input,
|
|
|
|
|
user_context=user_context,
|
|
|
|
|
router_output=router_output,
|
|
|
|
|
toolkit=worker_toolkit,
|
|
|
|
|
stage_config=worker_config,
|
|
|
|
|
runtime_client_time=runtime_client_time,
|
|
|
|
|
)
|
|
|
|
|
return {
|
|
|
|
|
"router": router_output.model_dump(mode="json", exclude_none=True),
|
|
|
|
|
"worker": worker_output.model_dump(mode="json", exclude_none=True),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if stage_agent_types[0] == AgentType.MEMORY:
|
|
|
|
|
if memory_job_config is None:
|
|
|
|
|
raise RuntimeError("memory job config is required")
|
|
|
|
|
stage_config = await self._build_memory_stage_config(
|
|
|
|
|
session=session,
|
|
|
|
|
memory_job_config=memory_job_config,
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
stage_config = await self._load_stage_config(
|
|
|
|
|
session=session,
|
|
|
|
|
agent_type=stage_agent_types[0],
|
|
|
|
|
)
|
2026-03-19 00:52:05 +08:00
|
|
|
stage_toolkit = self._build_stage_toolkit(
|
2026-03-16 18:32:09 +08:00
|
|
|
session=session,
|
2026-03-19 00:52:05 +08:00
|
|
|
owner_id=owner_id,
|
|
|
|
|
stage_config=stage_config,
|
2026-03-16 16:10:39 +08:00
|
|
|
)
|
2026-03-19 18:42:35 +08:00
|
|
|
stage_output = await self._execute_single_stage_step(
|
2026-03-16 16:10:39 +08:00
|
|
|
pipeline=pipeline,
|
|
|
|
|
run_input=run_input,
|
|
|
|
|
user_context=user_context,
|
2026-03-19 18:42:35 +08:00
|
|
|
input_messages=context_messages,
|
2026-03-19 00:52:05 +08:00
|
|
|
toolkit=stage_toolkit,
|
|
|
|
|
stage_config=stage_config,
|
2026-03-17 00:13:41 +08:00
|
|
|
runtime_client_time=runtime_client_time,
|
2026-03-16 16:10:39 +08:00
|
|
|
)
|
|
|
|
|
return {
|
2026-03-19 18:42:35 +08:00
|
|
|
stage_config.agent_type.value: stage_output.model_dump(
|
|
|
|
|
mode="json", exclude_none=True
|
|
|
|
|
),
|
2026-03-16 16:10:39 +08:00
|
|
|
}
|
|
|
|
|
|
2026-03-19 00:52:05 +08:00
|
|
|
def _build_stage_toolkit(
|
2026-03-16 16:10:39 +08:00
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
session: AsyncSession,
|
|
|
|
|
owner_id: UUID,
|
2026-03-19 00:52:05 +08:00
|
|
|
stage_config: SystemAgentRuntimeConfig,
|
2026-03-16 18:32:09 +08:00
|
|
|
) -> Any:
|
2026-03-19 00:52:05 +08:00
|
|
|
enabled_tool_names = TOOL_SELECTION_REGISTRY.resolve(stage_config=stage_config)
|
2026-03-16 18:32:09 +08:00
|
|
|
return build_stage_toolkit(
|
2026-03-19 00:52:05 +08:00
|
|
|
agent_type=stage_config.agent_type,
|
2026-03-16 18:32:09 +08:00
|
|
|
session=session,
|
|
|
|
|
owner_id=owner_id,
|
2026-03-19 00:52:05 +08:00
|
|
|
enabled_tool_names=enabled_tool_names,
|
2026-03-16 16:10:39 +08:00
|
|
|
)
|
|
|
|
|
|
2026-03-19 00:52:05 +08:00
|
|
|
@staticmethod
|
2026-03-19 18:42:35 +08:00
|
|
|
def _parse_agent_type(*, stage_name: str) -> AgentType:
|
|
|
|
|
normalized = stage_name.strip().lower()
|
|
|
|
|
if normalized == AgentType.ROUTER.value:
|
|
|
|
|
return AgentType.ROUTER
|
|
|
|
|
if normalized == AgentType.WORKER.value:
|
|
|
|
|
return AgentType.WORKER
|
|
|
|
|
if normalized == AgentType.MEMORY.value:
|
2026-03-19 00:52:05 +08:00
|
|
|
return AgentType.MEMORY
|
2026-03-19 18:42:35 +08:00
|
|
|
raise ValueError(f"unsupported stage name: {stage_name}")
|
2026-03-16 18:32:09 +08:00
|
|
|
|
2026-03-19 00:52:05 +08:00
|
|
|
async def _load_stage_config(
|
2026-03-16 18:32:09 +08:00
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
session: AsyncSession,
|
2026-03-19 00:52:05 +08:00
|
|
|
agent_type: AgentType,
|
|
|
|
|
) -> SystemAgentRuntimeConfig:
|
|
|
|
|
return await self._load_system_agent_config(
|
2026-03-16 18:32:09 +08:00
|
|
|
session=session,
|
2026-03-19 00:52:05 +08:00
|
|
|
agent_type=agent_type,
|
2026-03-16 18:32:09 +08:00
|
|
|
)
|
|
|
|
|
|
2026-03-19 18:42:35 +08:00
|
|
|
async def _execute_router_step(
|
2026-03-16 18:32:09 +08:00
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
pipeline: PipelineLike,
|
|
|
|
|
run_input: RunAgentInput,
|
|
|
|
|
user_context: UserContext,
|
2026-03-19 00:52:05 +08:00
|
|
|
context_messages: list[Msg],
|
2026-03-19 18:42:35 +08:00
|
|
|
stage_config: SystemAgentRuntimeConfig,
|
|
|
|
|
runtime_client_time: ClientTimeContext | None,
|
|
|
|
|
) -> RouterAgentOutput:
|
|
|
|
|
await self._emit_step_event(
|
|
|
|
|
pipeline=pipeline,
|
|
|
|
|
run_input=run_input,
|
|
|
|
|
step_name=AgentType.ROUTER.value,
|
|
|
|
|
event_type="STEP_STARTED",
|
|
|
|
|
)
|
|
|
|
|
router_result = await self._run_router_stage(
|
|
|
|
|
user_context=user_context,
|
|
|
|
|
context_messages=context_messages,
|
|
|
|
|
stage_config=stage_config,
|
|
|
|
|
runtime_client_time=runtime_client_time,
|
|
|
|
|
)
|
|
|
|
|
router_output = RouterAgentOutput.model_validate(router_result.payload)
|
|
|
|
|
await self._emit_step_event(
|
|
|
|
|
pipeline=pipeline,
|
|
|
|
|
run_input=run_input,
|
|
|
|
|
step_name=AgentType.ROUTER.value,
|
|
|
|
|
event_type="STEP_FINISHED",
|
|
|
|
|
)
|
|
|
|
|
return router_output
|
|
|
|
|
|
|
|
|
|
async def _execute_worker_step(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
pipeline: PipelineLike,
|
|
|
|
|
run_input: RunAgentInput,
|
|
|
|
|
user_context: UserContext,
|
|
|
|
|
router_output: RouterAgentOutput,
|
2026-03-16 18:32:09 +08:00
|
|
|
toolkit: Any,
|
|
|
|
|
stage_config: SystemAgentRuntimeConfig,
|
2026-03-17 00:13:41 +08:00
|
|
|
runtime_client_time: ClientTimeContext | None,
|
2026-03-19 18:42:35 +08:00
|
|
|
) -> WorkerAgentOutputLite:
|
|
|
|
|
worker_output_model = resolve_worker_output_model(router_output.ui.ui_mode)
|
2026-03-16 18:32:09 +08:00
|
|
|
await self._emit_step_event(
|
|
|
|
|
pipeline=pipeline,
|
|
|
|
|
run_input=run_input,
|
2026-03-19 18:42:35 +08:00
|
|
|
step_name=AgentType.WORKER.value,
|
2026-03-16 18:32:09 +08:00
|
|
|
event_type="STEP_STARTED",
|
|
|
|
|
)
|
|
|
|
|
worker_result = await self._run_worker_stage(
|
|
|
|
|
user_context=user_context,
|
2026-03-19 18:42:35 +08:00
|
|
|
input_messages=self._build_worker_input_messages(
|
|
|
|
|
router_output=router_output
|
|
|
|
|
),
|
2026-03-16 18:32:09 +08:00
|
|
|
toolkit=toolkit,
|
|
|
|
|
run_input=run_input,
|
|
|
|
|
stage_config=stage_config,
|
|
|
|
|
worker_output_model=worker_output_model,
|
|
|
|
|
pipeline=pipeline,
|
2026-03-17 00:13:41 +08:00
|
|
|
runtime_client_time=runtime_client_time,
|
2026-03-16 18:32:09 +08:00
|
|
|
)
|
|
|
|
|
worker_output = worker_output_model.model_validate(worker_result.payload)
|
|
|
|
|
await self._emit_step_event(
|
|
|
|
|
pipeline=pipeline,
|
|
|
|
|
run_input=run_input,
|
2026-03-19 18:42:35 +08:00
|
|
|
step_name=AgentType.WORKER.value,
|
2026-03-16 18:32:09 +08:00
|
|
|
event_type="STEP_FINISHED",
|
|
|
|
|
)
|
|
|
|
|
return worker_output
|
2026-03-16 16:10:39 +08:00
|
|
|
|
2026-03-19 18:42:35 +08:00
|
|
|
async def _execute_single_stage_step(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
pipeline: PipelineLike,
|
|
|
|
|
run_input: RunAgentInput,
|
|
|
|
|
user_context: UserContext,
|
|
|
|
|
input_messages: list[Msg],
|
|
|
|
|
toolkit: Any,
|
|
|
|
|
stage_config: SystemAgentRuntimeConfig,
|
|
|
|
|
runtime_client_time: ClientTimeContext | None,
|
|
|
|
|
) -> AgentOutput:
|
|
|
|
|
step_name = stage_config.agent_type.value
|
|
|
|
|
await self._emit_step_event(
|
|
|
|
|
pipeline=pipeline,
|
|
|
|
|
run_input=run_input,
|
|
|
|
|
step_name=step_name,
|
|
|
|
|
event_type="STEP_STARTED",
|
|
|
|
|
)
|
|
|
|
|
stage_result = await self._run_worker_stage(
|
|
|
|
|
user_context=user_context,
|
|
|
|
|
input_messages=input_messages,
|
|
|
|
|
toolkit=toolkit,
|
|
|
|
|
run_input=run_input,
|
|
|
|
|
stage_config=stage_config,
|
|
|
|
|
worker_output_model=AgentOutput,
|
|
|
|
|
pipeline=pipeline,
|
|
|
|
|
runtime_client_time=runtime_client_time,
|
|
|
|
|
)
|
|
|
|
|
stage_output = AgentOutput.model_validate(stage_result.payload)
|
|
|
|
|
await self._emit_step_event(
|
|
|
|
|
pipeline=pipeline,
|
|
|
|
|
run_input=run_input,
|
|
|
|
|
step_name=step_name,
|
|
|
|
|
event_type="STEP_FINISHED",
|
|
|
|
|
)
|
|
|
|
|
return stage_output
|
|
|
|
|
|
2026-03-16 16:10:39 +08:00
|
|
|
async def _load_system_agent_config(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
session: AsyncSession,
|
|
|
|
|
agent_type: AgentType,
|
|
|
|
|
) -> SystemAgentRuntimeConfig:
|
|
|
|
|
stmt = (
|
2026-03-17 18:05:49 +08:00
|
|
|
select(SystemAgents, Llm, LlmFactory)
|
2026-03-16 16:10:39 +08:00
|
|
|
.join(Llm, SystemAgents.llm_id == Llm.id)
|
2026-03-17 18:05:49 +08:00
|
|
|
.join(LlmFactory, Llm.factory_id == LlmFactory.id)
|
2026-03-16 16:10:39 +08:00
|
|
|
.where(SystemAgents.agent_type == agent_type.value)
|
|
|
|
|
)
|
|
|
|
|
row = (await session.execute(stmt)).one_or_none()
|
|
|
|
|
if row is None:
|
|
|
|
|
raise RuntimeError(f"system agent config not found: {agent_type.value}")
|
2026-03-17 18:05:49 +08:00
|
|
|
system_agent, llm, factory = row
|
2026-03-16 16:10:39 +08:00
|
|
|
status = str(system_agent.status).strip().lower()
|
|
|
|
|
if status != "active":
|
|
|
|
|
raise RuntimeError(f"system agent is not active: {agent_type.value}")
|
|
|
|
|
return SystemAgentRuntimeConfig(
|
|
|
|
|
agent_type=agent_type,
|
|
|
|
|
model_code=llm.model_code,
|
2026-03-17 18:05:49 +08:00
|
|
|
api_base_url=factory.request_url,
|
|
|
|
|
api_key=self._resolve_provider_api_key(factory_name=factory.name),
|
2026-03-16 16:10:39 +08:00
|
|
|
llm_config=SystemAgentLLMConfig.model_validate(system_agent.config or {}),
|
2026-03-19 18:42:35 +08:00
|
|
|
extra_context=None,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
async def _build_memory_stage_config(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
session: AsyncSession,
|
|
|
|
|
memory_job_config: AutomationJobConfig,
|
|
|
|
|
) -> SystemAgentRuntimeConfig:
|
|
|
|
|
stmt = (
|
|
|
|
|
select(Llm, LlmFactory)
|
|
|
|
|
.join(LlmFactory, Llm.factory_id == LlmFactory.id)
|
|
|
|
|
.where(Llm.model_code == memory_job_config.model_code)
|
|
|
|
|
)
|
|
|
|
|
row = (await session.execute(stmt)).one_or_none()
|
|
|
|
|
if row is None:
|
|
|
|
|
raise RuntimeError(
|
|
|
|
|
f"memory model not found: {memory_job_config.model_code}"
|
|
|
|
|
)
|
|
|
|
|
llm, factory = row
|
|
|
|
|
llm_config = SystemAgentLLMConfig(
|
|
|
|
|
temperature=0.7,
|
|
|
|
|
max_tokens=None,
|
|
|
|
|
timeout_seconds=30,
|
|
|
|
|
visibility_consumer_bit=18,
|
|
|
|
|
context_messages=ContextMessagesConfig(
|
|
|
|
|
mode=(
|
|
|
|
|
ContextBuildStrategy.DAY
|
|
|
|
|
if memory_job_config.context.window_mode.value == "day"
|
|
|
|
|
else ContextBuildStrategy.NUMBER
|
|
|
|
|
),
|
|
|
|
|
count=memory_job_config.context.window_count,
|
|
|
|
|
),
|
|
|
|
|
enabled_tools=memory_job_config.enabled_tools,
|
|
|
|
|
)
|
|
|
|
|
return SystemAgentRuntimeConfig(
|
|
|
|
|
agent_type=AgentType.MEMORY,
|
|
|
|
|
model_code=llm.model_code,
|
|
|
|
|
api_base_url=factory.request_url,
|
|
|
|
|
api_key=self._resolve_provider_api_key(factory_name=factory.name),
|
|
|
|
|
llm_config=llm_config,
|
|
|
|
|
extra_context=(
|
|
|
|
|
f"[Memory Input Template]\n{memory_job_config.input_template.strip()}"
|
|
|
|
|
),
|
2026-03-16 16:10:39 +08:00
|
|
|
)
|
|
|
|
|
|
2026-03-17 18:05:49 +08:00
|
|
|
@staticmethod
|
|
|
|
|
def _resolve_provider_api_key(*, factory_name: str) -> str:
|
|
|
|
|
normalized_factory_name = factory_name.strip().upper()
|
|
|
|
|
if normalized_factory_name == "VOLCENGINE":
|
|
|
|
|
normalized_factory_name = "ARK"
|
|
|
|
|
|
|
|
|
|
provider_keys = {
|
|
|
|
|
str(key).strip().upper(): str(value).strip()
|
|
|
|
|
for key, value in config.llm.provider_keys.items()
|
|
|
|
|
if str(value).strip()
|
|
|
|
|
}
|
|
|
|
|
api_key = provider_keys.get(normalized_factory_name, "")
|
|
|
|
|
if not api_key:
|
|
|
|
|
raise RuntimeError(f"provider api key missing for factory: {factory_name}")
|
|
|
|
|
return api_key
|
|
|
|
|
|
2026-03-19 18:42:35 +08:00
|
|
|
async def _run_router_stage(
|
2026-03-16 16:10:39 +08:00
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
user_context: UserContext,
|
2026-03-19 00:52:05 +08:00
|
|
|
context_messages: list[Msg],
|
2026-03-19 18:42:35 +08:00
|
|
|
stage_config: SystemAgentRuntimeConfig,
|
|
|
|
|
runtime_client_time: ClientTimeContext | None,
|
|
|
|
|
) -> StageExecutionResult:
|
|
|
|
|
tracking_model = self._build_model(stage_config=stage_config)
|
|
|
|
|
response, payload = await finalize_json_response(
|
|
|
|
|
model=tracking_model,
|
|
|
|
|
formatter=OpenAIChatFormatter(),
|
|
|
|
|
base_messages=[
|
|
|
|
|
Msg(
|
|
|
|
|
"system",
|
|
|
|
|
build_system_prompt(
|
|
|
|
|
agent_type=AgentType.ROUTER,
|
|
|
|
|
llm_config=stage_config.llm_config,
|
|
|
|
|
user_context=user_context,
|
|
|
|
|
now_utc=datetime.now(timezone.utc),
|
|
|
|
|
runtime_client_time=runtime_client_time,
|
|
|
|
|
tools=None,
|
|
|
|
|
),
|
|
|
|
|
"system",
|
|
|
|
|
),
|
|
|
|
|
*context_messages,
|
|
|
|
|
],
|
|
|
|
|
output_model=RouterAgentOutput,
|
|
|
|
|
retries=0,
|
|
|
|
|
)
|
|
|
|
|
response_msg = Msg(
|
|
|
|
|
name="router",
|
|
|
|
|
role="assistant",
|
|
|
|
|
content=list(getattr(response, "content", [])),
|
|
|
|
|
metadata=payload,
|
|
|
|
|
)
|
|
|
|
|
return StageExecutionResult(
|
|
|
|
|
message=response_msg,
|
|
|
|
|
payload=payload,
|
|
|
|
|
response_metadata=self._litellm_service.build_usage_metadata(
|
|
|
|
|
model=stage_config.model_code,
|
|
|
|
|
usage_summary=tracking_model.usage_summary(),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
async def _run_worker_stage(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
user_context: UserContext,
|
|
|
|
|
input_messages: list[Msg],
|
2026-03-16 16:10:39 +08:00
|
|
|
toolkit: Any,
|
|
|
|
|
run_input: RunAgentInput,
|
|
|
|
|
stage_config: SystemAgentRuntimeConfig,
|
2026-03-19 18:42:35 +08:00
|
|
|
worker_output_model: type[WorkerAgentOutputLite],
|
2026-03-16 16:10:39 +08:00
|
|
|
pipeline: PipelineLike,
|
2026-03-17 00:13:41 +08:00
|
|
|
runtime_client_time: ClientTimeContext | None,
|
2026-03-16 16:10:39 +08:00
|
|
|
) -> StageExecutionResult:
|
|
|
|
|
tracking_model = self._build_model(stage_config=stage_config)
|
2026-03-16 18:32:09 +08:00
|
|
|
emitter = PipelineStageEmitter(
|
2026-03-16 16:10:39 +08:00
|
|
|
pipeline=pipeline,
|
|
|
|
|
session_id=run_input.thread_id,
|
|
|
|
|
run_id=run_input.run_id,
|
2026-03-19 00:52:05 +08:00
|
|
|
stage=stage_config.agent_type.value,
|
2026-03-16 16:10:39 +08:00
|
|
|
emit_text_events=True,
|
|
|
|
|
emit_tool_events=True,
|
|
|
|
|
)
|
|
|
|
|
agent = self._build_agent(
|
2026-03-19 00:52:05 +08:00
|
|
|
agent_name=stage_config.agent_type.value,
|
2026-03-16 16:10:39 +08:00
|
|
|
system_prompt=build_system_prompt(
|
2026-03-19 00:52:05 +08:00
|
|
|
agent_type=stage_config.agent_type,
|
|
|
|
|
llm_config=stage_config.llm_config,
|
2026-03-16 16:10:39 +08:00
|
|
|
user_context=user_context,
|
|
|
|
|
now_utc=datetime.now(timezone.utc),
|
2026-03-17 00:13:41 +08:00
|
|
|
runtime_client_time=runtime_client_time,
|
2026-03-19 18:42:35 +08:00
|
|
|
extra_context=stage_config.extra_context,
|
2026-03-16 18:32:09 +08:00
|
|
|
tools=None,
|
2026-03-16 16:10:39 +08:00
|
|
|
),
|
|
|
|
|
toolkit=toolkit,
|
|
|
|
|
model=tracking_model,
|
|
|
|
|
emitter=emitter,
|
|
|
|
|
)
|
|
|
|
|
response_msg = await agent.reply_json(
|
2026-03-19 18:42:35 +08:00
|
|
|
input_messages, output_model=worker_output_model
|
2026-03-16 16:10:39 +08:00
|
|
|
)
|
|
|
|
|
worker_payload = worker_output_model.model_validate(response_msg.metadata or {})
|
|
|
|
|
response_metadata = self._litellm_service.build_usage_metadata(
|
|
|
|
|
model=stage_config.model_code,
|
|
|
|
|
usage_summary=tracking_model.usage_summary(),
|
|
|
|
|
)
|
|
|
|
|
await emitter.emit_final_text_end(
|
|
|
|
|
worker_output=worker_payload.model_dump(mode="json", exclude_none=True),
|
|
|
|
|
response_metadata=response_metadata,
|
|
|
|
|
)
|
|
|
|
|
return StageExecutionResult(
|
|
|
|
|
message=response_msg,
|
|
|
|
|
payload=worker_payload.model_dump(mode="json", exclude_none=True),
|
|
|
|
|
response_metadata=response_metadata,
|
|
|
|
|
)
|
|
|
|
|
|
2026-03-19 18:42:35 +08:00
|
|
|
def _build_worker_input_messages(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
router_output: RouterAgentOutput,
|
|
|
|
|
) -> list[Msg]:
|
|
|
|
|
return [
|
|
|
|
|
Msg(
|
|
|
|
|
name=AgentType.ROUTER.value,
|
|
|
|
|
role="user",
|
|
|
|
|
content=build_worker_contract_prompt(router_output=router_output),
|
|
|
|
|
)
|
|
|
|
|
]
|
|
|
|
|
|
2026-03-16 16:10:39 +08:00
|
|
|
def _build_model(
|
|
|
|
|
self, *, stage_config: SystemAgentRuntimeConfig
|
2026-03-16 18:32:09 +08:00
|
|
|
) -> TrackingChatModel:
|
2026-03-16 16:10:39 +08:00
|
|
|
generate_kwargs: dict[str, Any] = {
|
|
|
|
|
"temperature": stage_config.llm_config.temperature,
|
|
|
|
|
"max_tokens": stage_config.llm_config.max_tokens,
|
|
|
|
|
"timeout": stage_config.llm_config.timeout_seconds,
|
2026-03-19 18:42:35 +08:00
|
|
|
"extra_body": {"enable_thinking": False},
|
2026-03-16 16:10:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
model = OpenAIChatModel(
|
|
|
|
|
model_name=stage_config.model_code,
|
2026-03-17 18:05:49 +08:00
|
|
|
api_key=stage_config.api_key,
|
2026-03-16 16:10:39 +08:00
|
|
|
stream=False,
|
2026-03-17 18:05:49 +08:00
|
|
|
client_kwargs={"base_url": stage_config.api_base_url},
|
2026-03-16 16:10:39 +08:00
|
|
|
generate_kwargs=generate_kwargs,
|
|
|
|
|
)
|
2026-03-16 18:32:09 +08:00
|
|
|
return TrackingChatModel(model)
|
2026-03-16 16:10:39 +08:00
|
|
|
|
|
|
|
|
def _build_agent(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
agent_name: str,
|
|
|
|
|
system_prompt: str,
|
|
|
|
|
toolkit: Any,
|
2026-03-16 18:32:09 +08:00
|
|
|
model: TrackingChatModel,
|
|
|
|
|
emitter: PipelineStageEmitter | None = None,
|
2026-03-16 16:10:39 +08:00
|
|
|
) -> JsonReActAgent:
|
|
|
|
|
return JsonReActAgent(
|
|
|
|
|
name=agent_name,
|
|
|
|
|
sys_prompt=system_prompt,
|
|
|
|
|
model=model,
|
|
|
|
|
formatter=OpenAIChatFormatter(),
|
|
|
|
|
toolkit=toolkit,
|
|
|
|
|
memory=InMemoryMemory(),
|
|
|
|
|
emitter=emitter,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
async def _emit_step_event(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
pipeline: PipelineLike,
|
|
|
|
|
run_input: RunAgentInput,
|
|
|
|
|
step_name: str,
|
|
|
|
|
event_type: str,
|
|
|
|
|
) -> None:
|
|
|
|
|
await pipeline.emit(
|
|
|
|
|
session_id=run_input.thread_id,
|
|
|
|
|
event={
|
|
|
|
|
"type": event_type,
|
|
|
|
|
"threadId": run_input.thread_id,
|
|
|
|
|
"runId": run_input.run_id,
|
|
|
|
|
"stepName": step_name,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
|
2026-03-17 00:13:41 +08:00
|
|
|
def _resolve_runtime_client_time(
|
|
|
|
|
self, *, run_input: RunAgentInput
|
|
|
|
|
) -> ClientTimeContext | None:
|
|
|
|
|
return parse_forwarded_props_client_time(
|
|
|
|
|
getattr(run_input, "forwarded_props", None)
|
|
|
|
|
)
|
|
|
|
|
|
2026-03-16 16:10:39 +08:00
|
|
|
|
|
|
|
|
AgentScopeReActRunner = AgentScopeRunner
|