1. 사용자 프롬프트에 API 도구 클릭 및 프롬프트 작성
  2. LLM 이 tool calling
  3. /api/critique API 호출
# api_critique 함수

@app.post("/api/critique", operation_id="api_critique")
async def api_critique(req: CritiqueRequest):
    opts = req.options or CritiqueOptions()
    # 입력 원고 저장 (항상 수행)
    work_path = _save_critique_object(req.title, req.content)

    # 기준 로드 및 LLM 합평 생성
    criteria = _load_critique_criteria()
    critique_text: str
    if opts.chunked_critique:
        max_chars = opts.chunk_max_chars or CRITIQUE_CHUNK_MAX_CHARS
        max_parts = opts.max_parts or CRITIQUE_CHUNK_MAX_PARTS
        chunks = _split_critique_chunks(req.content, max_chars=max_chars, max_parts=max_parts)
        chunk_outputs: list[str] = []
        part_summaries: list[str] = []
        total_parts = len(chunks)

        for idx, chunk in enumerate(chunks, start=1):
            chunk_prompt = _build_critique_chunk_prompt(
                req.title,
                chunk,
                criteria,
                part_index=idx,
                total_parts=total_parts,
                extra_instruction=req.extra_instruction,
            )
            chunk_text = await call_llm(chunk_prompt)
            chunk_outputs.append(chunk_text)
            summary = _extract_chunk_summary(chunk_text) or _fallback_chunk_summary(chunk)
            part_summaries.append(summary)

        overall_prompt = _build_critique_overall_prompt(
            req.title,
            part_summaries,
            criteria,
            extra_instruction=req.extra_instruction,
        )
        overall_text = await call_llm(overall_prompt)
        critique_text = _assemble_chunked_critique(chunk_outputs, overall_text)
    else:
        prompt = _build_critique_prompt(req.title, req.content, criteria, extra_instruction=req.extra_instruction)
        critique_text = await call_llm(prompt)

    critique_path: str | None = None

    # ✅ response에 반환할 critique md(헤더 포함)를 만든다
    now_iso = datetime.now().isoformat()
    critique_yaml_header = {
        "type": "critique",
        "object_title": req.title,
        "created_at": now_iso,
        "updated_at": now_iso,
        "source_object_file": work_path,
        "usage": ["critique"],
    }
    critique_md_with_header = "---\n" + yaml.safe_dump(
        critique_yaml_header, allow_unicode=True, sort_keys=False
    ) + "---\n\n" + critique_text

    # ✅ 검증 (front-matter + 주요 필드)
    meta, _, has_fm = extract_front_matter(critique_md_with_header)
    if not has_fm:
        raise ValueError("critique output missing front-matter (server bug)")
    validate_critique_front_matter(meta)

    if opts.save_critique or (opts.save_work is True):
        # 기존 저장 로직 유지 (저장 파일도 동일한 헤더 포함)
        critique_path = _save_critique_result(req.title, critique_text, work_path)

    return standard_response(
        success=True,
        message="ok",
        data={
            "critique": critique_md_with_header,  # ✅ 이제 헤더 포함 md로 반환
            "critique_file_path": critique_path,
            "work_file_path": work_path,
        },
        error=None,
    )
  1. 입력 원고 저장
# api_critique 함수 내부

    opts = req.options or CritiqueOptions()
    # 입력 원고 저장 (항상 수행)
    work_path = _save_critique_object(req.title, req.content)
    
# _save_critique_object 함수

def _save_critique_object(title: str, content: str) -> str:
    now_iso = datetime.now().isoformat()
    yaml_header = {
        "type": "critique_object",
        "title": title,
        "created_at": now_iso,
        "updated_at": now_iso,
        "usage": ["critique", "reference"],
    }
    md = "---\n" + yaml.safe_dump(yaml_header, allow_unicode=True, sort_keys=False) + "---\n\n" + content
    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
    safe_title = slugify_filename(title)
    path = CRITIQUE_OBJECTS_ROOT / f"{ts}_{safe_title}.md"
    path.write_text(md, encoding="utf-8")
    return str(path)
    
# 파일 저장 시 이름 : slugify_filename 함수

def slugify_filename(text: str) -> str:
    text = text.strip().replace(" ", "")
    for ch in "/\\?%*:|\"<>":
        text = text.replace(ch, "-")
    return text or "note"

  1. 합평 기준 로드
