최신 발화 정의 수정 및 데모 페이지 개설
This commit is contained in:
1 parent
762a258f88
commit
f0e8071887
8 files changed
+636
-23
No files matched your search
@@ -49,6 +49,7 @@ flowchart LR
|
|||||||
|
|
||||||
## 맥락 추출 아키텍처
|
## 맥락 추출 아키텍처
|
||||||
기존 정보 및 토론 대화 기록에서 신규로 발생한 주장을 추출하고 기존 주장을 업데이트하고, 전체 토론의 흐름을 요약한다.
|
기존 정보 및 토론 대화 기록에서 신규로 발생한 주장을 추출하고 기존 주장을 업데이트하고, 전체 토론의 흐름을 요약한다.
|
||||||
|
신규 문장은 구 맥락 정보에 아직 반영되지 않은 발화 전부(하나 이상)이고, 이전 문장은 이미 반영된 발화다. 추출한 주장은 처음 나온 발화를 함께 기록한다.
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart LR
|
flowchart LR
|
||||||
subgraph Inputs [입력]
|
subgraph Inputs [입력]
|
||||||
|
|||||||
+5
-4
@@ -1,6 +1,6 @@
|
|||||||
"""맥락 추출과 심층 분석의 입출력 모델."""
|
"""맥락 추출과 심층 분석의 입출력 모델."""
|
||||||
|
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
from models.persona import PersonaInfo, PersonaInput
|
from models.persona import PersonaInfo, PersonaInput
|
||||||
|
|
||||||
@@ -25,6 +25,7 @@ class Claim(BaseModel):
|
|||||||
claim_id: str
|
claim_id: str
|
||||||
speaker: str
|
speaker: str
|
||||||
claim: str
|
claim: str
|
||||||
|
utterance: str # 이 주장이 처음 나온 발화 원문
|
||||||
reasons: list[Reason] = []
|
reasons: list[Reason] = []
|
||||||
|
|
||||||
|
|
||||||
@@ -50,8 +51,8 @@ class DiscussionContext(BaseModel):
|
|||||||
class ContextExtractionInput(BaseModel):
|
class ContextExtractionInput(BaseModel):
|
||||||
topic: str
|
topic: str
|
||||||
book: BookMetadata
|
book: BookMetadata
|
||||||
new_turn: DiscussionTurn
|
new_turns: list[DiscussionTurn] = Field(min_length=1) # 구 맥락에 아직 반영되지 않은 발화 전부
|
||||||
previous_turns: list[DiscussionTurn] = []
|
previous_turns: list[DiscussionTurn] = [] # 구 맥락에 이미 반영된 발화
|
||||||
previous_context: DiscussionContext | None = None # 첫 턴에는 없음
|
previous_context: DiscussionContext | None = None # 첫 턴에는 없음
|
||||||
|
|
||||||
|
|
||||||
@@ -68,8 +69,8 @@ class AnalysisInput(ContextExtractionInput):
|
|||||||
# 맥락 추출 단계별 LLM 출력. structured output 스키마로 쓰이므로 기본값을 두지 않는다.
|
# 맥락 추출 단계별 LLM 출력. structured output 스키마로 쓰이므로 기본값을 두지 않는다.
|
||||||
|
|
||||||
class NewClaim(BaseModel):
|
class NewClaim(BaseModel):
|
||||||
speaker: str
|
|
||||||
claim: str
|
claim: str
|
||||||
|
turn_id: str # 주장이 나온 최신 발화의 번호. 코드가 화자와 원문으로 바꾼다
|
||||||
|
|
||||||
|
|
||||||
class ClaimClassification(BaseModel):
|
class ClaimClassification(BaseModel):
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
"""신규 발화를 반영해 맥락 정보를 갱신한다. 신규 주장 구분 → 근거 분석 → 맥락 갱신."""
|
"""최신 발화들을 반영해 맥락 정보를 갱신한다. 신규 주장 구분 → 근거 분석 → 맥락 갱신.
|
||||||
|
|
||||||
|
최신 발화는 구 맥락에 아직 반영되지 않은 발화 전부다.
|
||||||
|
"""
|
||||||
|
|
||||||
from itertools import count
|
from itertools import count
|
||||||
|
|
||||||
@@ -18,18 +21,18 @@ from models.context import (
|
|||||||
from settings import settings
|
from settings import settings
|
||||||
from utils.common_llm import StructuredLLM
|
from utils.common_llm import StructuredLLM
|
||||||
|
|
||||||
CLASSIFY_PROMPT = """너는 독서토론에서 신규 발화가 어떤 주장에 해당하는지 구분한다.
|
CLASSIFY_PROMPT = """너는 독서토론의 최신 발화들이 어떤 주장에 해당하는지 구분한다.
|
||||||
|
|
||||||
- 기존 주장을 보강하거나 이어가는 발화면, 그 주장의 ID를 updated_claim_ids에 담는다. 기존 주장 목록에 있는 ID만 쓴다.
|
- 최신 발화가 기존 주장을 보강하거나 이어가면, 그 주장의 ID를 updated_claim_ids에 담는다. 기존 주장 목록에 있는 ID만 쓴다.
|
||||||
- 기존 주장을 반박하거나, 기존 주장과 무관한 새 주장이면 new_claims에 담는다.
|
- 최신 발화가 기존 주장을 반박하거나, 기존 주장과 무관한 새 주장을 내면 new_claims에 담는다.
|
||||||
- speaker: 발언자 이름을 그대로 쓴다.
|
|
||||||
- claim: 주장을 한 문장으로 정리한다.
|
- claim: 주장을 한 문장으로 정리한다.
|
||||||
- 주장이 없는 발화면 둘 다 빈 목록으로 둔다."""
|
- turn_id: 그 주장이 나온 발화의 번호를 [최신 발화] 목록에서 고른다.
|
||||||
|
- 주장이 없는 발화는 건너뛴다."""
|
||||||
|
|
||||||
REASON_PROMPT = """너는 독서토론 주장의 근거를 정리한다.
|
REASON_PROMPT = """너는 독서토론 주장의 근거를 정리한다.
|
||||||
|
|
||||||
주어진 주장마다 신규 발화를 반영해 근거 목록을 다시 쓴다.
|
주어진 주장마다 최신 발화들을 반영해 근거 목록을 다시 쓴다.
|
||||||
- 기존 근거는 유지하고, 신규 발화에서 나온 근거를 더한다. 같은 근거는 합친다.
|
- 기존 근거는 유지하고, 최신 발화에서 나온 근거를 더한다. 같은 근거는 합친다.
|
||||||
- claim_id: 주어진 ID를 그대로 쓴다.
|
- claim_id: 주어진 ID를 그대로 쓴다.
|
||||||
- reason: 주장을 뒷받침하는 이유를 쓴다. 주장 자체를 되풀이하지 않는다. 이유를 대지 않았으면 근거로 만들지 않는다.
|
- reason: 주장을 뒷받침하는 이유를 쓴다. 주장 자체를 되풀이하지 않는다. 이유를 대지 않았으면 근거로 만들지 않는다.
|
||||||
- turn_ids: 그 근거가 나온 발화의 번호를 [발화] 목록에서 고른다. 근거를 합쳤으면 합친 발화의 번호를 모두 고른다.
|
- turn_ids: 그 근거가 나온 발화의 번호를 [발화] 목록에서 고른다. 근거를 합쳤으면 합친 발화의 번호를 모두 고른다.
|
||||||
@@ -63,7 +66,9 @@ def _to_reason(draft: ReasonDraft, utterance_by_turn_id: dict[str, str]) -> Reas
|
|||||||
|
|
||||||
|
|
||||||
async def classify_claims(
|
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:
|
) -> ClaimClassification:
|
||||||
previous = extraction_input.previous_context
|
previous = extraction_input.previous_context
|
||||||
prompt = "\n\n".join([
|
prompt = "\n\n".join([
|
||||||
@@ -71,7 +76,9 @@ async def classify_claims(
|
|||||||
f"[이전 맥락]\n{previous.summary if previous else '없음'}",
|
f"[이전 맥락]\n{previous.summary if previous else '없음'}",
|
||||||
f"[기존 주장]\n{render_claims(existing_claims) or '없음'}",
|
f"[기존 주장]\n{render_claims(existing_claims) or '없음'}",
|
||||||
f"[이전 발화]\n{_render_turns(extraction_input.previous_turns) 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)
|
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},
|
{claim.claim_id for claim in existing_claims},
|
||||||
kind="주장",
|
kind="주장",
|
||||||
)
|
)
|
||||||
|
_reject_unknown_ids(
|
||||||
|
{new_claim.turn_id for new_claim in classification.new_claims},
|
||||||
|
set(new_turn_by_id),
|
||||||
|
kind="발화",
|
||||||
|
)
|
||||||
return classification
|
return classification
|
||||||
|
|
||||||
|
|
||||||
async def analyze_reasons(
|
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]:
|
) -> list[Claim]:
|
||||||
if not target_claims:
|
if not target_claims:
|
||||||
return []
|
return []
|
||||||
@@ -95,14 +107,14 @@ async def analyze_reasons(
|
|||||||
for reason in claim.reasons
|
for reason in claim.reasons
|
||||||
for utterance in reason.utterances
|
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)}
|
utterance_by_turn_id = {f"t{number}": text for number, text in enumerate(utterance_pool, 1)}
|
||||||
|
|
||||||
prompt = "\n\n".join([
|
prompt = "\n\n".join([
|
||||||
f"책: {book.title} ({book.author})",
|
f"책: {book.title} ({book.author})",
|
||||||
"[발화]\n" + "\n".join(f"[{turn_id}] {text}" for turn_id, text in utterance_by_turn_id.items()),
|
"[발화]\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_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)
|
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
|
previous = extraction_input.previous_context
|
||||||
existing_claims = previous.current_claims + previous.past_claims if previous else []
|
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}
|
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)
|
fresh_ids = (f"c{number}" for number in count(1) if f"c{number}" not in known_ids)
|
||||||
new_claims = [
|
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
|
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]
|
past_claims = [claim for claim in existing_claims if claim.claim_id not in updated_ids]
|
||||||
|
|
||||||
current_claims = await analyze_reasons(
|
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)
|
summary = await update_summary(extraction_input, current_claims, past_claims)
|
||||||
return DiscussionContext(summary=summary, current_claims=current_claims, past_claims=past_claims)
|
return DiscussionContext(summary=summary, current_claims=current_claims, past_claims=past_claims)
|
||||||
+468
@@ -0,0 +1,468 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ko">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>스타일 가이드 시연</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg: #f6f7f9; --card: #fff; --line: #e3e6ea; --text: #1f2328; --muted: #656d76;
|
||||||
|
--accent: #2f6feb; --accent-weak: #e8f0fe; --danger: #cf222e;
|
||||||
|
--dummy: #9a6700; --dummy-weak: #fff8c5; --guide-bg: #f6f8fa;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body { margin: 0; font: 14px/1.6 system-ui, -apple-system, "Segoe UI", "Noto Sans KR", sans-serif; background: var(--bg); color: var(--text); }
|
||||||
|
body > header { padding: 16px 24px; border-bottom: 1px solid var(--line); background: var(--card); }
|
||||||
|
body > header h1 { margin: 0; font-size: 18px; }
|
||||||
|
body > header p { margin: 4px 0 0; color: var(--muted); }
|
||||||
|
main { display: grid; grid-template-columns: 280px minmax(0, 1fr) 340px; gap: 16px; padding: 16px 24px; align-items: start; }
|
||||||
|
@media (max-width: 1100px) { main { grid-template-columns: 1fr; } }
|
||||||
|
section { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 16px; }
|
||||||
|
h2 { font-size: 15px; margin: 0 0 10px; }
|
||||||
|
h3 { font-size: 13px; margin: 14px 0 4px; color: var(--muted); }
|
||||||
|
label { display: block; font-size: 12px; color: var(--muted); margin: 10px 0 4px; }
|
||||||
|
input, textarea { width: 100%; padding: 7px 9px; border: 1px solid var(--line); border-radius: 6px; font: inherit; background: #fff; }
|
||||||
|
textarea { resize: vertical; }
|
||||||
|
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
||||||
|
.compose { display: grid; grid-template-columns: 120px 1fr; gap: 8px; margin-top: 8px; }
|
||||||
|
.actions { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; align-items: center; }
|
||||||
|
button { padding: 8px 14px; border-radius: 6px; border: 1px solid var(--line); background: var(--card); font: inherit; cursor: pointer; }
|
||||||
|
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||||
|
button.small { padding: 2px 10px; font-size: 12px; margin-left: auto; }
|
||||||
|
button:disabled { opacity: .5; cursor: default; }
|
||||||
|
.error { margin-top: 8px; font-size: 12px; color: var(--danger); white-space: pre-wrap; }
|
||||||
|
.empty { color: var(--muted); }
|
||||||
|
.badge { display: inline-block; font-size: 11px; font-weight: normal; padding: 1px 7px; border-radius: 10px; background: var(--accent-weak); color: var(--accent); vertical-align: middle; }
|
||||||
|
.badge.dummy { background: var(--dummy-weak); color: var(--dummy); border: 1px solid var(--dummy); }
|
||||||
|
summary { cursor: pointer; color: var(--muted); font-size: 12px; }
|
||||||
|
pre { background: var(--guide-bg); padding: 10px; border-radius: 6px; overflow: auto; font-size: 12px; }
|
||||||
|
.card { border: 1px solid var(--line); border-radius: 8px; padding: 12px 14px; margin-bottom: 12px; }
|
||||||
|
|
||||||
|
/* 대화 타임라인 */
|
||||||
|
#timeline { display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.turn { border: 1px solid var(--line); border-left: 4px solid var(--speaker); border-radius: 8px; padding: 10px 14px; background: var(--card); }
|
||||||
|
.turn > header { display: flex; gap: 8px; align-items: center; }
|
||||||
|
.turn > header strong { color: var(--speaker); }
|
||||||
|
.turn .turn-index { font-size: 12px; color: var(--muted); }
|
||||||
|
.turn > p { margin: 6px 0 0; }
|
||||||
|
.turn.pending { border-style: dashed; border-left-style: solid; background: var(--guide-bg); }
|
||||||
|
.used-guide { margin-top: 10px; padding: 8px 10px; border-radius: 6px; background: var(--guide-bg); }
|
||||||
|
.used-guide .label { font-size: 12px; color: var(--muted); margin-bottom: 4px; }
|
||||||
|
.turn-claims { margin-top: 8px; }
|
||||||
|
.guide { display: grid; grid-template-columns: 72px 1fr; gap: 2px 10px; margin: 6px 0 0; }
|
||||||
|
.guide dt { font-size: 12px; color: var(--muted); }
|
||||||
|
.guide dd { margin: 0; }
|
||||||
|
|
||||||
|
/* 주장 */
|
||||||
|
.claim { border-left: 3px solid var(--line); padding: 2px 10px; margin: 6px 0; }
|
||||||
|
.claim .meta { font-size: 12px; color: var(--muted); }
|
||||||
|
.claim .source, .reason .source { font-size: 12px; color: var(--muted); margin-left: 12px; }
|
||||||
|
.reason { margin: 4px 0 0 8px; font-size: 13px; }
|
||||||
|
|
||||||
|
/* 현재 상태 */
|
||||||
|
.facts dt { font-size: 12px; color: var(--muted); }
|
||||||
|
.facts dd { margin: 0 0 8px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<h1>지식 기반 스타일 가이드 생성 시연</h1>
|
||||||
|
<p>맥락 추출 → 페르소나 분석 → 발화 가이드. 서버는 상태를 갖지 않고, 이 페이지가 맥락·페르소나 정보를 들고 있다가 다음 턴에 되돌려 보냅니다.</p>
|
||||||
|
</header>
|
||||||
|
<main>
|
||||||
|
<section>
|
||||||
|
<h2>설정</h2>
|
||||||
|
<label for="bookTitle">책 제목</label><input id="bookTitle">
|
||||||
|
<label for="bookAuthor">저자</label><input id="bookAuthor">
|
||||||
|
<label for="topic">토론 주제</label><textarea id="topic" rows="3"></textarea>
|
||||||
|
|
||||||
|
<h3>다음 화자</h3>
|
||||||
|
<label for="speakerName">이름</label><input id="speakerName">
|
||||||
|
<label for="speakerKeywords">키워드 (쉼표로 구분)</label><input id="speakerKeywords">
|
||||||
|
<div class="row">
|
||||||
|
<div><label for="speakerGender">성별</label><input id="speakerGender"></div>
|
||||||
|
<div><label for="speakerAge">나이 (선택)</label><input id="speakerAge" type="number" min="0"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>대화</h2>
|
||||||
|
<div id="timeline"></div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="primary" id="runButton">스타일 가이드 생성</button>
|
||||||
|
<button id="manualButton">최신 발화 직접 입력</button>
|
||||||
|
<button id="resetButton">초기화</button>
|
||||||
|
</div>
|
||||||
|
<div class="error" id="errorMessage"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>현재 상태</h2>
|
||||||
|
<div id="side"></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const $ = (id) => document.getElementById(id);
|
||||||
|
const escapeHtml = (text) => String(text ?? "").replace(/[&<>"']/g, (char) => (
|
||||||
|
{ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[char]
|
||||||
|
));
|
||||||
|
|
||||||
|
const SPEAKER_COLORS = ["#2f6feb", "#1a7f37", "#bf3989", "#9a6700", "#8250df", "#cf222e"];
|
||||||
|
const speakerColors = new Map();
|
||||||
|
|
||||||
|
function colorOf(speaker) {
|
||||||
|
if (!speaker) return "var(--line)";
|
||||||
|
if (!speakerColors.has(speaker)) {
|
||||||
|
speakerColors.set(speaker, SPEAKER_COLORS[speakerColors.size % SPEAKER_COLORS.length]);
|
||||||
|
}
|
||||||
|
return speakerColors.get(speaker);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 클라이언트가 들고 다니는 상태. 서버는 이걸 저장하지 않는다.
|
||||||
|
const state = {};
|
||||||
|
|
||||||
|
function resetState() {
|
||||||
|
Object.assign(state, {
|
||||||
|
turns: [], // { speaker, text, guide, isDummy } — 구 맥락에 반영된 발화. guide는 이 발화에 쓰인 발화 가이드
|
||||||
|
draftTurns: [], // { speaker, text, isDummy } — 구 맥락에 아직 반영되지 않은 최신 발화
|
||||||
|
editingIndex: null, // 수정 중인 최신 발화의 위치
|
||||||
|
pendingGuide: null, // { speaker, guide } — 아직 쓰이지 않은 다음 발화 가이드
|
||||||
|
previousContext: null,
|
||||||
|
previousPersonaInfo: null,
|
||||||
|
personaKey: null,
|
||||||
|
lastResult: null,
|
||||||
|
personaReused: false,
|
||||||
|
});
|
||||||
|
speakerColors.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
function readNextSpeaker() {
|
||||||
|
const age = $("speakerAge").value.trim();
|
||||||
|
return {
|
||||||
|
name: $("speakerName").value.trim(),
|
||||||
|
persona: {
|
||||||
|
keywords: $("speakerKeywords").value.split(",").map((keyword) => keyword.trim()).filter(Boolean),
|
||||||
|
gender: $("speakerGender").value.trim(),
|
||||||
|
age: age ? Number(age) : null,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 이전 페르소나 정보는 페르소나 입력과 토론 주제가 그대로일 때만 보낸다. 이 검증은 호스트(이 페이지)의 몫이다.
|
||||||
|
function personaKeyOf(input) {
|
||||||
|
return JSON.stringify([input.next_speaker.persona, input.topic]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const plainTurns = (turns) => turns.map(({ speaker, text }) => ({ speaker, text }));
|
||||||
|
|
||||||
|
// 대기 중인 가이드는 그 가이드를 받은 화자의 바로 다음 발화, 즉 첫 번째 최신 발화에만 쓰인다.
|
||||||
|
function guideForFirstDraft() {
|
||||||
|
const pending = state.pendingGuide;
|
||||||
|
const first = state.draftTurns[0];
|
||||||
|
return pending && first && pending.speaker === first.speaker ? pending.guide : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildInput() {
|
||||||
|
const input = {
|
||||||
|
book: { title: $("bookTitle").value.trim(), author: $("bookAuthor").value.trim() },
|
||||||
|
topic: $("topic").value.trim(),
|
||||||
|
previous_turns: plainTurns(state.turns),
|
||||||
|
new_turns: plainTurns(state.draftTurns),
|
||||||
|
previous_context: state.previousContext,
|
||||||
|
next_speaker: readNextSpeaker(),
|
||||||
|
};
|
||||||
|
input.previous_persona_info = personaKeyOf(input) === state.personaKey ? state.previousPersonaInfo : null;
|
||||||
|
return input;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postJson(url, body) {
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
const data = await response.json().catch(() => ({ error: response.statusText }));
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(typeof data.error === "string" ? data.error : JSON.stringify(data.error, null, 2));
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showError(message) {
|
||||||
|
$("errorMessage").textContent = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function withBusy(button, task) {
|
||||||
|
const label = button.textContent;
|
||||||
|
for (const other of document.querySelectorAll("button")) other.disabled = true;
|
||||||
|
button.textContent = "생성 중…";
|
||||||
|
showError("");
|
||||||
|
try {
|
||||||
|
await task();
|
||||||
|
} catch (error) {
|
||||||
|
showError(error.message);
|
||||||
|
} finally {
|
||||||
|
button.textContent = label;
|
||||||
|
for (const other of document.querySelectorAll("button")) other.disabled = false;
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderGuide(guide) {
|
||||||
|
return `
|
||||||
|
<dl class="guide">
|
||||||
|
<dt>대상 주장</dt><dd>${escapeHtml(guide.target_claim)}</dd>
|
||||||
|
<dt>의도</dt><dd>${escapeHtml(guide.intent)}</dd>
|
||||||
|
<dt>핵심 메시지</dt><dd>${escapeHtml(guide.key_message)}</dd>
|
||||||
|
<dt>태도</dt><dd>${escapeHtml(guide.tone)}</dd>
|
||||||
|
</dl>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderUsedGuide(guide) {
|
||||||
|
return guide ? `<div class="used-guide"><div class="label">사용한 발화 가이드</div>${renderGuide(guide)}</div>` : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderClaims(claims, { withOrigin = false } = {}) {
|
||||||
|
if (!claims.length) return '<p class="empty">없음</p>';
|
||||||
|
return claims.map((claim) => `
|
||||||
|
<div class="claim">
|
||||||
|
<div class="meta">${escapeHtml(claim.claim_id)} · ${escapeHtml(claim.speaker)}</div>
|
||||||
|
<div>${escapeHtml(claim.claim)}</div>
|
||||||
|
${withOrigin ? `<div class="source">처음 나온 발화: ${escapeHtml(claim.utterance)}</div>` : ""}
|
||||||
|
${claim.reasons.map((reason) => `
|
||||||
|
<div class="reason">근거: ${escapeHtml(reason.reason)}
|
||||||
|
${reason.utterances.map((utterance) => `<div class="source">발화: ${escapeHtml(utterance)}</div>`).join("")}
|
||||||
|
${(reason.book_excerpts ?? []).map((excerpt) => `<div class="source">책 인용: ${escapeHtml(excerpt)}</div>`).join("")}
|
||||||
|
</div>`).join("")}
|
||||||
|
</div>`).join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 최신 맥락의 주장을 발화 원문으로 각 카드에 매칭한다. 처음 나온 발화와 근거로 쓰인 발화를 나눠서 단다.
|
||||||
|
function claimsOfTurn(turn) {
|
||||||
|
const context = state.previousContext;
|
||||||
|
if (!context) return { origin: [], supported: [] };
|
||||||
|
const claims = [...context.current_claims, ...context.past_claims];
|
||||||
|
return {
|
||||||
|
origin: claims.filter((claim) => claim.utterance === turn.text),
|
||||||
|
supported: claims.filter((claim) => claim.utterance !== turn.text
|
||||||
|
&& claim.reasons.some((reason) => reason.utterances.includes(turn.text))),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderClaimSection(title, claims) {
|
||||||
|
if (!claims.length) return "";
|
||||||
|
return `
|
||||||
|
<details class="turn-claims" open>
|
||||||
|
<summary>${title} (${claims.length})</summary>
|
||||||
|
${renderClaims(claims)}
|
||||||
|
</details>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTurn(turn, index) {
|
||||||
|
const { origin, supported } = claimsOfTurn(turn);
|
||||||
|
return `
|
||||||
|
<article class="turn" style="--speaker: ${colorOf(turn.speaker)}">
|
||||||
|
<header>
|
||||||
|
<strong>${escapeHtml(turn.speaker)}</strong>
|
||||||
|
<span class="turn-index">#${index + 1}</span>
|
||||||
|
${turn.isDummy ? '<span class="badge dummy">더미 생성</span>' : ""}
|
||||||
|
</header>
|
||||||
|
<p>${escapeHtml(turn.text)}</p>
|
||||||
|
${renderUsedGuide(turn.guide)}
|
||||||
|
${renderClaimSection("이 발화에서 나온 주장", origin)}
|
||||||
|
${renderClaimSection("이 발화가 근거로 쓰인 주장", supported)}
|
||||||
|
</article>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderPendingGuide() {
|
||||||
|
const { speaker, guide } = state.pendingGuide;
|
||||||
|
return `
|
||||||
|
<article class="turn pending" style="--speaker: ${colorOf(speaker)}">
|
||||||
|
<header><strong>다음 발화 가이드</strong><span class="badge">${escapeHtml(speaker)}</span></header>
|
||||||
|
${renderGuide(guide)}
|
||||||
|
<div class="actions">
|
||||||
|
<button id="dummyButton">가이드대로 발화 생성</button>
|
||||||
|
<span class="badge dummy">테스트용 더미 · MCP에 포함되지 않음</span>
|
||||||
|
</div>
|
||||||
|
</article>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderDraft(draft, draftIndex) {
|
||||||
|
const index = state.turns.length + draftIndex;
|
||||||
|
if (state.editingIndex === draftIndex) {
|
||||||
|
return `
|
||||||
|
<article class="turn" style="--speaker: ${colorOf(draft.speaker)}">
|
||||||
|
<header><strong>최신 발화</strong><span class="turn-index">#${index + 1}</span></header>
|
||||||
|
<div class="compose">
|
||||||
|
<input id="draftSpeaker" value="${escapeHtml(draft.speaker)}" placeholder="화자">
|
||||||
|
<textarea id="draftText" rows="3" placeholder="발화 내용">${escapeHtml(draft.text)}</textarea>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="primary" id="saveDraftButton">저장</button>
|
||||||
|
<button id="cancelDraftButton">취소</button>
|
||||||
|
</div>
|
||||||
|
</article>`;
|
||||||
|
}
|
||||||
|
return `
|
||||||
|
<article class="turn" style="--speaker: ${colorOf(draft.speaker)}">
|
||||||
|
<header>
|
||||||
|
<strong>${escapeHtml(draft.speaker)}</strong>
|
||||||
|
<span class="turn-index">#${index + 1}</span>
|
||||||
|
<span class="badge">최신 발화</span>
|
||||||
|
${draft.isDummy ? '<span class="badge dummy">더미 생성</span>' : ""}
|
||||||
|
<button class="small" data-edit-index="${draftIndex}">수정</button>
|
||||||
|
</header>
|
||||||
|
<p>${escapeHtml(draft.text)}</p>
|
||||||
|
${draftIndex === 0 ? renderUsedGuide(guideForFirstDraft()) : ""}
|
||||||
|
</article>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTimeline() {
|
||||||
|
const cards = state.turns.map(renderTurn);
|
||||||
|
// 최신 발화가 없을 때만 가이드 카드를 따로 보여준다. 있으면 첫 최신 발화 카드에 붙거나, 다른 화자가 먼저 말했으면 버려진다.
|
||||||
|
if (state.pendingGuide && !state.draftTurns.length) cards.push(renderPendingGuide());
|
||||||
|
cards.push(...state.draftTurns.map(renderDraft));
|
||||||
|
|
||||||
|
$("timeline").innerHTML = cards.join("") || '<p class="empty">아직 발화가 없습니다.</p>';
|
||||||
|
$("dummyButton")?.addEventListener("click", (event) => withBusy(event.currentTarget, runDummyUtterance));
|
||||||
|
$("saveDraftButton")?.addEventListener("click", saveDraft);
|
||||||
|
$("cancelDraftButton")?.addEventListener("click", cancelDraft);
|
||||||
|
for (const button of document.querySelectorAll("[data-edit-index]")) {
|
||||||
|
button.addEventListener("click", () => editDraft(Number(button.dataset.editIndex)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderSide() {
|
||||||
|
const result = state.lastResult;
|
||||||
|
if (!result) {
|
||||||
|
$("side").innerHTML = '<p class="empty">아직 실행하지 않았습니다.</p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { context, persona_info: persona } = result;
|
||||||
|
$("side").innerHTML = `
|
||||||
|
<div class="card">
|
||||||
|
<h2>맥락 정보</h2>
|
||||||
|
<p>${escapeHtml(context.summary)}</p>
|
||||||
|
<h3>신규/갱신 주장</h3>
|
||||||
|
${renderClaims(context.current_claims, { withOrigin: true })}
|
||||||
|
<details>
|
||||||
|
<summary>과거 주장 (${context.past_claims.length})</summary>
|
||||||
|
${renderClaims(context.past_claims, { withOrigin: true })}
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<h2>페르소나 정보 ${state.personaReused ? '<span class="badge">요약·관점 재사용</span>' : ""}</h2>
|
||||||
|
<dl class="facts">
|
||||||
|
<dt>키워드</dt><dd>${escapeHtml(persona.keywords.join(", "))}</dd>
|
||||||
|
<dt>요약</dt><dd>${escapeHtml(persona.summary)}</dd>
|
||||||
|
<dt>토론 관점</dt><dd>${escapeHtml(persona.topic_view_point)}</dd>
|
||||||
|
<dt>발화 전략</dt><dd>${escapeHtml(persona.current_strategy)}</dd>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
<details>
|
||||||
|
<summary>원본 JSON</summary>
|
||||||
|
<pre>${escapeHtml(JSON.stringify(result, null, 2))}</pre>
|
||||||
|
</details>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
renderTimeline();
|
||||||
|
renderSide();
|
||||||
|
const editing = state.editingIndex !== null;
|
||||||
|
$("runButton").disabled = !state.draftTurns.length || editing;
|
||||||
|
$("manualButton").disabled = editing;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runStyleGuide() {
|
||||||
|
const input = buildInput();
|
||||||
|
const result = await postJson("/api/style-guide", input);
|
||||||
|
const firstGuide = guideForFirstDraft();
|
||||||
|
state.turns.push(...state.draftTurns.map((draft, draftIndex) => ({
|
||||||
|
...draft,
|
||||||
|
guide: draftIndex === 0 ? firstGuide : null,
|
||||||
|
})));
|
||||||
|
Object.assign(state, {
|
||||||
|
draftTurns: [],
|
||||||
|
pendingGuide: { speaker: input.next_speaker.name, guide: result.guide },
|
||||||
|
previousContext: result.context,
|
||||||
|
previousPersonaInfo: result.persona_info,
|
||||||
|
personaKey: personaKeyOf(input),
|
||||||
|
lastResult: result,
|
||||||
|
personaReused: input.previous_persona_info !== null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runDummyUtterance() {
|
||||||
|
const { speaker, guide } = state.pendingGuide;
|
||||||
|
const turn = await postJson("/api/dummy-utterance", {
|
||||||
|
speaker,
|
||||||
|
turns: plainTurns([...state.turns, ...state.draftTurns]),
|
||||||
|
persona_info: state.lastResult.persona_info,
|
||||||
|
guide,
|
||||||
|
context: state.lastResult.context,
|
||||||
|
});
|
||||||
|
state.draftTurns.push({ speaker: turn.speaker, text: turn.text, isDummy: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
function startManualDraft() {
|
||||||
|
state.draftTurns.push({ speaker: "", text: "", isDummy: false });
|
||||||
|
state.editingIndex = state.draftTurns.length - 1;
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function editDraft(draftIndex) {
|
||||||
|
state.editingIndex = draftIndex;
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveDraft() {
|
||||||
|
const speaker = $("draftSpeaker").value.trim();
|
||||||
|
const text = $("draftText").value.trim();
|
||||||
|
if (!speaker || !text) {
|
||||||
|
showError("최신 발화의 화자와 내용을 입력하세요.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const draft = state.draftTurns[state.editingIndex];
|
||||||
|
// 더미가 만든 발화를 사람이 고치면 더 이상 더미 발화로 표시하지 않는다.
|
||||||
|
const changed = speaker !== draft.speaker || text !== draft.text;
|
||||||
|
state.draftTurns[state.editingIndex] = { speaker, text, isDummy: draft.isDummy && !changed };
|
||||||
|
state.editingIndex = null;
|
||||||
|
showError("");
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelDraft() {
|
||||||
|
const draft = state.draftTurns[state.editingIndex];
|
||||||
|
if (!draft.speaker && !draft.text) state.draftTurns.splice(state.editingIndex, 1);
|
||||||
|
state.editingIndex = null;
|
||||||
|
showError("");
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSample() {
|
||||||
|
resetState();
|
||||||
|
showError("");
|
||||||
|
try {
|
||||||
|
const sample = await (await fetch("/api/sample")).json();
|
||||||
|
$("bookTitle").value = sample.book.title;
|
||||||
|
$("bookAuthor").value = sample.book.author;
|
||||||
|
$("topic").value = sample.topic;
|
||||||
|
$("speakerName").value = sample.next_speaker.name;
|
||||||
|
$("speakerKeywords").value = sample.next_speaker.persona.keywords.join(", ");
|
||||||
|
$("speakerGender").value = sample.next_speaker.persona.gender;
|
||||||
|
$("speakerAge").value = sample.next_speaker.persona.age ?? "";
|
||||||
|
state.draftTurns = sample.new_turns.map((turn) => ({ ...turn, isDummy: false }));
|
||||||
|
} catch (error) {
|
||||||
|
showError(`샘플 입력을 불러오지 못했습니다: ${error.message}`);
|
||||||
|
}
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
$("runButton").addEventListener("click", (event) => withBusy(event.currentTarget, runStyleGuide));
|
||||||
|
$("manualButton").addEventListener("click", startManualDraft);
|
||||||
|
$("resetButton").addEventListener("click", loadSample);
|
||||||
|
loadSample();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""시연용 웹 서버. 루트에서 `tests/run_demo.sh`로 실행한다."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from pydantic import ValidationError
|
||||||
|
from starlette.applications import Starlette
|
||||||
|
from starlette.requests import Request
|
||||||
|
from starlette.responses import FileResponse, JSONResponse
|
||||||
|
from starlette.routing import Route
|
||||||
|
|
||||||
|
from models.context import AnalysisInput
|
||||||
|
from services.utterance_guide import generate_style_guide
|
||||||
|
from tests.dummy_utterance import DummyUtteranceInput, generate_dummy_utterance
|
||||||
|
from tests.test_modules import BOOK, NEXT_SPEAKER, TOPIC, TURN_1, TURN_2, TURN_3
|
||||||
|
|
||||||
|
DEMO_HTML = Path(__file__).with_name("demo.html")
|
||||||
|
|
||||||
|
|
||||||
|
def _invalid_input(error: ValidationError) -> JSONResponse:
|
||||||
|
return JSONResponse({"error": json.loads(error.json(include_url=False))}, status_code=422)
|
||||||
|
|
||||||
|
|
||||||
|
async def index(request: Request) -> FileResponse:
|
||||||
|
return FileResponse(DEMO_HTML)
|
||||||
|
|
||||||
|
|
||||||
|
async def sample(request: Request) -> JSONResponse:
|
||||||
|
return JSONResponse({
|
||||||
|
"book": BOOK.model_dump(),
|
||||||
|
"topic": TOPIC,
|
||||||
|
"new_turns": [TURN_1.model_dump(), TURN_2.model_dump(), TURN_3.model_dump()],
|
||||||
|
"next_speaker": NEXT_SPEAKER.model_dump(),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
async def style_guide(request: Request) -> JSONResponse:
|
||||||
|
try:
|
||||||
|
analysis_input = AnalysisInput.model_validate(await request.json())
|
||||||
|
except ValidationError as error:
|
||||||
|
return _invalid_input(error)
|
||||||
|
result = await generate_style_guide(analysis_input)
|
||||||
|
return JSONResponse(result.model_dump())
|
||||||
|
|
||||||
|
|
||||||
|
async def dummy_utterance(request: Request) -> JSONResponse:
|
||||||
|
try:
|
||||||
|
dummy_input = DummyUtteranceInput.model_validate(await request.json())
|
||||||
|
except ValidationError as error:
|
||||||
|
return _invalid_input(error)
|
||||||
|
turn = await generate_dummy_utterance(dummy_input)
|
||||||
|
return JSONResponse(turn.model_dump())
|
||||||
|
|
||||||
|
|
||||||
|
async def server_error(request: Request, error: Exception) -> JSONResponse:
|
||||||
|
# 응답으로 메시지를 돌려주고, 트레이스백은 Starlette가 다시 올려 서버 로그에 남는다.
|
||||||
|
return JSONResponse({"error": f"{type(error).__name__}: {error}"}, status_code=500)
|
||||||
|
|
||||||
|
|
||||||
|
app = Starlette(
|
||||||
|
routes=[
|
||||||
|
Route("/", index),
|
||||||
|
Route("/api/sample", sample),
|
||||||
|
Route("/api/style-guide", style_guide, methods=["POST"]),
|
||||||
|
Route("/api/dummy-utterance", dummy_utterance, methods=["POST"]),
|
||||||
|
],
|
||||||
|
exception_handlers={Exception: server_error},
|
||||||
|
)
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""[테스트 전용 더미] 발화 가이드대로 다음 화자의 실제 발화를 만들어 낸다.
|
||||||
|
|
||||||
|
이 프로젝트의 MCP에는 포함되지 않는다. 실제 운영에서는 가이드를 받은 에이전트가 발화하는데,
|
||||||
|
시연에서 대화를 다음 턴으로 이어가기 위해 그 역할을 흉내 낸다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from models.context import DiscussionContext, DiscussionTurn
|
||||||
|
from models.persona import PersonaInfo
|
||||||
|
from models.utterance_guide import UtteranceGuide
|
||||||
|
from settings import settings
|
||||||
|
from utils.common_llm import StructuredLLM
|
||||||
|
|
||||||
|
DUMMY_UTTERANCE_PROMPT = """너는 독서토론 참여자다. 주어진 페르소나와 발화 가이드대로 지금 할 말을 쓴다.
|
||||||
|
- 가이드의 대상 주장, 의도, 핵심 메시지, 태도를 지킨다.
|
||||||
|
- 대화 기록의 마지막 발화에 자연스럽게 이어지는 말로 쓴다.
|
||||||
|
- 실제 토론에서 말하듯 두세 문장의 구어체로 쓴다.
|
||||||
|
- 화자 이름을 붙이지 않고 발화 내용만 쓴다."""
|
||||||
|
|
||||||
|
dummy_llm = StructuredLLM(settings.llm_model, settings.chatgpt_api_key)
|
||||||
|
|
||||||
|
|
||||||
|
class DummyUtteranceInput(BaseModel):
|
||||||
|
speaker: str
|
||||||
|
turns: list[DiscussionTurn] # 지금까지의 대화 기록
|
||||||
|
persona_info: PersonaInfo
|
||||||
|
guide: UtteranceGuide
|
||||||
|
context: DiscussionContext
|
||||||
|
|
||||||
|
|
||||||
|
class DummyUtterance(BaseModel):
|
||||||
|
text: str
|
||||||
|
|
||||||
|
|
||||||
|
async def generate_dummy_utterance(dummy_input: DummyUtteranceInput) -> DiscussionTurn:
|
||||||
|
persona = dummy_input.persona_info
|
||||||
|
guide = dummy_input.guide
|
||||||
|
prompt = "\n\n".join([
|
||||||
|
f"[참여자]\n{dummy_input.speaker}",
|
||||||
|
f"[페르소나]\n키워드: {', '.join(persona.keywords)}\n요약: {persona.summary}\n발화 전략: {persona.current_strategy}",
|
||||||
|
f"[현재 맥락]\n{dummy_input.context.summary}",
|
||||||
|
"[대화 기록]\n" + "\n".join(f"{turn.speaker}: {turn.text}" for turn in dummy_input.turns),
|
||||||
|
f"[발화 가이드]\n대상 주장: {guide.target_claim}\n의도: {guide.intent}\n핵심 메시지: {guide.key_message}\n태도: {guide.tone}",
|
||||||
|
])
|
||||||
|
result = await dummy_llm.ask(DummyUtterance, prompt, system=DUMMY_UTTERANCE_PROMPT)
|
||||||
|
# 프롬프트로 막아도 대화 기록 형식을 따라 "화자: "를 붙이는 경우가 있어 코드에서 떼어낸다.
|
||||||
|
text = re.sub(rf"^\s*{re.escape(dummy_input.speaker)}\s*:\s*", "", result.text)
|
||||||
|
return DiscussionTurn(speaker=dummy_input.speaker, text=text)
|
||||||
Executable
+6
@@ -0,0 +1,6 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 시연용 웹 서버를 띄운다. 기본은 이 PC에서만 접속된다.
|
||||||
|
# 다른 기기에서 접속하려면 HOST=0.0.0.0 으로 실행한다. 같은 네트워크의 누구나 OpenAI 비용을 쓸 수 있게 되니 주의.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
exec uv run uvicorn tests.demo_server:app --host "${HOST:-127.0.0.1}" --port "${PORT:-8000}"
|
||||||
@@ -57,7 +57,7 @@ def _assert_context_carried_over(previous: DiscussionContext, updated: Discussio
|
|||||||
|
|
||||||
async def test_context_extraction() -> DiscussionContext:
|
async def test_context_extraction() -> DiscussionContext:
|
||||||
first = await extract_context(
|
first = await extract_context(
|
||||||
ContextExtractionInput(topic=TOPIC, book=BOOK, new_turn=TURN_1)
|
ContextExtractionInput(topic=TOPIC, book=BOOK, new_turns=[TURN_1])
|
||||||
)
|
)
|
||||||
_print("맥락 추출 1턴 (구 맥락 없음)", first)
|
_print("맥락 추출 1턴 (구 맥락 없음)", first)
|
||||||
assert not first.past_claims, "첫 턴인데 과거 주장이 있음"
|
assert not first.past_claims, "첫 턴인데 과거 주장이 있음"
|
||||||
@@ -66,7 +66,7 @@ async def test_context_extraction() -> DiscussionContext:
|
|||||||
ContextExtractionInput(
|
ContextExtractionInput(
|
||||||
topic=TOPIC,
|
topic=TOPIC,
|
||||||
book=BOOK,
|
book=BOOK,
|
||||||
new_turn=TURN_2,
|
new_turns=[TURN_2],
|
||||||
previous_turns=[TURN_1],
|
previous_turns=[TURN_1],
|
||||||
previous_context=first,
|
previous_context=first,
|
||||||
)
|
)
|
||||||
@@ -96,7 +96,7 @@ async def test_style_guide(context: DiscussionContext) -> None:
|
|||||||
AnalysisInput(
|
AnalysisInput(
|
||||||
topic=TOPIC,
|
topic=TOPIC,
|
||||||
book=BOOK,
|
book=BOOK,
|
||||||
new_turn=TURN_3,
|
new_turns=[TURN_3],
|
||||||
previous_turns=[TURN_1, TURN_2],
|
previous_turns=[TURN_1, TURN_2],
|
||||||
previous_context=context,
|
previous_context=context,
|
||||||
next_speaker=NEXT_SPEAKER,
|
next_speaker=NEXT_SPEAKER,
|
||||||
|
|||||||
Reference in new issue
Block a user