"""投顾意图结果到草稿与事件的编排。""" from __future__ import annotations from decimal import Decimal import json from agent.advisor_agent.intent.draft_generation import ( build_rebalance_draft, build_recommendation_draft, ) from common.common_const import EVENT_ADVISOR_REBALANCE_DRAFT_CREATED from service.advisor_agent.draft import create_draft from agent.advisor_agent.llm import generate_text async def generate_rebalance_draft( *, draft_repo, publish, customer_id: int, advisor_id: int, customer_risk: str, relation_status: str, holdings: list[dict], target_allocation: dict[str, int | float | Decimal], threshold: Decimal, candidates: list[dict], trace_id: str, ) -> dict | None: draft_data = build_rebalance_draft( customer_id=customer_id, advisor_id=advisor_id, customer_risk=customer_risk, relation_status=relation_status, holdings=holdings, target_allocation=target_allocation, threshold=threshold, candidates=candidates, ) if draft_data is None: return None draft = await create_draft(draft_repo, draft_data) event_id = await publish( event_name=EVENT_ADVISOR_REBALANCE_DRAFT_CREATED, trace_id=trace_id, trigger_user_id=advisor_id, customer_id=customer_id, payload={ "draft_id": draft.draft_id, "customer_id": customer_id, "advisor_id": advisor_id, "deviation": float(draft.deviation or 0), "created_at": draft.create_time.isoformat() if draft.create_time else None, }, ) return {"draft": draft, "event_id": event_id} async def generate_recommendation_draft( *, draft_repo, customer_id: int, advisor_id: int, customer_risk: str, relation_status: str, candidates: list[dict], trace_id: str, memories: list[dict] | None = None, llm_client=None, llm_timeout: float = 5.0, ): draft_data = build_recommendation_draft( customer_id=customer_id, advisor_id=advisor_id, customer_risk=customer_risk, candidates=candidates, relation_status=relation_status, memories=memories, ) if llm_client is not None: draft_data["content"] = await generate_text( llm_client, system_prompt="你是基金投顾助手,只生成内部投顾草稿说明,不下单、不承诺收益。", user_prompt=( "请根据以下候选基金和客户记忆生成简洁推荐说明:" + json.dumps( {"candidates": candidates, "memories": memories or []}, ensure_ascii=False, ) ), fallback=lambda: draft_data["content"], timeout=llm_timeout, ) return await create_draft(draft_repo, draft_data)