|
| 1 | +"""사이드패널 콘텐츠 생성 서비스 (side_panel 시나리오, 일반 Step 전용). |
| 2 | +
|
| 3 | +LLMClient + RAGClient를 조합하여, DOJ KB와 Custom KB 검색 결과를 합쳐 |
| 4 | +프롬프트로 조립하고 Claude를 호출해 일반 Step 사이드패널 콘텐츠를 생성한다. |
| 5 | +필수 Step의 사이드패널은 DB 사전 제작이므로 이 서비스는 호출되지 않는다. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import asyncio |
| 11 | +import json |
| 12 | +import logging |
| 13 | +from typing import Any |
| 14 | + |
| 15 | +from ai.clients.llm import LLMClient |
| 16 | +from ai.clients.rag import RAGClient |
| 17 | +from ai.prompts.template import PromptTemplate |
| 18 | +from ai.schemas.common import RetrievedChunk |
| 19 | +from ai.schemas.side_panel import SidePanelInput, SidePanelOutput |
| 20 | + |
| 21 | +logger = logging.getLogger(__name__) |
| 22 | + |
| 23 | +_SCENARIO = "side_panel" |
| 24 | +_NONE_LABEL = "없음" |
| 25 | + |
| 26 | + |
| 27 | +def _format_rag_context( |
| 28 | + doj_chunks: list[RetrievedChunk], |
| 29 | + custom_chunks: list[RetrievedChunk], |
| 30 | +) -> str: |
| 31 | + """DOJ + Custom 검색 결과를 프롬프트용 텍스트로 합쳐 포맷팅.""" |
| 32 | + sections: list[str] = [] |
| 33 | + |
| 34 | + if doj_chunks: |
| 35 | + sections.append("[DOJ SDLC]") |
| 36 | + sections.extend(chunk.text for chunk in doj_chunks) |
| 37 | + |
| 38 | + if custom_chunks: |
| 39 | + sections.append("[자체 문서]") |
| 40 | + sections.extend(chunk.text for chunk in custom_chunks) |
| 41 | + |
| 42 | + if not sections: |
| 43 | + return _NONE_LABEL |
| 44 | + |
| 45 | + return "\n".join(sections) |
| 46 | + |
| 47 | + |
| 48 | +def _coerce(value: Any, default: str = _NONE_LABEL) -> str: |
| 49 | + """None을 default 라벨로 변환.""" |
| 50 | + if value is None: |
| 51 | + return default |
| 52 | + return str(value) |
| 53 | + |
| 54 | + |
| 55 | +class SidePanelGenerator: |
| 56 | + """side_panel 시나리오 — 일반 Step 사이드패널 콘텐츠 동적 생성.""" |
| 57 | + |
| 58 | + def __init__(self, llm: LLMClient, rag: RAGClient) -> None: |
| 59 | + self.llm = llm |
| 60 | + self.rag = rag |
| 61 | + |
| 62 | + async def generate_side_panel(self, input_data: SidePanelInput) -> SidePanelOutput: |
| 63 | + """입력을 받아 Claude로 사이드패널 콘텐츠를 생성한다. |
| 64 | +
|
| 65 | + 흐름: |
| 66 | + 1) RAG 병렬 검색 (DOJ + Custom) |
| 67 | + 2) 프롬프트 조립 |
| 68 | + 3) LLM 호출 → SidePanelOutput 검증 |
| 69 | + """ |
| 70 | + stage = input_data.current_stage |
| 71 | + project = input_data.project_info |
| 72 | + target = input_data.target_step |
| 73 | + |
| 74 | + doj_query = f"Stage {stage.stage_number} {stage.name} {target.name}" |
| 75 | + custom_query = target.name |
| 76 | + |
| 77 | + doj_chunks, custom_chunks = await asyncio.gather( |
| 78 | + self.rag.search_doj(doj_query), |
| 79 | + self.rag.search_custom(custom_query), |
| 80 | + ) |
| 81 | + |
| 82 | + decision_history_json = json.dumps( |
| 83 | + [item.model_dump() for item in input_data.decision_history], |
| 84 | + ensure_ascii=False, |
| 85 | + ) |
| 86 | + |
| 87 | + if input_data.current_required_step is not None: |
| 88 | + required_step_info = json.dumps( |
| 89 | + input_data.current_required_step.model_dump(), |
| 90 | + ensure_ascii=False, |
| 91 | + ) |
| 92 | + else: |
| 93 | + required_step_info = _NONE_LABEL |
| 94 | + |
| 95 | + rag_context_text = _format_rag_context(doj_chunks, custom_chunks) |
| 96 | + |
| 97 | + prompt = PromptTemplate.load_and_render( |
| 98 | + _SCENARIO, |
| 99 | + project_name=_coerce(project.name), |
| 100 | + duration_months=str(project.duration_months), |
| 101 | + member_count=str(project.member_count), |
| 102 | + description=_coerce(project.description), |
| 103 | + constraints=_coerce(project.constraints), |
| 104 | + initial_prompt=project.initial_prompt, |
| 105 | + stage_number=str(stage.stage_number), |
| 106 | + stage_name=stage.name, |
| 107 | + target_step_name=target.name, |
| 108 | + decision_history=decision_history_json, |
| 109 | + current_required_step_info=required_step_info, |
| 110 | + rag_context=rag_context_text, |
| 111 | + ) |
| 112 | + |
| 113 | + logger.info( |
| 114 | + json.dumps( |
| 115 | + { |
| 116 | + "event": "side_panel_generator_invoke", |
| 117 | + "project_id": project.project_id, |
| 118 | + "stage_number": stage.stage_number, |
| 119 | + "target_step_name": target.name, |
| 120 | + "doj_chunks": len(doj_chunks), |
| 121 | + "custom_chunks": len(custom_chunks), |
| 122 | + "has_required_step": input_data.current_required_step is not None, |
| 123 | + "prompt_len": len(prompt), |
| 124 | + }, |
| 125 | + ensure_ascii=False, |
| 126 | + ) |
| 127 | + ) |
| 128 | + |
| 129 | + return await self.llm.invoke(prompt, SidePanelOutput) |
0 commit comments