광고 자리 모집 중 · 제휴 문의

Anthropic Claude Citations API 연동 실전 가이드: 정확한 구문 사실 접지, 문자 단위 인덱싱 및 RAG 검증 파이프라인

Ana Flávia Magalhães · 365Finds Editorial
Wiki 문서 88,650편 수록

내 AI에서 365 Wiki 사용하기

아래 프롬프트를 복사해 평소 사용하는 AI에 붙여넣고 바로 질문하세요.

전체 Skill 다운로드

먼저 프롬프트로 체험해 보세요. 365 Wiki를 자주 쓴다면 전체 365Wiki Skill을 설치해 매번 붙여넣는 수고를 줄일 수 있습니다. 평소 쓰는 AI가 없다면 Gemini나 Microsoft Copilot 웹 버전도 사용할 수 있습니다.

프롬프트 엔지니어링을 통해 모델에게 출처 인용을 요구하는 방식은 언제나 불완전한 타협안이었습니다. 법률 분석, 금융 감사, 규제 컴플라이언스 등 오류를 허용할 수 없는 핵심 업무에서 검색 증강 생성(RAG) 시스템을 구축할 때, 많은 개발팀은 "각 대괄호 안에 정확한 문서명, 페이지 번호 및 원문 인용구를 기재하라"는 식의 프롬프트를 작성해 왔습니다.

그러나 프로덕션 환경에서 마주하는 현실은 치명적인 은닉 환각(Hallucination)입니다. 모델은 그럴듯해 보이는 가짜 페이지 번호를 날조하거나, 원문 인용처럼 꾸며내면서 핵심 단어를 임의로 변조하고, 전혀 관련 없는 문단에 사실적 주장을 억지로 연결합니다. 사내 파일럿 단계에서는 문제없어 보일지라도, 규제 기관의 감사나 법적 증거 제시, 신용 심사 프로세스에서 이러한 허위 증거 사슬은 심각한 운영 위험을 초래합니다.

365Finds는 Anthropic Claude의 공식 Citations API가 생성형 AI의 결정론적(Deterministic) 신뢰성을 확보하는 핵심 전환점이라고 판단합니다. 프롬프트에 의존해 확률적으로 다음 토큰을 생성하는 대신, Citations API는 출처 추적을 추론 및 토큰화 기반 계층으로 끌어내렸습니다. Claude는 생성된 텍스트 블록과 함께 엄격한 문자 단위 오프셋(start_char_index, end_char_index), 페이지 번호, 서버에서 직접 추출한 정확한 원문 슬라이스를 구조화된 객체 형태로 반환합니다.

본 가이드에서는 365Finds의 시각에서 Claude Citations API의 동작 원리, 문자 단위 인덱싱 메커니즘, 프로덕션급 파이썬 연동 코드, 그리고 백엔드 사실 검증 파이프라인 구축법을 상세히 다룹니다.


아키텍처: 결정론적 포인터와 프롬프트 기반 환각의 본질적 차이

Citations API의 기술적 가치를 이해하려면 확률적 생성과 결정론적 소프트웨어 공학의 경계를 명확히 구분해야 합니다.

과거 프롬프트로 Claude에게 [문서 1, 14페이지: "매출은 전년 대비 14% 증가했다"]라는 인용문을 작성하도록 지시했을 때, 해당 인용구의 모든 토큰은 언어 모델의 확률 분포에 종속되었습니다. 모델 내부의 어텐션이 미세하게 흔들리는 순간 페이지 번호와 인용 문구는 왜곡됩니다.

반면 Anthropic Citations API에서 인용 정보는 자유 생성 텍스트 토큰이 아닙니다. 텍스트 블록에 결합된 독립적인 구조화 메타데이터 객체로 반환됩니다.