# api_critique 함수 내부

		# 기준 로드 및 LLM 합평 생성
    criteria = _load_critique_criteria()
    critique_text: str
    if opts.chunked_critique:
        max_chars = opts.chunk_max_chars or CRITIQUE_CHUNK_MAX_CHARS
        max_parts = opts.max_parts or CRITIQUE_CHUNK_MAX_PARTS
        chunks = _split_critique_chunks(req.content, max_chars=max_chars, max_parts=max_parts)
        chunk_outputs: list[str] = []
        part_summaries: list[str] = []
        total_parts = len(chunks)

            
 # _load_critique_criteria 함수
 
	def _load_critique_criteria() -> str:
    if CRITIQUE_CRITERIA_PATH.exists():
        try:
            return CRITIQUE_CRITERIA_PATH.read_text(encoding="utf-8")
        except Exception:
            return CRITIQUE_FALLBACK_RULES
    return CRITIQUE_FALLBACK_RULES
 
 # _split_critique_chunks 함수
 
 def _split_critique_chunks(text: str, max_chars: int, max_parts: int) -> list[str]:
    normalized = (text or "").strip()
    if not normalized:
        return [""]
    paragraphs = re.split(r"\n\s*\n", normalized)
    chunks: list[str] = []
    current: list[str] = []
    current_len = 0

    for para in paragraphs:
        para = para.strip()
        if not para:
            continue
        if len(para) > max_chars:
            if current:
                chunks.append("\n\n".join(current))
                if len(chunks) >= max_parts:
                    return chunks
                current = []
                current_len = 0
            start = 0
            while start < len(para):
                part = para[start:start + max_chars]
                chunks.append(part)
                if len(chunks) >= max_parts:
                    return chunks
                start += max_chars
            continue

        extra_len = len(para) + (2 if current else 0)
        if current_len + extra_len > max_chars:
            chunks.append("\n\n".join(current))
            if len(chunks) >= max_parts:
                return chunks
            current = [para]
            current_len = len(para)
        else:
            current.append(para)
            current_len += extra_len

    if current and len(chunks) < max_parts:
        chunks.append("\n\n".join(current))

    return chunks
 
  1. LLM 합평 생성
# api_critique 함수 내부
				# 분할 합평 시
        for idx, chunk in enumerate(chunks, start=1):
            chunk_prompt = _build_critique_chunk_prompt(
                req.title,
                chunk,
                criteria,
                part_index=idx,
                total_parts=total_parts,
                extra_instruction=req.extra_instruction,
            )
            chunk_text = await call_llm(chunk_prompt)
            chunk_outputs.append(chunk_text)
            summary = _extract_chunk_summary(chunk_text) or _fallback_chunk_summary(chunk)
            part_summaries.append(summary)

				# 전체 합평
				overall_prompt = _build_critique_overall_prompt(
            req.title,
            part_summaries,
            criteria,
            extra_instruction=req.extra_instruction,
        )
        overall_text = await call_llm(overall_prompt)
        critique_text = _assemble_chunked_critique(chunk_outputs, overall_text)
    else:
        prompt = _build_critique_prompt(req.title, req.content, criteria, extra_instruction=req.extra_instruction)
        critique_text = await call_llm(prompt)

# _build_critique_chunk_prompt 함수 : LLM 호출
 
 def _build_critique_chunk_prompt(
    title: str,
    content: str,
    criteria: str,
    part_index: int,
    total_parts: int,
    extra_instruction: str | None = None,
) -> str:
    extra = extra_instruction.strip() if extra_instruction else ""
    extra_block = f"\n\n[추가 지시사항]\n{extra}" if extra else ""
    return f"""
너는 단편소설 합평 전문 에디터다. 아래 구조를 반드시 지켜 출력하라.
이 파트는 원고의 일부이므로, 이 파트의 내용에만 근거해 평가하라.

[합평 기준]
{criteria}

[입력 원고 제목]
{title}

[입력 원고 파트 {part_index}/{total_parts}]
{content}
{extra_block}

--- 출력 형식 (반드시 이 순서로) ---
(0) 파트 요약: 2~3문장으로 현재 파트에서 무슨 일이 벌어지는지 요약
(1) 한 줄 총평
(2) 항목별 점수: 각 항목 10점 만점, 근거로 원고 문장/문단을 인용
(3) 개선 제안: 구체적으로 몇 라인/어느 문단을 어떤 표현·묘사·방향으로 수정할지 제안 (장면/문단 단위)
(4) 기준 준수 여부 체크리스트: 합평기준규칙.md 항목을 그대로 나열하고 각 항목에 대해 준수/미흡 + 한 줄 근거
""".strip()

 # _extract_chunk_summary 함수 : 분할 합평 시 파트별 요약
 
 def _extract_chunk_summary(text: str) -> str | None:
    if not text:
        return None
    match = re.search(r"^\(0\)\s*파트 요약[::]?\s*(.+)$", text, re.M)
    if match:
        return match.group(1).strip()
    match = re.search(r"^파트 요약[::]?\s*(.+)$", text, re.M)
    if match:
        return match.group(1).strip()
    return None
 
 # _fallback_chunk_summary 함수 : 미분할 합평 시 파트요약 없음
 
 def _fallback_chunk_summary(content: str, max_chars: int = 300) -> str:
    trimmed = re.sub(r"\s+", " ", (content or "").strip())
    return trimmed[:max_chars] if trimmed else "요약 없음"
    
