2026-09-10 15:55:54 +08:00
|
|
|
import logging
|
2026-09-09 21:55:37 +08:00
|
|
|
from functools import lru_cache
|
|
|
|
|
from typing import Any, cast
|
|
|
|
|
|
2026-09-10 15:55:54 +08:00
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
2026-09-11 14:44:29 +08:00
|
|
|
from app.core.advisor_allocation_contracts import AssetAllocationQuery
|
2026-09-10 15:55:54 +08:00
|
|
|
from app.core.config import get_settings
|
|
|
|
|
from app.core.errors import RecoverableAgentError
|
2026-09-09 23:40:35 +08:00
|
|
|
from app.core.fund_contracts import FundQuoteQuery
|
2026-09-11 13:11:58 +08:00
|
|
|
from app.core.investment_goal_contracts import InvestmentGoalQuery
|
2026-09-11 13:20:09 +08:00
|
|
|
from app.core.portfolio_analysis_contracts import PortfolioAnalysisQuery
|
2026-09-11 19:20:32 +08:00
|
|
|
from app.core.product_comparison_contracts import ProductComparisonQuery
|
2026-09-11 15:29:20 +08:00
|
|
|
from app.core.product_recommendation_contracts import ProductRecommendationQuery
|
2026-09-10 15:55:54 +08:00
|
|
|
from app.infrastructure.fund_quote_cache import FundQuoteCache
|
|
|
|
|
from app.infrastructure.memory_cache import MemoryCacheAdapter
|
|
|
|
|
from app.infrastructure.vector_memory import VectorMemoryAdapter
|
2026-09-09 21:55:37 +08:00
|
|
|
from app.service.agent.factory import AgentFactory
|
2026-09-10 15:55:54 +08:00
|
|
|
from app.service.agent.governance import PlatformGovernance
|
2026-09-11 11:49:11 +08:00
|
|
|
from app.service.agent.implementations.advisor import AdvisorAgent
|
2026-09-10 15:55:54 +08:00
|
|
|
from app.service.agent.implementations.fund_query_demo import FundQueryDemoAgent
|
2026-09-11 14:44:29 +08:00
|
|
|
from app.service.asset_allocation_service import asset_allocation_tool
|
2026-09-09 23:40:35 +08:00
|
|
|
from app.service.fund_quote_service import query_fund_quote_tool
|
2026-09-09 21:55:37 +08:00
|
|
|
from app.service.intent_classifier import IntentClassifier
|
2026-09-11 13:11:58 +08:00
|
|
|
from app.service.investment_goal_service import investment_goal_query_tool
|
2026-09-10 15:55:54 +08:00
|
|
|
from app.service.memory_recall_service import MemoryRecallService
|
2026-09-09 21:55:37 +08:00
|
|
|
from app.service.model_gateway import (
|
|
|
|
|
DatabaseModelEndpointResolver,
|
|
|
|
|
DatabaseModelGateway,
|
|
|
|
|
ModelDispatchService,
|
2026-09-10 15:55:54 +08:00
|
|
|
ModelEmbeddingService,
|
2026-09-09 21:55:37 +08:00
|
|
|
ModelGenerationService,
|
|
|
|
|
)
|
2026-09-11 13:20:09 +08:00
|
|
|
from app.service.portfolio_analysis_service import portfolio_analysis_tool
|
2026-09-11 19:20:32 +08:00
|
|
|
from app.service.product_comparison_service import product_comparison_tool
|
2026-09-11 15:29:20 +08:00
|
|
|
from app.service.product_recommendation_service import product_recommendation_tool
|
2026-09-10 15:55:54 +08:00
|
|
|
from app.service.runtime_config_service import load_active_intent_configs
|
2026-09-09 23:40:35 +08:00
|
|
|
from app.service.suitability_service import SuitabilityToolInput, suitability_tool_handler
|
2026-09-09 21:55:37 +08:00
|
|
|
from app.service.tool_executor import ToolDefinition, ToolExecutor, ToolRegistry
|
|
|
|
|
|
2026-09-10 15:55:54 +08:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
|
|
|
def get_model_service() -> ModelGenerationService:
|
|
|
|
|
"""生产模型装配的唯一入口;业务 Agent 与 Worker 记忆抽取共用同一实例。"""
|
|
|
|
|
return ModelGenerationService(ModelDispatchService(DatabaseModelGateway()))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
|
|
|
def get_memory_cache_adapter() -> MemoryCacheAdapter | None:
|
|
|
|
|
"""Redis 记忆缓存适配器;构造失败返回 None——缓存只是优化层,不得阻塞召回。"""
|
|
|
|
|
try:
|
|
|
|
|
from redis.asyncio import Redis
|
|
|
|
|
|
|
|
|
|
settings = get_settings()
|
|
|
|
|
client = Redis.from_url(
|
|
|
|
|
settings.redis_url,
|
|
|
|
|
socket_connect_timeout=settings.redis_connect_timeout_seconds,
|
|
|
|
|
socket_timeout=settings.redis_connect_timeout_seconds,
|
|
|
|
|
decode_responses=True,
|
|
|
|
|
)
|
|
|
|
|
return MemoryCacheAdapter(client)
|
|
|
|
|
except Exception:
|
|
|
|
|
logger.warning("memory cache adapter unavailable; recall runs without cache",
|
|
|
|
|
exc_info=True)
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
|
|
|
def get_fund_quote_cache() -> FundQuoteCache | None:
|
|
|
|
|
"""行情短缓存:与记忆召回共用同一个 Redis 适配器。
|
|
|
|
|
|
|
|
|
|
Redis 不可用时这里仍会返回适配器,但读写异常由 `MemoryCacheAdapter` 内部
|
|
|
|
|
吞掉并以 `degraded` 语义返回,行情查询会退化为直连外部数据源而不会阻塞;
|
|
|
|
|
适配器构造失败(例如缺少 redis 依赖)则返回 None,效果相同。缓存永远只是
|
|
|
|
|
优化层,不得让行情查询因缓存故障失败。
|
|
|
|
|
"""
|
|
|
|
|
adapter = get_memory_cache_adapter()
|
|
|
|
|
if adapter is None:
|
|
|
|
|
return None
|
|
|
|
|
return FundQuoteCache(adapter)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
|
|
|
def get_vector_memory_adapter() -> VectorMemoryAdapter | None:
|
|
|
|
|
"""Milvus 适配器;构造失败返回 None(语义通道关闭),不影响结构化召回。"""
|
|
|
|
|
try:
|
|
|
|
|
from pymilvus import MilvusClient # type: ignore[import-untyped]
|
|
|
|
|
|
|
|
|
|
settings = get_settings()
|
|
|
|
|
client = MilvusClient(uri=settings.milvus_uri, token=settings.milvus_token or None)
|
|
|
|
|
return VectorMemoryAdapter(client, settings.milvus_collection)
|
|
|
|
|
except Exception:
|
|
|
|
|
logger.warning("vector memory adapter unavailable; semantic recall disabled",
|
|
|
|
|
exc_info=True)
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
|
|
|
def get_memory_embedding_service() -> ModelEmbeddingService:
|
|
|
|
|
"""文本向量化入口:与文本生成共用同一套端点解析与受控降级。"""
|
|
|
|
|
return ModelEmbeddingService(ModelDispatchService(DatabaseModelGateway()))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def _embed_text(text: str) -> list[float]:
|
|
|
|
|
"""把文本向量化;端点来自发布配置(task_type=embedding),无端点时失败关闭。"""
|
|
|
|
|
endpoints = await DatabaseModelEndpointResolver().resolve(
|
|
|
|
|
agent_type="memory_recall", task_type="embedding"
|
|
|
|
|
)
|
|
|
|
|
if not endpoints:
|
|
|
|
|
raise RecoverableAgentError("没有可用的 embedding 端点")
|
|
|
|
|
execution = await get_memory_embedding_service().embed(endpoints, text)
|
|
|
|
|
return execution.vector
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def build_memory_recall_service(session: AsyncSession) -> MemoryRecallService:
|
|
|
|
|
"""记忆召回组装:结构化召回始终可用,Redis 缓存与语义通道可用时叠加。
|
|
|
|
|
|
|
|
|
|
语义通道需要**两件事同时具备**:可达的 Milvus 与可用的 embedding 端点。缺少
|
|
|
|
|
embedding 端点时向量化按设计失败关闭,结果标记 `embedding_failed` 并保留结构化
|
|
|
|
|
召回——这是配置缺口而非功能缺失,配置端点后语义召回无需改代码即可生效。
|
|
|
|
|
"""
|
|
|
|
|
vector = get_vector_memory_adapter()
|
|
|
|
|
return MemoryRecallService(
|
|
|
|
|
session,
|
|
|
|
|
vector=vector,
|
|
|
|
|
cache=get_memory_cache_adapter(),
|
|
|
|
|
embed=_embed_text if vector is not None else None,
|
|
|
|
|
)
|
|
|
|
|
|
2026-09-09 21:55:37 +08:00
|
|
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
|
|
|
def get_agent_factory() -> AgentFactory:
|
|
|
|
|
"""HTTP 与 Worker 共用的唯一底座依赖组装入口。"""
|
|
|
|
|
registry = ToolRegistry()
|
|
|
|
|
registry.register(ToolDefinition(
|
|
|
|
|
name="check_suitability",
|
|
|
|
|
input_model=SuitabilityToolInput,
|
|
|
|
|
handler=cast(Any, suitability_tool_handler),
|
|
|
|
|
required_permission="suitability:read",
|
|
|
|
|
allowed_roles=("customer", "advisor", "operator", "admin"),
|
|
|
|
|
))
|
2026-09-09 23:40:35 +08:00
|
|
|
registry.register(ToolDefinition(
|
|
|
|
|
name="query_fund_quote",
|
|
|
|
|
input_model=FundQuoteQuery,
|
|
|
|
|
handler=cast(Any, query_fund_quote_tool),
|
|
|
|
|
required_permission="fund:quote:read",
|
|
|
|
|
allowed_roles=("customer", "advisor", "operator", "risk_operator", "admin"),
|
2026-09-10 15:55:54 +08:00
|
|
|
# C3 数值依据:EastmoneyAdapterFactory 的单代码最坏预算为
|
|
|
|
|
# 4.0s(单次) + 0.2s(退避) + 4.0s(重试) = 8.2s,且 FundQuoteService
|
|
|
|
|
# 已按代码并发,总耗时与代码数量无关。15s ≈ 8.2s × 1.8,余量覆盖
|
|
|
|
|
# DNS/TLS 建连与事件循环调度开销。原值 5s 小于适配器默认单次超时
|
|
|
|
|
# (12s)与重试预算,多代码查询必然先撞工具超时。
|
|
|
|
|
timeout_seconds=15,
|
2026-09-09 23:40:35 +08:00
|
|
|
))
|
2026-09-11 13:11:58 +08:00
|
|
|
registry.register(ToolDefinition(
|
|
|
|
|
name="query_investment_goal",
|
|
|
|
|
input_model=InvestmentGoalQuery,
|
|
|
|
|
handler=cast(Any, investment_goal_query_tool),
|
|
|
|
|
required_permission="investment-goal:read:self",
|
|
|
|
|
allowed_roles=("customer", "advisor", "operator", "admin"),
|
|
|
|
|
))
|
2026-09-11 13:20:09 +08:00
|
|
|
registry.register(ToolDefinition(
|
|
|
|
|
name="analyze_portfolio",
|
|
|
|
|
input_model=PortfolioAnalysisQuery,
|
|
|
|
|
handler=cast(Any, portfolio_analysis_tool),
|
|
|
|
|
required_permission="portfolio-analysis:read:self",
|
|
|
|
|
allowed_roles=("customer", "advisor", "operator", "admin"),
|
|
|
|
|
timeout_seconds=10,
|
|
|
|
|
))
|
2026-09-11 14:44:29 +08:00
|
|
|
registry.register(ToolDefinition(
|
|
|
|
|
name="generate_asset_allocation",
|
|
|
|
|
input_model=AssetAllocationQuery,
|
|
|
|
|
handler=cast(Any, asset_allocation_tool),
|
|
|
|
|
required_permission="asset-allocation:generate:self",
|
|
|
|
|
allowed_roles=("customer", "advisor", "operator", "admin"),
|
|
|
|
|
timeout_seconds=15,
|
|
|
|
|
))
|
2026-09-11 15:29:20 +08:00
|
|
|
registry.register(ToolDefinition(
|
|
|
|
|
name="recommend_products",
|
|
|
|
|
input_model=ProductRecommendationQuery,
|
|
|
|
|
handler=cast(Any, product_recommendation_tool),
|
|
|
|
|
required_permission="product-recommendation:generate:self",
|
|
|
|
|
allowed_roles=("customer", "advisor", "operator", "admin"),
|
|
|
|
|
timeout_seconds=15,
|
|
|
|
|
))
|
2026-09-11 19:20:32 +08:00
|
|
|
registry.register(ToolDefinition(
|
|
|
|
|
name="compare_products",
|
|
|
|
|
input_model=ProductComparisonQuery,
|
|
|
|
|
handler=cast(Any, product_comparison_tool),
|
|
|
|
|
required_permission="product-comparison:read:self",
|
|
|
|
|
allowed_roles=("customer", "advisor", "operator", "admin"),
|
|
|
|
|
timeout_seconds=10,
|
|
|
|
|
))
|
2026-09-10 15:55:54 +08:00
|
|
|
model_service = get_model_service()
|
2026-09-09 21:55:37 +08:00
|
|
|
endpoint_resolver = DatabaseModelEndpointResolver()
|
2026-09-10 15:55:54 +08:00
|
|
|
factory = AgentFactory(
|
|
|
|
|
# 记忆召回接入统一治理链:Agent 的 recall_memory 走组合召回服务,
|
|
|
|
|
# 而不是每个 Agent 自行决定召回方式。
|
|
|
|
|
governance=PlatformGovernance(recall_factory=build_memory_recall_service),
|
2026-09-09 21:55:37 +08:00
|
|
|
model_service=model_service,
|
|
|
|
|
tool_executor=ToolExecutor(registry),
|
2026-09-10 15:55:54 +08:00
|
|
|
intent_classifier=IntentClassifier(
|
|
|
|
|
model_service, config_loader=load_active_intent_configs
|
|
|
|
|
),
|
2026-09-09 21:55:37 +08:00
|
|
|
intent_endpoint_resolver=endpoint_resolver,
|
|
|
|
|
)
|
2026-09-10 15:55:54 +08:00
|
|
|
register_business_agents(factory)
|
|
|
|
|
return factory
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def register_business_agents(factory: AgentFactory) -> None:
|
|
|
|
|
"""业务 Agent 的统一注册入口:组员在这里登记自己的一行 `factory.register(...)`。
|
|
|
|
|
|
|
|
|
|
HTTP 服务与 Worker 共用 `get_agent_factory()` 返回的同一个工厂,因此这里注册
|
|
|
|
|
一次即可在两个入口生效。注册只声明"代码允许什么":真正能调用哪些工具,还要
|
|
|
|
|
看当前 active 的 `config_release` 里为该 `agent_type:intent` 发布的工具白名单
|
|
|
|
|
(两者取交集,缺发布配置时白名单为空、工具失败关闭)。
|
|
|
|
|
"""
|
|
|
|
|
factory.register(
|
|
|
|
|
FundQueryDemoAgent.definition,
|
|
|
|
|
lambda _context: FundQueryDemoAgent(FundQueryDemoAgent.definition),
|
|
|
|
|
)
|
2026-09-11 11:49:11 +08:00
|
|
|
factory.register(
|
|
|
|
|
AdvisorAgent.definition,
|
|
|
|
|
lambda _context: AdvisorAgent(AdvisorAgent.definition),
|
|
|
|
|
)
|