+-------------------------------------------------------------------+
|                           사용자 질의 요청                        |
|     "3분기 영업이익률은 얼마이며, 하락을 유발한 핵심 원인은?"     |
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|                     문서 입력 블록 (Payload)                      |
|  - type: "document"                                               |
|  - source: { type: "text", media_type: "text/plain", data: ... }  |
|  - citations: { "enabled": true }                                 |
|  - cache_control: { "type": "ephemeral" }                         |
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|               Anthropic Claude 네이티브 추론 파이프라인           |
|  - 원본 문서에 대한 서버 측 문장 단위 결정론적 청킹               |
|  - 생성 토큰과 문서 위치 포인터 간의 내부 어텐션 정렬             |
|  - 서버 측에서 원문 추출 및 구조화된 인용 객체 생성               |
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|                      구조화된 응답 텍스트 블록                    |
|  텍스트 블록 1: "영업이익률은 18.2%로 축소되었습니다 "           |
|    └── 인용 메타데이터: char_location [412:478] -> "영업이익률..."|
|  텍스트 블록 2: "주요 원인은 국제 간선 물류비 급증 때문입니다."   |
|    └── 인용 메타데이터: char_location [502:580] -> "해상 운임..."|
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|                    백엔드 결정론적 검증 엔진                      |
|  어설션 검증: raw_doc[start_char_index:end_char_index] == cited_text|
|  인용이 결여된 수치 주장이나 핵심 사실을 즉각 감지 및 차단        |
+-------------------------------------------------------------------+

비용 구조의 결정적 이점: 인용 원문에 출력 토큰 미과금

엔터프라이즈 환경에서 많은 아키텍트들이 간과하는 비용상 장점이 있습니다. API가 구조화하여 반환하는 cited_text 원문 문자열은 출력 토큰(Output Tokens) 요금에 일절 합산되지 않습니다.

프롬프트를 통해 모델에게 장문의 법조문이나 계약서 조항을 그대로 인용하도록 강제하면, 컨텍스트에서 복사해 온 모든 단어에 대해 출력 토큰 요금이 부과됩니다. 대규모 문서 처리 시 이는 심각한 비용 누수를 유발합니다. Citations API의 경우 Anthropic 서버가 내부 위치 마커를 해석한 후 원문에서 cited_text를 추출해 메타데이터로 제공하므로 출력 토큰 요금이 발생하지 않습니다. 또한 멀티턴 대화에서 이 필드를 다시 컨텍스트에 전달할 때도 입력 토큰으로 재청구되지 않습니다.


3대 문서 유형 및 인덱싱 기준

Claude Citations API는 세 가지 문서 입력 형식을 지원하며, 각각 서로 다른 인덱싱 단위를 제공합니다:

문서 유형입력 형식서버 측 청킹 단위인용 객체 타입(Type)위치 오프셋 기준
일반 텍스트 (Plain Text)인라인 text/plain 문자열 또는 Files API file_id문장(Sentence) 단위 자동 분할char_locationstart_char_index (0부터 시작, 포함) ~ end_char_index (미포함)
PDF 문서Base64 인코딩, HTTPS URL 또는 file_id페이지 내 텍스트 추출 후 문장 분할page_locationstart_page_number (1부터 시작, 포함) ~ end_page_number (미포함)
커스텀 콘텐츠 (Custom Content)개발자 정의 콘텐츠 블록 배열추가 분할 없음 (개발자의 청크 단위 엄격 유지)content_block_locationstart_block_index (0부터 시작, 포함) ~ end_block_index (미포함)

365Finds는 검증 정밀도에 맞춰 문서 형식을 선택할 것을 권장합니다:


프로덕션 연동: Python 구현 예제

아래 코드는 기업 여신 협약서를 전달하고, Citations API를 활성화하며, Prompt Caching을 적용해 비용을 절감하는 동시에 정확한 문자 오프셋을 추출하는 실전 파이썬 예제입니다.

import os
import anthropic

client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))

