|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | | -from typing import Literal, Protocol |
| 3 | +import re |
| 4 | +from collections.abc import Awaitable, Callable |
| 5 | +from typing import Any, Literal, Protocol |
4 | 6 |
|
5 | 7 | from langchain_core.output_parsers import PydanticOutputParser |
6 | 8 | from langchain_core.prompts import ChatPromptTemplate |
|
16 | 18 |
|
17 | 19 | class FollowupResult(BaseModel): |
18 | 20 | followup_question: str = Field(..., description="한국어 꼬리질문 1개") |
19 | | - answer_evaluation: AnswerEvaluation |
| 21 | + answer_evaluation: AnswerEvaluation | None = None |
20 | 22 | # 답변 의도. NORMAL=정상답변, DONT_KNOW=모름/포기, CLARIFICATION=질문 재설명 요청. |
21 | 23 | answer_intent: Literal["NORMAL", "DONT_KNOW", "CLARIFICATION"] = "NORMAL" |
22 | 24 |
|
23 | 25 |
|
| 26 | +_INTENT_RE = re.compile(r"<intent>\s*(.*?)\s*</intent>", re.DOTALL) |
| 27 | +_QUESTION_RE = re.compile(r"<question>\s*(.*?)\s*</question>", re.DOTALL) |
| 28 | +_META_RE = re.compile(r"<meta>\s*(\{.*?\})\s*</meta>", re.DOTALL) |
| 29 | +_VALID_INTENTS = {"NORMAL", "DONT_KNOW", "CLARIFICATION"} |
| 30 | + |
| 31 | + |
| 32 | +def extract_question_span(text: str) -> str: |
| 33 | + """완성 또는 진행 중 텍스트에서 <question> 안쪽만 추출(닫는 태그 없어도 가능).""" |
| 34 | + closed = _QUESTION_RE.search(text) |
| 35 | + if closed: |
| 36 | + return closed.group(1).strip() |
| 37 | + open_idx = text.find("<question>") |
| 38 | + if open_idx == -1: |
| 39 | + return "" |
| 40 | + tail = text[open_idx + len("<question>") :] |
| 41 | + tail = tail.split("<meta>", 1)[0] |
| 42 | + # 닫는/메타 태그가 스트림 청크 경계로 잘려 들어와도(예: "질문?</quest") |
| 43 | + # 미완성 '<...' 꼬리를 잘라낸다 — 질문 본문에는 '<' 가 없다고 가정. |
| 44 | + lt = tail.rfind("<") |
| 45 | + if lt != -1 and ">" not in tail[lt:]: |
| 46 | + tail = tail[:lt] |
| 47 | + return tail.strip() |
| 48 | + |
| 49 | + |
| 50 | +def parse_followup_result(text: str) -> FollowupResult: |
| 51 | + """종료된 누적 텍스트를 FollowupResult 로. 태그 누락 시 전체를 질문으로 폴백.""" |
| 52 | + intent_m = _INTENT_RE.search(text) |
| 53 | + intent = intent_m.group(1).strip().upper() if intent_m else "NORMAL" |
| 54 | + if intent not in _VALID_INTENTS: |
| 55 | + intent = "NORMAL" |
| 56 | + |
| 57 | + question = extract_question_span(text) |
| 58 | + if not question: |
| 59 | + question = text.strip() |
| 60 | + |
| 61 | + evaluation = None |
| 62 | + meta_m = _META_RE.search(text) |
| 63 | + if meta_m: |
| 64 | + try: |
| 65 | + evaluation = AnswerEvaluation.model_validate_json(meta_m.group(1)) |
| 66 | + except Exception: |
| 67 | + evaluation = None |
| 68 | + |
| 69 | + return FollowupResult( |
| 70 | + followup_question=question, |
| 71 | + answer_evaluation=evaluation, |
| 72 | + answer_intent=intent, |
| 73 | + ) |
| 74 | + |
| 75 | + |
| 76 | +class StreamingFollowupGenerator: |
| 77 | + """단일 LLM 콜을 astream 으로 흘리며 <question> 토큰만 콜백으로 내보낸다. |
| 78 | +
|
| 79 | + intent 가 DONT_KNOW 면 질문 델타를 보내지 않는다(Core 가 폐기하므로). |
| 80 | + 종료 후 누적 텍스트를 parse_followup_result 로 검증해 반환. |
| 81 | + """ |
| 82 | + |
| 83 | + def __init__(self, *, prompt: ChatPromptTemplate, llm: Any) -> None: |
| 84 | + self._prompt = prompt |
| 85 | + self._llm = llm |
| 86 | + |
| 87 | + async def stream( |
| 88 | + self, |
| 89 | + *, |
| 90 | + on_question_token: Callable[[str], Awaitable[None] | None], |
| 91 | + job_category: str, |
| 92 | + mode: str, |
| 93 | + previous_question: str, |
| 94 | + answer_text: str, |
| 95 | + context: str, |
| 96 | + parent_category: str, |
| 97 | + expected_signal: str, |
| 98 | + history: str, |
| 99 | + ) -> FollowupResult: |
| 100 | + all_vars = { |
| 101 | + "job_category": job_category, |
| 102 | + "mode": mode, |
| 103 | + "previous_question": previous_question, |
| 104 | + "answer_text": answer_text, |
| 105 | + "context": context, |
| 106 | + "parent_category": parent_category, |
| 107 | + "expected_signal": expected_signal, |
| 108 | + "history": history, |
| 109 | + } |
| 110 | + # 프롬프트가 선언한 변수만 전달(템플릿마다 변수 집합이 다를 수 있음). |
| 111 | + wanted = set(self._prompt.input_variables) |
| 112 | + prompt_vars = {k: v for k, v in all_vars.items() if k in wanted} |
| 113 | + messages = self._prompt.format_messages(**prompt_vars) |
| 114 | + |
| 115 | + acc = "" |
| 116 | + emitted_q = "" |
| 117 | + async for chunk in self._llm.astream(messages): |
| 118 | + piece = getattr(chunk, "content", "") or "" |
| 119 | + if not piece: |
| 120 | + continue |
| 121 | + acc += piece |
| 122 | + intent_known = _INTENT_RE.search(acc) |
| 123 | + if not intent_known: |
| 124 | + continue |
| 125 | + if intent_known.group(1).strip().upper() == "DONT_KNOW": |
| 126 | + continue |
| 127 | + q_now = extract_question_span(acc) |
| 128 | + if len(q_now) > len(emitted_q): |
| 129 | + delta = q_now[len(emitted_q) :] |
| 130 | + emitted_q = q_now |
| 131 | + res = on_question_token(delta) |
| 132 | + if res is not None and hasattr(res, "__await__"): |
| 133 | + await res |
| 134 | + |
| 135 | + return parse_followup_result(acc) |
| 136 | + |
| 137 | + |
24 | 138 | class FollowupGenerator(Protocol): |
25 | 139 | async def generate( |
26 | 140 | self, |
@@ -103,3 +217,41 @@ def build_followup_generation_chain( |
103 | 217 | callbacks=callbacks, |
104 | 218 | ) |
105 | 219 | return prompt | llm | parser |
| 220 | + |
| 221 | + |
| 222 | +def build_streaming_followup_generator( |
| 223 | + settings: Settings, core_client: CoreClient | None = None |
| 224 | +) -> StreamingFollowupGenerator: |
| 225 | + """스트리밍 꼬리질문 생성기 빌더. |
| 226 | +
|
| 227 | + format_instructions 없는 프롬프트 + Flash LLM 을 조합해 |
| 228 | + StreamingFollowupGenerator 를 반환한다. |
| 229 | + """ |
| 230 | + from langchain_openai import ChatOpenAI |
| 231 | + |
| 232 | + prompt = ChatPromptTemplate.from_messages( |
| 233 | + [ |
| 234 | + ("system", SYSTEM_PROMPT), |
| 235 | + ("human", HUMAN_PROMPT), |
| 236 | + ] |
| 237 | + ) |
| 238 | + |
| 239 | + callbacks = [] |
| 240 | + if core_client is not None: |
| 241 | + callbacks.append( |
| 242 | + CoreAiLogCallback( |
| 243 | + core_client=core_client, |
| 244 | + request_type="generate.followup.stream", |
| 245 | + default_model=settings.llm_flash_model, |
| 246 | + ) |
| 247 | + ) |
| 248 | + |
| 249 | + llm = ChatOpenAI( |
| 250 | + model=settings.llm_flash_model, |
| 251 | + temperature=settings.llm_flash_temperature, |
| 252 | + api_key=settings.llm_api_key or None, |
| 253 | + base_url=settings.llm_base_url, |
| 254 | + max_tokens=settings.llm_flash_max_tokens, |
| 255 | + callbacks=callbacks, |
| 256 | + ) |
| 257 | + return StreamingFollowupGenerator(prompt=prompt, llm=llm) |
0 commit comments