Files
romanov_btg_rag/rag/extract/extract.py
T
anorandClaude Opus 4.8 d49599e9ff feat: извлечение карточек через Claude structured output
messages.parse() с pydantic-схемой (валидация на клиенте), adaptive
thinking, кэш system-промпта, замер usage и стоимости на лекцию.
CLI build_knowledge.py: --source/--limit/--lecture/--dry-run/--force,
выход в data/knowledge/<лекция>.json.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 14:37:19 +10:00

86 lines
3.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Извлечение карточек из лекции через Claude (structured output).
messages.parse() + pydantic: SDK сам убирает из wire-схемы неподдерживаемые
ограничения (pattern/min_length) и валидирует ответ клиентски — модель
физически не может вернуть карточку без источника.
Замер usage → стоимость: пилот экстраполируется на весь корпус (шаг 6 плана).
"""
from __future__ import annotations
from dataclasses import dataclass
import anthropic
from ..corpus import Lecture
from .cards import ExtractionResult
from .prompt import build_system_prompt
MODEL = "claude-opus-4-8"
# Цены Opus 4.8, $/токен (вход / выход / чтение кэша ~0.1x)
PRICE_IN = 5.00 / 1_000_000
PRICE_OUT = 25.00 / 1_000_000
PRICE_CACHE_READ = 0.50 / 1_000_000
# Большой JSON-выход (десятки карточек с цитатами) + запас; не-стриминг
# с таким max_tokens требует явного timeout, иначе SDK откажет
MAX_TOKENS = 32_000
TIMEOUT_S = 600.0
@dataclass(frozen=True)
class Usage:
input_tokens: int
output_tokens: int
cache_read_tokens: int
cost_usd: float
def build_request_kwargs(lecture: Lecture) -> dict:
"""Параметры запроса отдельно от вызова — тестируются без API."""
return {
"model": MODEL,
"max_tokens": MAX_TOKENS,
"timeout": TIMEOUT_S,
"thinking": {"type": "adaptive"},
# system стабилен между лекциями; cache_control — задел (ниже 4096
# токенов Opus молча не кэширует, вреда нет)
"system": [{
"type": "text",
"text": build_system_prompt(),
"cache_control": {"type": "ephemeral"},
}],
"messages": [{
"role": "user",
"content": (f"Лекция: {lecture.id}\n"
f"(в поле video карточек указывай id фрагмента из маркера "
f"«=== ФРАГМЕНТ: … ===»; таймкоды локальны фрагменту)\n\n"
f"{lecture.load_text()}"),
}],
"output_format": ExtractionResult,
}
def extract_lecture(lecture: Lecture,
client: anthropic.Anthropic | None = None,
) -> tuple[ExtractionResult, Usage]:
client = client or anthropic.Anthropic()
response = client.messages.parse(**build_request_kwargs(lecture))
if response.stop_reason == "max_tokens":
raise RuntimeError(
f"{lecture.id}: ответ обрезан по max_tokens={MAX_TOKENS} — "
f"карточки неполные, поднять лимит или дробить лекцию")
result = response.parsed_output
if result is None:
raise RuntimeError(f"{lecture.id}: модель не вернула структурированный "
f"ответ (stop_reason={response.stop_reason})")
u = response.usage
cache_read = getattr(u, "cache_read_input_tokens", 0) or 0
usage = Usage(
input_tokens=u.input_tokens,
output_tokens=u.output_tokens,
cache_read_tokens=cache_read,
cost_usd=(u.input_tokens * PRICE_IN
+ u.output_tokens * PRICE_OUT
+ cache_read * PRICE_CACHE_READ),
)
return result, usage