credit_agreement_text = """
CREDIT AGREEMENT SECTION 4.02: FINANCIAL COVENANTS.
The Borrower shall not permit the Consolidated Leverage Ratio as of the end of any 
fiscal quarter of the Borrower to exceed 3.50 to 1.00; provided that, following any 
Material Acquisition, such maximum ratio shall increase to 4.00 to 1.00 for the four 
consecutive fiscal quarters immediately following the consummation of such acquisition.
The Borrower shall maintain a minimum Interest Coverage Ratio of not less than 2.50 to 1.00 
at all times during the term of this Facility.
"""

response = client.messages.create(
    model="claude-sonnet-4-5-20250929",
    max_tokens=2048,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "document",
                    "source": {
                        "type": "text",
                        "media_type": "text/plain",
                        "data": credit_agreement_text,
                    },
                    "title": "Facility Credit Agreement - Exhibit A",
                    "context": "Governing syndicated lending documentation dated January 15, 2025.",
                    "citations": {"enabled": True},
                    "cache_control": {"type": "ephemeral"},  # 장문 문서 캐싱 적용
                },
                {
                    "type": "text",
                    "text": (
                        "What is the maximum allowed Consolidated Leverage Ratio, "
                        "and does it change after an acquisition?"
                    ),
                },
            ],
        }
    ],
)

# 구조화된 인용 객체 파싱
for block in response.content:
    if block.type == "text":
        print(f"\n[생성된 텍스트]:\n{block.text}")
        if hasattr(block, "citations") and block.citations:
            for citation in block.citations:
                if citation.type == "char_location":
                    print("  --> [사실 접지 메타데이터]:")
                    print(f"      문서 인덱스: {citation.document_index} ({citation.document_title})")
                    print(f"      문자 범위: [{citation.start_char_index}:{citation.end_char_index}]")
                    print(f"      인용된 실제 원문: \"{citation.cited_text.strip()}\"")

반환된 페이로드 구조

위 코드를 실행하면 Claude는 응답을 문맥별 텍스트 블록으로 세분화하여, 실제 출처 근거가 존재하는 명제에만 인용 메타데이터를 연결합니다:

{
  "content": [
    {
      "type": "text",
      "text": "The Borrower's Consolidated Leverage Ratio cannot exceed "
    },
    {
      "type": "text",
      "text": "3.50 to 1.00 as of the end of any fiscal quarter.",
      "citations": [
        {
          "type": "char_location",
          "document_index": 0,
          "document_title": "Facility Credit Agreement - Exhibit A",
          "start_char_index": 52,
          "end_char_index": 216,
          "cited_text": "The Borrower shall not permit the Consolidated Leverage Ratio as of the end of any \nfiscal quarter of the Borrower to exceed 3.50 to 1.00;"
        }
      ]
    },
    {
      "type": "text",
      "text": " However, following a Material Acquisition, this limit increases to "
    },
    {
      "type": "text",
      "text": "4.00 to 1.00 for the next four consecutive fiscal quarters.",
      "citations": [
        {
          "type": "char_location",
          "document_index": 0,
          "document_title": "Facility Credit Agreement - Exhibit A",
          "start_char_index": 217,
          "end_char_index": 384,
          "cited_text": "provided that, following any \nMaterial Acquisition, such maximum ratio shall increase to 4.00 to 1.00 for the four \nconsecutive fiscal quarters immediately following the consummation of such acquisition."
        }
      ]
    }
  ]
}

일반 접속사에는 불필요한 인용이 붙지 않고, 핵심 재무 비율 수치와 법적 조건에만 오프셋이 정확히 결합된 점을 확인할 수 있습니다.


백엔드 결정론적 RAG 검증 엔진 구축

API로부터 인용 데이터를 수신하는 것은 절반에 불과합니다. 금융 및 규제 준수 시스템에서는 모델이 생성한 답변을 사용자에게 노출하기 전에 제로 트러스트(Zero-Trust) 감사 파이프라인을 통과시켜야 합니다.

