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>
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
"""Извлечение карточек из лекции через 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
|
||||
+50
-14
@@ -1,38 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Фаза 1 — извлечение карточек знаний из транскриптов (+ кадров).
|
||||
"""Фаза 1 — извлечение карточек знаний из транскриптов.
|
||||
|
||||
Запуск из корня проекта:
|
||||
python scripts/build_knowledge.py --limit 5 --source manual
|
||||
Запуск из корня проекта (нужен ANTHROPIC_API_KEY в .env):
|
||||
python scripts/build_knowledge.py --source manual --limit 1 # пример
|
||||
python scripts/build_knowledge.py --lecture "1.5" # по подстроке id
|
||||
python scripts/build_knowledge.py --dry-run # без API: что и сколько
|
||||
|
||||
Сейчас скелет: показывает, что увидит конвейер, и где остановиться.
|
||||
Реализация — в rag/extract/ (см. его TODO и ROADMAP Фаза 1).
|
||||
Выход: data/knowledge/<лекция>.json (карточки + usage) — версионируется в git.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # корень в путь
|
||||
from rag import corpus # noqa: E402
|
||||
from rag import config, corpus # noqa: E402
|
||||
from rag.extract import extract # noqa: E402
|
||||
|
||||
|
||||
def _safe_name(lecture_id: str) -> str:
|
||||
return re.sub(r'[/\\:*?"<>|]', "_", lecture_id)[:150]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="Фаза 1: транскрипт → карточки знаний")
|
||||
ap.add_argument("--limit", type=int, default=0, help="сколько лекций (0 = все)")
|
||||
ap.add_argument("--source", choices=["all", "mass", "manual"], default="all")
|
||||
ap.add_argument("--lecture", default="", help="фильтр по подстроке id лекции")
|
||||
ap.add_argument("--dry-run", action="store_true", help="показать план без вызовов API")
|
||||
ap.add_argument("--force", action="store_true", help="перезаписать готовые карточки")
|
||||
args = ap.parse_args()
|
||||
|
||||
items = [t for t in corpus.iter_transcripts()
|
||||
if args.source == "all" or t.source == args.source]
|
||||
items = [lec for lec in corpus.iter_lectures()
|
||||
if (args.source == "all" or lec.source == args.source)
|
||||
and (not args.lecture or args.lecture.lower() in lec.id.lower())]
|
||||
if args.limit:
|
||||
items = items[: args.limit]
|
||||
|
||||
print(f"К обработке: {len(items)} транскриптов (source={args.source})")
|
||||
for t in items[:10]:
|
||||
print(f" [{t.source}] {t.id}")
|
||||
if len(items) > 10:
|
||||
print(f" … ещё {len(items) - 10}")
|
||||
print(f"К обработке: {len(items)} лекций (source={args.source})")
|
||||
if args.dry_run:
|
||||
for lec in items:
|
||||
print(f" [{lec.source}] {lec.id} — {len(lec.fragments)} фрагм., "
|
||||
f"{len(lec.load_text())} симв.")
|
||||
return 0
|
||||
|
||||
print("\n[TODO] извлечение карточек ещё не реализовано — см. rag/extract/ и ROADMAP Фаза 1.")
|
||||
config.KNOWLEDGE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
total_cost = 0.0
|
||||
for lec in items:
|
||||
out_path = config.KNOWLEDGE_DIR / f"{_safe_name(lec.id)}.json"
|
||||
if out_path.exists() and not args.force:
|
||||
print(f" пропуск (готово): {lec.id}")
|
||||
continue
|
||||
print(f" извлечение: {lec.id} ({len(lec.fragments)} фрагм.) …", flush=True)
|
||||
result, usage = extract.extract_lecture(lec)
|
||||
payload = result.model_dump()
|
||||
payload["_usage"] = {
|
||||
"input_tokens": usage.input_tokens,
|
||||
"output_tokens": usage.output_tokens,
|
||||
"cache_read_tokens": usage.cache_read_tokens,
|
||||
"cost_usd": round(usage.cost_usd, 4),
|
||||
"model": extract.MODEL,
|
||||
}
|
||||
out_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
total_cost += usage.cost_usd
|
||||
print(f" карточек: {len(result.cards)}, токены {usage.input_tokens}→"
|
||||
f"{usage.output_tokens}, ${usage.cost_usd:.3f} → {out_path.name}")
|
||||
|
||||
print(f"\nИтого стоимость прогона: ${total_cost:.3f}")
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Сборка запроса извлечения — проверяется без API."""
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from rag import config, corpus
|
||||
from rag.extract import extract
|
||||
from rag.extract.cards import ExtractionResult
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def lecture(tmp_path: Path) -> corpus.Lecture:
|
||||
seg = tmp_path / "segments.txt"
|
||||
seg.write_text("[00:01] тестовый сегмент про 80 кГц\n", encoding="utf-8")
|
||||
return corpus.Lecture(id="тест-лекция", fragments=(
|
||||
corpus.Transcript(id="тест-лекция__фрагмент1", source="mass", path=seg),
|
||||
))
|
||||
|
||||
|
||||
def test_request_has_model_and_schema(lecture):
|
||||
kw = extract.build_request_kwargs(lecture)
|
||||
assert kw["model"] == "claude-opus-4-8"
|
||||
assert kw["output_format"] is ExtractionResult
|
||||
assert kw["thinking"] == {"type": "adaptive"}
|
||||
|
||||
|
||||
def test_request_system_is_cached_and_has_glossary(lecture):
|
||||
kw = extract.build_request_kwargs(lecture)
|
||||
sys_block = kw["system"][0]
|
||||
assert sys_block["cache_control"] == {"type": "ephemeral"}
|
||||
# живой словарь из docs/glossary.md подставлен
|
||||
assert "IR2153" in sys_block["text"]
|
||||
|
||||
|
||||
def test_request_user_contains_fragment_marker_and_text(lecture):
|
||||
kw = extract.build_request_kwargs(lecture)
|
||||
user_text = kw["messages"][0]["content"]
|
||||
assert "=== ФРАГМЕНТ: тест-лекция__фрагмент1 ===" in user_text
|
||||
assert "тестовый сегмент про 80 кГц" in user_text
|
||||
assert "Лекция: тест-лекция" in user_text
|
||||
|
||||
|
||||
def test_cost_constants_positive():
|
||||
# цены заданы и стоимость считается из usage, не из воздуха
|
||||
assert extract.PRICE_IN > 0 and extract.PRICE_OUT > extract.PRICE_IN
|
||||
Reference in New Issue
Block a user