아키텍처 구조화 및 일부 구현
This commit is contained in:
1 parent
3a257fbe26
commit
20d5409c41
8 files changed
+477
-85
No files matched your search
@@ -1,39 +0,0 @@
|
||||
"""독서토론 발언에서 주장을 추출한다."""
|
||||
|
||||
from models.context import AnalysisInput, DiscussionContext
|
||||
from settings import settings
|
||||
from utils.common_llm import StructuredLLM
|
||||
|
||||
SYSTEM_PROMPT = """너는 독서토론 기록에서 참여자의 주장을 추출한다.
|
||||
|
||||
- 화자가 실제로 내세운 주장만 뽑는다. 없는 주장을 추측해서 만들지 않는다.
|
||||
- statement: 주장을 한 문장으로 정리한다.
|
||||
- evidence: 화자가 그 주장을 뒷받침하려고 든 근거를 옮긴다. 근거를 대지 않았으면 빈 목록으로 둔다.
|
||||
- speaker: 발언자 이름을 그대로 쓴다."""
|
||||
|
||||
claim_llm = StructuredLLM(settings.llm_model, settings.chatgpt_api_key)
|
||||
|
||||
|
||||
def _render_input(analysis_input: AnalysisInput) -> str:
|
||||
lines = [f"책: {analysis_input.book.title} ({analysis_input.book.author})"]
|
||||
|
||||
if analysis_input.excerpts:
|
||||
lines.append("\n[원문 발췌]")
|
||||
for excerpt in analysis_input.excerpts:
|
||||
locator = f"({excerpt.locator}) " if excerpt.locator else ""
|
||||
lines.append(f"{locator}{excerpt.text}")
|
||||
|
||||
if analysis_input.turns:
|
||||
lines.append("\n[토론 발언]")
|
||||
for turn in analysis_input.turns:
|
||||
lines.append(f"{turn.speaker}: {turn.text}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
async def extract_claims(analysis_input: AnalysisInput) -> DiscussionContext:
|
||||
return await claim_llm.ask(
|
||||
DiscussionContext,
|
||||
_render_input(analysis_input),
|
||||
system=SYSTEM_PROMPT,
|
||||
)
|
||||
@@ -0,0 +1,123 @@
|
||||
"""신규 발화를 반영해 맥락 정보를 갱신한다. 신규 주장 구분 → 근거 분석 → 맥락 갱신."""
|
||||
|
||||
from itertools import count
|
||||
|
||||
from models.context import (
|
||||
Claim,
|
||||
ClaimClassification,
|
||||
ContextExtractionInput,
|
||||
ContextSummary,
|
||||
DiscussionContext,
|
||||
DiscussionTurn,
|
||||
ReasonAnalysis,
|
||||
render_claims,
|
||||
)
|
||||
from settings import settings
|
||||
from utils.common_llm import StructuredLLM
|
||||
|
||||
CLASSIFY_PROMPT = """너는 독서토론에서 신규 발화가 어떤 주장에 해당하는지 구분한다.
|
||||
|
||||
- 기존 주장을 보강하거나 반박하거나 이어가는 발화면, 그 주장의 ID를 updated_claim_ids에 담는다. 기존 주장 목록에 있는 ID만 쓴다.
|
||||
- 기존 주장과 무관한 새 주장이면 new_claims에 담는다.
|
||||
- speaker: 발언자 이름을 그대로 쓴다.
|
||||
- claim: 주장을 한 문장으로 정리한다.
|
||||
- 주장이 없는 발화면 둘 다 빈 목록으로 둔다."""
|
||||
|
||||
REASON_PROMPT = """너는 독서토론 주장의 근거를 정리한다.
|
||||
|
||||
주어진 주장마다 신규 발화를 반영해 근거 목록을 다시 쓴다.
|
||||
- 기존 근거는 유지하고, 신규 발화에서 나온 근거를 더한다. 같은 근거는 합친다.
|
||||
- claim_id: 주어진 ID를 그대로 쓴다.
|
||||
- reason: 근거를 한 문장으로 정리한다.
|
||||
- excerpts: 그 근거로 든 인용을 그대로 옮긴다. 인용이 없으면 빈 목록으로 둔다."""
|
||||
|
||||
SUMMARY_PROMPT = """너는 독서토론의 맥락을 요약한다.
|
||||
|
||||
이전 맥락과 현재까지의 주장을 바탕으로 토론이 지금 어디까지 왔는지를 요약한다.
|
||||
- 어떤 쟁점이 오갔고 누가 어떤 입장인지 드러나게 쓴다.
|
||||
- 신규/갱신 주장을 반영한다."""
|
||||
|
||||
context_llm = StructuredLLM(settings.llm_model, settings.chatgpt_api_key)
|
||||
|
||||
|
||||
def _render_turns(turns: list[DiscussionTurn]) -> str:
|
||||
return "\n".join(f"{turn.speaker}: {turn.text}" for turn in turns)
|
||||
|
||||
|
||||
def _reject_unknown_ids(returned_ids: set[str], known_ids: set[str]) -> None:
|
||||
unknown_ids = returned_ids - known_ids
|
||||
if unknown_ids:
|
||||
raise ValueError(f"존재하지 않는 주장 ID: {sorted(unknown_ids)}")
|
||||
|
||||
|
||||
async def classify_claims(
|
||||
extraction_input: ContextExtractionInput, existing_claims: list[Claim]
|
||||
) -> ClaimClassification:
|
||||
previous = extraction_input.previous_context
|
||||
prompt = "\n\n".join([
|
||||
f"토론 주제: {extraction_input.topic}",
|
||||
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])}",
|
||||
])
|
||||
classification = await context_llm.ask(ClaimClassification, prompt, system=CLASSIFY_PROMPT)
|
||||
|
||||
_reject_unknown_ids(
|
||||
set(classification.updated_claim_ids),
|
||||
{claim.claim_id for claim in existing_claims},
|
||||
)
|
||||
return classification
|
||||
|
||||
|
||||
async def analyze_reasons(new_turn: DiscussionTurn, target_claims: list[Claim]) -> list[Claim]:
|
||||
if not target_claims:
|
||||
return []
|
||||
|
||||
prompt = f"[주장]\n{render_claims(target_claims)}\n\n[신규 발화]\n{_render_turns([new_turn])}"
|
||||
analysis = await context_llm.ask(ReasonAnalysis, prompt, system=REASON_PROMPT)
|
||||
|
||||
reasons_by_id = {item.claim_id: item.reasons for item in analysis.claims}
|
||||
_reject_unknown_ids(set(reasons_by_id), {claim.claim_id for claim in target_claims})
|
||||
return [
|
||||
claim.model_copy(update={"reasons": reasons_by_id.get(claim.claim_id, claim.reasons)})
|
||||
for claim in target_claims
|
||||
]
|
||||
|
||||
|
||||
async def update_summary(
|
||||
extraction_input: ContextExtractionInput,
|
||||
current_claims: list[Claim],
|
||||
past_claims: list[Claim],
|
||||
) -> str:
|
||||
previous = extraction_input.previous_context
|
||||
prompt = "\n\n".join([
|
||||
f"토론 주제: {extraction_input.topic}",
|
||||
f"[이전 맥락]\n{previous.summary if previous else '없음'}",
|
||||
f"[신규/갱신 주장]\n{render_claims(current_claims) or '없음'}",
|
||||
f"[과거 주장]\n{render_claims(past_claims) or '없음'}",
|
||||
])
|
||||
result = await context_llm.ask(ContextSummary, prompt, system=SUMMARY_PROMPT)
|
||||
return result.summary
|
||||
|
||||
|
||||
async def extract_context(extraction_input: ContextExtractionInput) -> DiscussionContext:
|
||||
previous = extraction_input.previous_context
|
||||
existing_claims = previous.current_claims + previous.past_claims if previous else []
|
||||
|
||||
classification = await classify_claims(extraction_input, existing_claims)
|
||||
|
||||
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)
|
||||
for new_claim in classification.new_claims
|
||||
]
|
||||
|
||||
updated_ids = set(classification.updated_claim_ids)
|
||||
updated_claims = [claim for claim in existing_claims if claim.claim_id in updated_ids]
|
||||
past_claims = [claim for claim in existing_claims if claim.claim_id not in updated_ids]
|
||||
|
||||
current_claims = await analyze_reasons(extraction_input.new_turn, 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)
|
||||
@@ -0,0 +1,62 @@
|
||||
"""페르소나를 해석하고, 토론 관점과 이번 발화의 전략을 정한다."""
|
||||
|
||||
from models.context import DiscussionContext, render_claims
|
||||
from models.persona import PersonaInfo, PersonaInput, PersonaSummary, SpeechStrategy, TopicViewPoint
|
||||
from settings import settings
|
||||
from utils.common_llm import StructuredLLM
|
||||
|
||||
INTERPRET_PROMPT = """너는 독서토론 참여자의 페르소나를 해석한다.
|
||||
키워드와 인적 정보를 바탕으로 이 사람이 어떤 사람인지, 어떻게 생각하고 말하는지를 요약한다."""
|
||||
|
||||
VIEW_POINT_PROMPT = """너는 독서토론 참여자가 토론 주제를 어떤 관점에서 바라볼지 정한다.
|
||||
페르소나 요약에 비추어 이 사람이 주제에 대해 가질 법한 입장과 관심사를 쓴다."""
|
||||
|
||||
STRATEGY_PROMPT = """너는 독서토론 참여자의 이번 발화 전략을 정한다.
|
||||
페르소나 요약과 토론 관점, 현재 맥락을 바탕으로 이 사람이 지금 어떤 방식으로 대화에 참여할지 쓴다.
|
||||
공감, 반문, 정리, 새로운 시각 제시처럼 대화에 작용하는 방식을 구체적으로 쓴다.
|
||||
주장 목록에서 참여자 자신의 주장은 입장의 일관성을 지키는 데 참고한다."""
|
||||
|
||||
persona_llm = StructuredLLM(settings.llm_model, settings.chatgpt_api_key)
|
||||
|
||||
|
||||
def _render_persona(persona_input: PersonaInput) -> str:
|
||||
lines = [f"키워드: {', '.join(persona_input.keywords)}", f"성별: {persona_input.gender}"]
|
||||
if persona_input.age is not None:
|
||||
lines.append(f"나이: {persona_input.age}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
async def interpret_persona(persona_input: PersonaInput) -> str:
|
||||
result = await persona_llm.ask(PersonaSummary, _render_persona(persona_input), system=INTERPRET_PROMPT)
|
||||
return result.summary
|
||||
|
||||
|
||||
async def derive_view_point(summary: str, topic: str) -> str:
|
||||
prompt = f"토론 주제: {topic}\n\n[페르소나 요약]\n{summary}"
|
||||
result = await persona_llm.ask(TopicViewPoint, prompt, system=VIEW_POINT_PROMPT)
|
||||
return result.topic_view_point
|
||||
|
||||
|
||||
async def prepare_persona(
|
||||
persona_input: PersonaInput, topic: str, previous_persona_info: PersonaInfo | None
|
||||
) -> tuple[str, str]:
|
||||
"""페르소나 요약과 토론 관점을 돌려준다. 이전 결과가 있으면 그대로 쓴다."""
|
||||
if previous_persona_info:
|
||||
return previous_persona_info.summary, previous_persona_info.topic_view_point
|
||||
summary = await interpret_persona(persona_input)
|
||||
return summary, await derive_view_point(summary, topic)
|
||||
|
||||
|
||||
async def select_strategy(
|
||||
speaker: str, summary: str, view_point: str, context: DiscussionContext
|
||||
) -> str:
|
||||
prompt = "\n\n".join([
|
||||
f"[참여자]\n{speaker}",
|
||||
f"[페르소나 요약]\n{summary}",
|
||||
f"[토론 관점]\n{view_point}",
|
||||
f"[현재 맥락]\n{context.summary}",
|
||||
f"[신규/갱신 주장]\n{render_claims(context.current_claims) or '없음'}",
|
||||
f"[과거 주장]\n{render_claims(context.past_claims) or '없음'}",
|
||||
])
|
||||
result = await persona_llm.ask(SpeechStrategy, prompt, system=STRATEGY_PROMPT)
|
||||
return result.current_strategy
|
||||
+41
-22
@@ -1,39 +1,45 @@
|
||||
"""토론에서 나온 주장과 페르소나로 다음 발화의 가이드를 만든다."""
|
||||
"""갱신된 맥락과 페르소나 정보로 다음 발화의 가이드를 만든다."""
|
||||
|
||||
from models.context import AnalysisInput
|
||||
from models.utterance_guide import UtteranceGuide, UtteranceGuideInput
|
||||
from services.claim_extraction import extract_claims
|
||||
import asyncio
|
||||
|
||||
from models.context import AnalysisInput, render_claims
|
||||
from models.persona import PersonaInfo
|
||||
from models.utterance_guide import StyleGuideResult, UtteranceGuide, UtteranceGuideInput
|
||||
from services.context_extraction import extract_context
|
||||
from services.persona_analysis import prepare_persona, select_strategy
|
||||
from settings import settings
|
||||
from utils.common_llm import StructuredLLM
|
||||
|
||||
SYSTEM_PROMPT = """너는 독서토론에 참여하는 AI의 다음 발화를 설계한다.
|
||||
주어진 페르소나로 토론에 참여한다고 보고, 발화문은 쓰지 말고 어떻게 발화할지만 정한다.
|
||||
주어진 참여자로서 페르소나대로 토론에 참여한다고 보고, 발화문은 쓰지 말고 어떻게 발화할지만 정한다.
|
||||
주장 목록에서 참여자 자신의 주장은 입장의 일관성을 지키는 데 참고한다.
|
||||
|
||||
- target_claim: 반응할 주장 하나를 고르고 한 문장으로 옮긴다.
|
||||
- target_claim: 다른 화자의 주장 중 반응할 주장 하나를 고르고 한 문장으로 옮긴다. 신규/갱신 주장을 우선하고, 과거 주장은 참고만 한다.
|
||||
- intent: 그 주장에 대해 무엇을 할지 쓴다. 동의, 반박, 질문, 확장 등.
|
||||
- key_message: 핵심으로 전할 내용을 한 문장으로 쓴다.
|
||||
- tone: 페르소나의 성격과 말투에 맞는 태도를 쓴다."""
|
||||
- tone: 발화 전략과 페르소나에 맞는 태도를 쓴다."""
|
||||
|
||||
guide_llm = StructuredLLM(settings.llm_model, settings.chatgpt_api_key)
|
||||
|
||||
|
||||
def _render_input(guide_input: UtteranceGuideInput) -> str:
|
||||
persona = guide_input.persona
|
||||
context = guide_input.context
|
||||
lines = [
|
||||
f"책: {guide_input.book.title} ({guide_input.book.author})",
|
||||
f"\n[참여자]\n{guide_input.next_speaker}",
|
||||
"\n[페르소나]",
|
||||
f"이름: {persona.name}",
|
||||
f"성격: {persona.personality}",
|
||||
f"말투: {persona.speaking_style}",
|
||||
f"관점: {persona.perspective}",
|
||||
f"키워드: {', '.join(persona.keywords)}",
|
||||
f"요약: {persona.summary}",
|
||||
f"토론 관점: {persona.topic_view_point}",
|
||||
f"발화 전략: {persona.current_strategy}",
|
||||
f"\n[현재 맥락]\n{context.summary}",
|
||||
]
|
||||
|
||||
if guide_input.claims:
|
||||
lines.append("\n[토론에서 나온 주장]")
|
||||
for claim in guide_input.claims:
|
||||
lines.append(f"{claim.speaker}: {claim.statement}")
|
||||
for evidence in claim.evidence:
|
||||
lines.append(f" 근거: {evidence}")
|
||||
if context.current_claims:
|
||||
lines.append(f"\n[신규/갱신 주장]\n{render_claims(context.current_claims)}")
|
||||
if context.past_claims:
|
||||
lines.append(f"\n[과거 주장]\n{render_claims(context.past_claims)}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
@@ -46,13 +52,26 @@ async def build_utterance_guide(guide_input: UtteranceGuideInput) -> UtteranceGu
|
||||
)
|
||||
|
||||
|
||||
async def generate_style_guide(analysis_input: AnalysisInput) -> UtteranceGuide:
|
||||
async def generate_style_guide(analysis_input: AnalysisInput) -> StyleGuideResult:
|
||||
"""지식 기반 스타일 가이드를 생성한다."""
|
||||
discussion = await extract_claims(analysis_input)
|
||||
return await build_utterance_guide(
|
||||
speaker = analysis_input.next_speaker
|
||||
context, (summary, view_point) = await asyncio.gather(
|
||||
extract_context(analysis_input),
|
||||
prepare_persona(speaker.persona, analysis_input.topic, analysis_input.previous_persona_info),
|
||||
)
|
||||
strategy = await select_strategy(speaker.name, summary, view_point, context)
|
||||
persona_info = PersonaInfo(
|
||||
keywords=speaker.persona.keywords,
|
||||
summary=summary,
|
||||
current_strategy=strategy,
|
||||
topic_view_point=view_point,
|
||||
)
|
||||
guide = await build_utterance_guide(
|
||||
UtteranceGuideInput(
|
||||
book=analysis_input.book,
|
||||
persona=analysis_input.persona,
|
||||
claims=discussion.claims,
|
||||
next_speaker=speaker.name,
|
||||
persona=persona_info,
|
||||
context=context,
|
||||
)
|
||||
)
|
||||
return StyleGuideResult(context=context, persona_info=persona_info, guide=guide)
|
||||
Reference in new issue
Block a user