365Finds가 제안하는 검증 체계는 두 가지 핵심 방어벽으로 구성됩니다:

  1. 부분 문자열 패리티 검증 (Sub-string Parity): 메모리 상에서 원본 텍스트를 raw_documents[doc_idx][start_char:end_char]로 직접 슬라이싱하여 citation.cited_text와 1비트의 오차도 없이 일치하는지 단언(Assert)합니다.
  2. 미인용 핵심 사실 필터링 (Grounding Coverage): 수치나 법적 확약이 포함된 문장에 유효한 인용이 결합되어 있는지 검사하고, 근거 없는 주장을 차단합니다.
from typing import List, Dict, Any

class GroundingVerificationError(Exception):
    pass

class RAGCitationAuditor:
    def __init__(self, raw_documents: List[str]):
        self.raw_documents = raw_documents

    def verify_message_response(self, response_content: List[Any]) -> Dict[str, Any]:
        total_text_blocks = 0
        cited_text_blocks = 0
        verified_citations = 0

        for block in response_content:
            if block.type != "text":
                continue
            
            total_text_blocks += 1
            citations = getattr(block, "citations", None)

            if citations:
                cited_text_blocks += 1
                for cit in citations:
                    if cit.type == "char_location":
                        doc_idx = cit.document_index
                        start = cit.start_char_index
                        end = cit.end_char_index
                        expected_text = cit.cited_text

                        if doc_idx >= len(self.raw_documents):
                            raise GroundingVerificationError(f"유효하지 않은 문서 인덱스: {doc_idx}")

                        source_slice = self.raw_documents[doc_idx][start:end]

                        if source_slice != expected_text:
                            raise GroundingVerificationError(
                                f"인용 슬라이스 불일치! 원본 슬라이스: '{source_slice}' != 인용문: '{expected_text}'"
                            )
                        
                        verified_citations += 1

        coverage_ratio = (
            cited_text_blocks / total_text_blocks if total_text_blocks > 0 else 0.0
        )

        return {
            "status": "PASS",
            "total_blocks": total_text_blocks,
            "cited_blocks": cited_text_blocks,
            "verified_citations": verified_citations,
            "grounding_coverage_ratio": round(coverage_ratio, 3),
        }

이 연산은 순수 메모리 슬라이싱($\mathcal{O}(1)$)으로 수행되므로 요청당 1밀리초도 걸리지 않으며, 전체 지연 시간에 영향을 미치지 않습니다.


스트리밍 환경에서의 citations_delta 처리

실시간 인터페이스에서는 전체 답변 생성이 완료될 때까지 기다릴 필요가 없습니다. Anthropic의 SSE 스트림은 content_block_delta 이벤트 내에 citations_delta를 포함하여 전송합니다:

with client.messages.stream(
    model="claude-sonnet-4-5-20250929",
    max_tokens=1024,
    messages=[...],
) as stream:
    for event in stream:
        if event.type == "content_block_delta":
            delta = event.delta
            if delta.type == "text_delta":
                sys.stdout.write(delta.text)
                sys.stdout.flush()
            elif delta.type == "citations_delta":
                citation = delta.citation
                print(f"\n[스트리밍 인용 수신: {citation.cited_text[:25]}...]")

프론트엔드 연동: 정규표현식 없는 고속 텍스트 하이라이트

수백 페이지에 달하는 문서 뷰어에서 정규식이나 유사 문자열 검색으로 인용구를 찾으려 하면, 브라우저 UI 스레드가 멈추거나 중복 문구가 존재할 때 잘못된 위치를 하이라이트하는 문제가 발생합니다.

Citations API의 start_char_index와 end_char_index를 활용하면 최신 브라우저의 CSS Custom Highlight API 또는 DOM TreeWalker를 통해 특정 텍스트 노드를 즉각 지정할 수 있습니다:

