Files
2nd/10_Wiki/Topics/Domain_Programming/AI_and_ML/Natural-Language-Generation-NLG.md
T
Antigravity Agent c24165b8bc refactor(topics): 멀티 에이전트용 지식 재편 — _Common(공통 기본기) + Domain_* 구조
에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게
[공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류.
문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인).

- Topic_Programming → Domain_Programming (내부 구조 보존)
- Topic_Graphic → Domain_Design
- Topic_Business → Domain_Product
- Topic_General → Domain_General
- _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning),
  Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing)
- 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서)
- 빈 폴더 정리 (memory/procedures)
- 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 11:05:56 +09:00

6.0 KiB
Raw Blame History

id, title, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-natural-language-generation-nlg Natural Language Generation (NLG) verified wiki-2026-0508-natural-language-generation-nlg
NLG
Text Generation
Natural-Language-Generation
none A 0.93 applied
nlp
nlg
text-generation
llm
evaluation
2026-05-10 pending
python
transformers
openai
anthropic
sacrebleu

Natural Language Generation (NLG)

한 줄 정의

구조화된 입력(데이터·표·의도)이나 unstructured prompt에서 자연어 텍스트를 생성하는 NLP 하위 분야. 2020년대 LLM 등장 이후 사실상 "프롬프트 → LLM 호출"이 default가 되며, 전통적 template/규칙 기반은 하이브리드 fallback 역할.

핵심

세대 구분

  • Template-based: 슬롯 채우기 ("오늘 {city} 기온 {temp}°C"). 정확·예측가능, 다양성 0.
  • Statistical (n-gram, HMM): 2010년대 이전. 현재는 거의 사용 X.
  • Neural seq2seq (LSTM/Transformer): 20142019. 요약·번역 SOTA.
  • LLM-based (GPT/Claude/Llama 계열): 2020+. zero/few-shot, instruction tuning.

파이프라인 (전통)

content determination → text structuring → sentence aggregation → lexicalization → referring expression generation → linguistic realization. LLM 시대에는 이 단계가 implicit.

평가 지표

  • BLEU — n-gram overlap. 번역에서 유래.
  • ROUGE — recall 기반. 요약 표준.
  • METEOR — synonym/stem 고려.
  • BERTScore — embedding cosine. semantic.
  • BLEURT, COMET — learned metric.
  • G-Eval / LLM-as-judge — LLM이 채점.
  • Human eval — fluency, faithfulness, relevance, factuality.

응용

요약, 번역, 데이터→문장(report generation), 챗봇, 코드 생성, 광고 문안, 시나리오, RAG 답변, 데이터 증강.

💻 패턴

Template fallback

def render_weather(city, temp, cond):
    return f"{city}의 현재 기온은 {temp}°C, 날씨는 {cond}입니다."

Hugging Face 생성

from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
mdl = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B-Instruct",
                                           device_map="auto")
ids = tok.apply_chat_template(
    [{"role":"user","content":"한 문장 요약: ..."}],
    return_tensors="pt").to(mdl.device)
out = mdl.generate(ids, max_new_tokens=128, temperature=0.7, top_p=0.9)
print(tok.decode(out[0][ids.shape[-1]:], skip_special_tokens=True))

Anthropic API (modern default)

import anthropic
client = anthropic.Anthropic()
msg = client.messages.create(
    model="claude-opus-4-7",
    max_tokens=512,
    system="간결하고 사실에 기반한 한국어로 답하라.",
    messages=[{"role":"user","content":"분기 매출표 → 한 문단 요약: ..."}],
)
print(msg.content[0].text)

Sampling 제어

# 결정론적 (사실 답변)
generate(temperature=0.0)
# 다양성 (창작)
generate(temperature=0.9, top_p=0.95)
# 반복 억제
generate(repetition_penalty=1.1, no_repeat_ngram_size=3)

BLEU/ROUGE 평가

import sacrebleu
from rouge_score import rouge_scorer

bleu = sacrebleu.corpus_bleu(hyps, [refs])
print(bleu.score)

scorer = rouge_scorer.RougeScorer(['rouge1','rougeL'], use_stemmer=True)
scores = [scorer.score(r, h) for r, h in zip(refs, hyps)]

BERTScore

from bert_score import score
P, R, F1 = score(hyps, refs, lang="ko", rescale_with_baseline=True)
print(F1.mean().item())

LLM-as-judge (G-Eval 스타일)

JUDGE = """다음 요약의 사실 정확도를 1-5로 평가하라.
원문: {src}
요약: {hyp}
JSON으로만: {{"score": int, "reason": str}}"""

def judge(src, hyp):
    r = client.messages.create(
        model="claude-opus-4-7", max_tokens=200,
        messages=[{"role":"user","content":JUDGE.format(src=src, hyp=hyp)}])
    return json.loads(r.content[0].text)

결정 기준

상황 추천
고정 양식·법적 정확성 Template
데이터 → 보고서 (수치 보존) Template + LLM rewrite
일반 자유 텍스트 LLM (Claude/GPT)
비용 민감, on-prem open-weight LLM (Llama/Qwen)
평가 — 번역 BLEU + COMET
평가 — 요약 ROUGE + BERTScore + LLM-judge
평가 — open-ended LLM-as-judge + 인간 spot check

기본값: LLM 호출, 사실 정확성 위험 시 template hybrid.

🔗 Graph

🤖 LLM 활용

언제: NLG 작업 자체(요약·번역·rewrite), 평가 자동화(LLM-as-judge), prompt 설계, hallucination 감지 보조.

언제 X: 수치·법률·의료 등 사실 정확성이 절대적인 출력에 LLM 단독 의존. 반드시 template/grounding/검증 layer 추가.

안티패턴

  • BLEU 단일 지표로 요약·자유생성 평가 → 의미 차이 못 잡음.
  • temperature=1.0+ 로 사실 응답 생성 → hallucination 폭증.
  • LLM-as-judge에 같은 모델 사용 (self-preference bias).
  • Template 없이 수치 그대로 자연어로 → 잘못된 반올림·단위 누락.
  • 평가셋 누출 (test set이 학습에 들어감) — 평가 무의미.

🧪 검증 / 중복

Verified source: Reiter & Dale Building NLG Systems, Hugging Face transformers docs, Anthropic/OpenAI API 문서, ACL/EMNLP 평가 논문, BERTScore (Zhang et al. 2020), G-Eval (Liu et al. 2023). 신뢰도 A.

Large-Language-Models 와 겹치지만 NLG는 태스크/평가 관점, LLM은 모델/시스템 관점으로 분리.

🕓 Changelog

  • 2026-05-08 Phase 1 — 초기 stub.
  • 2026-05-10 Manual cleanup — FULL 재작성. 세대 구분, 평가 6종, 코드 7개(template/HF/Anthropic/sampling/BLEU/BERTScore/judge).