diff --git a/architecture.md b/architecture.md index b3e2e3d..5c4fc9d 100644 --- a/architecture.md +++ b/architecture.md @@ -49,6 +49,7 @@ flowchart LR ## 맥락 추출 아키텍처 기존 정보 및 토론 대화 기록에서 신규로 발생한 주장을 추출하고 기존 주장을 업데이트하고, 전체 토론의 흐름을 요약한다. +신규 문장은 구 맥락 정보에 아직 반영되지 않은 발화 전부(하나 이상)이고, 이전 문장은 이미 반영된 발화다. 추출한 주장은 처음 나온 발화를 함께 기록한다. ```mermaid flowchart LR subgraph Inputs [입력] diff --git a/models/context.py b/models/context.py index 3712403..7f4bf54 100644 --- a/models/context.py +++ b/models/context.py @@ -1,6 +1,6 @@ """맥락 추출과 심층 분석의 입출력 모델.""" -from pydantic import BaseModel +from pydantic import BaseModel, Field from models.persona import PersonaInfo, PersonaInput @@ -25,6 +25,7 @@ class Claim(BaseModel): claim_id: str speaker: str claim: str + utterance: str # 이 주장이 처음 나온 발화 원문 reasons: list[Reason] = [] @@ -50,8 +51,8 @@ class DiscussionContext(BaseModel): class ContextExtractionInput(BaseModel): topic: str book: BookMetadata - new_turn: DiscussionTurn - previous_turns: list[DiscussionTurn] = [] + new_turns: list[DiscussionTurn] = Field(min_length=1) # 구 맥락에 아직 반영되지 않은 발화 전부 + previous_turns: list[DiscussionTurn] = [] # 구 맥락에 이미 반영된 발화 previous_context: DiscussionContext | None = None # 첫 턴에는 없음 @@ -68,8 +69,8 @@ class AnalysisInput(ContextExtractionInput): # 맥락 추출 단계별 LLM 출력. structured output 스키마로 쓰이므로 기본값을 두지 않는다. class NewClaim(BaseModel): - speaker: str claim: str + turn_id: str # 주장이 나온 최신 발화의 번호. 코드가 화자와 원문으로 바꾼다 class ClaimClassification(BaseModel): diff --git a/services/context_extraction.py b/services/context_extraction.py index cf7f5d6..b59713a 100644 --- a/services/context_extraction.py +++ b/services/context_extraction.py @@ -1,4 +1,7 @@ -"""신규 발화를 반영해 맥락 정보를 갱신한다. 신규 주장 구분 → 근거 분석 → 맥락 갱신.""" +"""최신 발화들을 반영해 맥락 정보를 갱신한다. 신규 주장 구분 → 근거 분석 → 맥락 갱신. + +최신 발화는 구 맥락에 아직 반영되지 않은 발화 전부다. +""" from itertools import count @@ -18,18 +21,18 @@ from models.context import ( from settings import settings from utils.common_llm import StructuredLLM -CLASSIFY_PROMPT = """너는 독서토론에서 신규 발화가 어떤 주장에 해당하는지 구분한다. +CLASSIFY_PROMPT = """너는 독서토론의 최신 발화들이 어떤 주장에 해당하는지 구분한다. -- 기존 주장을 보강하거나 이어가는 발화면, 그 주장의 ID를 updated_claim_ids에 담는다. 기존 주장 목록에 있는 ID만 쓴다. -- 기존 주장을 반박하거나, 기존 주장과 무관한 새 주장이면 new_claims에 담는다. - - speaker: 발언자 이름을 그대로 쓴다. +- 최신 발화가 기존 주장을 보강하거나 이어가면, 그 주장의 ID를 updated_claim_ids에 담는다. 기존 주장 목록에 있는 ID만 쓴다. +- 최신 발화가 기존 주장을 반박하거나, 기존 주장과 무관한 새 주장을 내면 new_claims에 담는다. - claim: 주장을 한 문장으로 정리한다. -- 주장이 없는 발화면 둘 다 빈 목록으로 둔다.""" + - turn_id: 그 주장이 나온 발화의 번호를 [최신 발화] 목록에서 고른다. +- 주장이 없는 발화는 건너뛴다.""" REASON_PROMPT = """너는 독서토론 주장의 근거를 정리한다. -주어진 주장마다 신규 발화를 반영해 근거 목록을 다시 쓴다. -- 기존 근거는 유지하고, 신규 발화에서 나온 근거를 더한다. 같은 근거는 합친다. +주어진 주장마다 최신 발화들을 반영해 근거 목록을 다시 쓴다. +- 기존 근거는 유지하고, 최신 발화에서 나온 근거를 더한다. 같은 근거는 합친다. - claim_id: 주어진 ID를 그대로 쓴다. - reason: 주장을 뒷받침하는 이유를 쓴다. 주장 자체를 되풀이하지 않는다. 이유를 대지 않았으면 근거로 만들지 않는다. - turn_ids: 그 근거가 나온 발화의 번호를 [발화] 목록에서 고른다. 근거를 합쳤으면 합친 발화의 번호를 모두 고른다. @@ -63,7 +66,9 @@ def _to_reason(draft: ReasonDraft, utterance_by_turn_id: dict[str, str]) -> Reas async def classify_claims( - extraction_input: ContextExtractionInput, existing_claims: list[Claim] + extraction_input: ContextExtractionInput, + existing_claims: list[Claim], + new_turn_by_id: dict[str, DiscussionTurn], ) -> ClaimClassification: previous = extraction_input.previous_context prompt = "\n\n".join([ @@ -71,7 +76,9 @@ async def classify_claims( f"[이전 맥락]\n{previous.summary if previous else '없음'}", f"[기존 주장]\n{render_claims(existing_claims) or '없음'}", f"[이전 발화]\n{_render_turns(extraction_input.previous_turns) or '없음'}", - f"[신규 발화]\n{_render_turns([extraction_input.new_turn])}", + "[최신 발화]\n" + "\n".join( + f"[{turn_id}] {turn.speaker}: {turn.text}" for turn_id, turn in new_turn_by_id.items() + ), ]) classification = await context_llm.ask(ClaimClassification, prompt, system=CLASSIFY_PROMPT) @@ -80,11 +87,16 @@ async def classify_claims( {claim.claim_id for claim in existing_claims}, kind="주장", ) + _reject_unknown_ids( + {new_claim.turn_id for new_claim in classification.new_claims}, + set(new_turn_by_id), + kind="발화", + ) return classification async def analyze_reasons( - book: BookMetadata, new_turn: DiscussionTurn, target_claims: list[Claim] + book: BookMetadata, new_turns: list[DiscussionTurn], target_claims: list[Claim] ) -> list[Claim]: if not target_claims: return [] @@ -95,14 +107,14 @@ async def analyze_reasons( for reason in claim.reasons for utterance in reason.utterances ] - utterance_pool = list(dict.fromkeys(existing_utterances + [new_turn.text])) + utterance_pool = list(dict.fromkeys(existing_utterances + [turn.text for turn in new_turns])) utterance_by_turn_id = {f"t{number}": text for number, text in enumerate(utterance_pool, 1)} prompt = "\n\n".join([ f"책: {book.title} ({book.author})", "[발화]\n" + "\n".join(f"[{turn_id}] {text}" for turn_id, text in utterance_by_turn_id.items()), f"[주장]\n{render_claims(target_claims)}", - f"[신규 발화]\n{_render_turns([new_turn])}", + f"[최신 발화]\n{_render_turns(new_turns)}", ]) analysis = await context_llm.ask(ReasonAnalysis, prompt, system=REASON_PROMPT) @@ -146,12 +158,18 @@ async def extract_context(extraction_input: ContextExtractionInput) -> Discussio previous = extraction_input.previous_context existing_claims = previous.current_claims + previous.past_claims if previous else [] - classification = await classify_claims(extraction_input, existing_claims) + new_turn_by_id = {f"t{number}": turn for number, turn in enumerate(extraction_input.new_turns, 1)} + classification = await classify_claims(extraction_input, existing_claims, new_turn_by_id) known_ids = {claim.claim_id for claim in existing_claims} fresh_ids = (f"c{number}" for number in count(1) if f"c{number}" not in known_ids) new_claims = [ - Claim(claim_id=next(fresh_ids), speaker=new_claim.speaker, claim=new_claim.claim) + Claim( + claim_id=next(fresh_ids), + speaker=new_turn_by_id[new_claim.turn_id].speaker, + claim=new_claim.claim, + utterance=new_turn_by_id[new_claim.turn_id].text, + ) for new_claim in classification.new_claims ] @@ -160,7 +178,7 @@ async def extract_context(extraction_input: ContextExtractionInput) -> Discussio past_claims = [claim for claim in existing_claims if claim.claim_id not in updated_ids] current_claims = await analyze_reasons( - extraction_input.book, extraction_input.new_turn, updated_claims + new_claims + extraction_input.book, extraction_input.new_turns, updated_claims + new_claims ) summary = await update_summary(extraction_input, current_claims, past_claims) return DiscussionContext(summary=summary, current_claims=current_claims, past_claims=past_claims) diff --git a/tests/demo.html b/tests/demo.html new file mode 100644 index 0000000..f1f09cd --- /dev/null +++ b/tests/demo.html @@ -0,0 +1,468 @@ + + +
+ + +맥락 추출 → 페르소나 분석 → 발화 가이드. 서버는 상태를 갖지 않고, 이 페이지가 맥락·페르소나 정보를 들고 있다가 다음 턴에 되돌려 보냅니다.
+