function highlightSourcePassage(containerElement, startChar, endChar) {
  const textContent = containerElement.textContent;
  if (startChar < 0 || endChar > textContent.length) return;

  const walker = document.createTreeWalker(
    containerElement,
    NodeFilter.SHOW_TEXT,
    null
  );

  let currentCharCount = 0;
  let startNode = null, endNode = null;
  let startNodeOffset = 0, endNodeOffset = 0;

  let node;
  while ((node = walker.nextNode())) {
    const nextCharCount = currentCharCount + node.length;

    if (!startNode && startChar >= currentCharCount && startChar < nextCharCount) {
      startNode = node;
      startNodeOffset = startChar - currentCharCount;
    }
    if (!endNode && endChar > currentCharCount && endChar <= nextCharCount) {
      endNode = node;
      endNodeOffset = endChar - currentCharCount;
      break;
    }
    currentCharCount = nextCharCount;
  }

  if (startNode && endNode) {
    const range = document.createRange();
    range.setStart(startNode, startNodeOffset);
    range.setEnd(endNode, endNodeOffset);

    const highlight = new Highlight(range);
    CSS.highlights.set("claude-citation-target", highlight);
  }
}

아키텍처 제약 사항과 365Finds의 분석

365Finds의 기술 분석은 도구의 장점뿐만 아니라 현실적인 제약 사항을 명확히 전달하는 데 중점을 둡니다. Citations API 도입 시 다음 세 가지 한계를 반드시 고려해야 합니다:

1. 네이티브 구조화 출력(output_config.format)과의 상호 배타성

가장 중대한 제약입니다. Citations API는 Claude의 네이티브 구조화 출력(JSON Schema 모드)과 동시에 활성화할 수 없습니다. 두 옵션을 함께 전송하면 Messages API는 즉시 400 Bad Request 에러를 반환합니다.

인용 기능은 텍스트 토큰 사이에 인용 블록을 교차 배치해야 하지만, 엄격한 JSON 파서는 문법 트리 제약을 강제하므로 두 방식이 충돌하기 때문입니다.

실무적 해결책: 인용이 포함된 정형 데이터가 필요하다면 JSON 대신 줄바꿈 기반의 키-값(Key-Value) 형태로 출력을 유도하십시오:

문서에서 다음 항목을 추출하십시오:
revenue: [값]
operating_margin: [값]
각 항목은 "필드명: 값" 형식으로 한 줄씩 출력하고, 각 줄마다 반드시 인용을 첨부하십시오.

백엔드에서는 콜론을 기준으로 문자열을 분할하고 각 줄에 바인딩된 citations 배열을 매핑합니다.

2. 일괄 활성화 규칙

단일 API 요청 내에서는 모든 문서 또는 검색 결과 블록의 citations.enabled 설정이 동일해야 합니다. 특정 보안 문서에만 인용을 켜고 보조 문서에는 끌 수 없습니다.

3. 텍스트 레이어가 없는 스캔 PDF 미지원

Citations API는 텍스트 레이어를 프로그래밍 방식으로 추출합니다. 스캔된 이미지 형태의 PDF는 OCR 처리가 선행되지 않으면 page_location 인용을 생성할 수 없습니다.


365Finds의 최종 결론

프롬프트로 "출처 페이지를 함께 기재해 달라"고 요청하는 RAG 시스템은 즉시 전환되어야 합니다. 자기회귀 모델의 태생적 특성상, 프롬프트만으로는 인용 환각을 원천 차단할 수 없습니다.

Anthropic Claude의 Citations API는 문서 근거 제시를 확률적 추측에서 검증 가능한 결정론적 포인터로 승격시켰습니다. 문자 단위 물리 오프셋 검증, 인용문 출력 토큰 무료 정책, 프롬프트 캐싱의 결합을 통해 법률 및 규제 환경에서도 완벽한 신뢰성을 갖춘 엔터프라이즈 AI 시스템 구축이 가능해졌습니다.


참고 자료