# _build_critique_overall_prompt
 
def _build_critique_overall_prompt(
    title: str,
    part_summaries: list[str],
    criteria: str,
    extra_instruction: str | None = None,
) -> str:
    summary_lines = "\n".join([f"- 파트 {idx}: {summary}" for idx, summary in enumerate(part_summaries, start=1)])
    extra = extra_instruction.strip() if extra_instruction else ""
    extra_block = f"\n\n[추가 지시사항]\n{extra}" if extra else ""
    return f"""
너는 단편소설 합평 전문 에디터다. 아래 구조를 반드시 지켜 출력하라.
아래 파트 요약을 바탕으로 작품 전체의 구조/전개/정서 흐름을 평가하라.

[합평 기준]
{criteria}

[입력 원고 제목]
{title}

[파트 요약]
{summary_lines}
{extra_block}

--- 출력 형식 (반드시 이 순서로) ---
(1) 한 줄 총평
(2) 항목별 점수: 각 항목 10점 만점, 근거로 파트 요약을 인용
(3) 개선 제안: 작품 전체 구조/전개/정서 흐름 중심으로 구체적 수정 방향 제안
(4) 기준 준수 여부 체크리스트: 합평기준규칙.md 항목을 그대로 나열하고 각 항목에 대해 준수/미흡 + 한 줄 근거
""".strip() 

# call_llm

async def call_llm(prompt: str) -> str:
    """
    WAAI 백엔드용 공통 LLM 호출 함수
    - LLM_BACKEND=ollama  : Ollama /api/generate
    - LLM_BACKEND=openai  : OpenAI 또는 호환 서버 /v1/chat/completions
    """
    backend = LLM_BACKEND

    # 1) Ollama
    if backend == "ollama":
        async with httpx.AsyncClient(timeout=120) as client:
            resp = await client.post(
                f"{OLLAMA_URL}/api/generate",
                json={
                    "model": MODEL_NAME,
                    "prompt": prompt,
                    "stream": False,
                },
            )
            resp.raise_for_status()
            data = resp.json()
            return data.get("response", "")

    # 2) OpenAI / 호환 서버
    elif backend == "openai":
        if not OPENAI_API_KEY:
            raise RuntimeError("OPENAI_API_KEY 가 설정되어 있지 않습니다.")

        headers = {
            "Authorization": f"Bearer {OPENAI_API_KEY}",
            "Content-Type": "application/json",
        }
        payload = {
            "model": OPENAI_MODEL,
            "messages": [
                {"role": "user", "content": prompt},
            ],
        }
        async with httpx.AsyncClient(timeout=120) as client:
            resp = await client.post(
                f"{OPENAI_BASE_URL}/chat/completions",
                headers=headers,
                json=payload,
            )
            resp.raise_for_status()
            data = resp.json()
            return data["choices"][0]["message"]["content"]

    else:
        raise RuntimeError(f"지원하지 않는 LLM_BACKEND: {backend}")

# _assemble_chunked_critique : 분할 합평 시 모든 합평 결과를 붙여주는 부분

def _assemble_chunked_critique(chunk_outputs: list[str], overall_text: str) -> str:
    parts: list[str] = ["## 파트별 합평"]
    total_parts = len(chunk_outputs)
    for idx, text in enumerate(chunk_outputs, start=1):
        body = (text or "").strip()
        parts.append(f"### 파트 {idx}/{total_parts}\n{body}")
    parts.append("---\n\n## 전체 합평\n" + (overall_text or "").strip())
    return "\n\n".join(parts).strip()
  1. 응답에 반환할 합평 md 생성 및 최종 결과 저장