feat: извлечение через Z.AI (GLM) и сравнение с эталоном Opus
Anthropic-совместимый эндпоинт Z.AI; схему просим текстом (structured output у GLM нет), pydantic-валидация + один ретрай с фидбеком ошибки. zai_compare.py: GLM извлекает «Принцип» по сырому ASR → сравнение с эталоном по типам карточек, битым таймкодам, покрытию 9 golden-фактов. Выход GLM в data/eval/zai/ — базу знаний не трогает. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -61,3 +61,8 @@ EVAL_DIR = DATA / "eval" # тест-вопросы агента (Ф
|
||||
EMBEDDING_MODEL = os.environ.get("EMBEDDING_MODEL", "BAAI/bge-m3")
|
||||
VECTOR_BACKEND = os.environ.get("VECTOR_BACKEND", "chroma")
|
||||
ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
|
||||
|
||||
# Z.AI (GLM) — кандидат на дешёвое масштабирование извлечения; сравнивается
|
||||
# с эталоном Opus на golden set (см. scripts/zai_compare.py)
|
||||
ZAI_API_KEY = os.environ.get("ZAI_API_KEY", "")
|
||||
ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-4.6")
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Извлечение карточек через Z.AI (GLM) — Anthropic-совместимый эндпоинт.
|
||||
|
||||
Кандидат на дешёвое масштабирование: качество сравнивается с эталоном Opus
|
||||
на одной и той же лекции (scripts/zai_compare.py). Structured outputs
|
||||
Anthropic у GLM нет — схему просим текстом, ответ валидируем pydantic,
|
||||
при ошибке валидации один ретрай с фидбеком.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
import anthropic
|
||||
from pydantic import ValidationError
|
||||
|
||||
from .. import config
|
||||
from ..corpus import Lecture
|
||||
from .cards import ExtractionResult
|
||||
from .prompt import build_system_prompt
|
||||
|
||||
ZAI_BASE_URL = "https://api.z.ai/api/anthropic"
|
||||
MAX_TOKENS = 32_000
|
||||
TIMEOUT_S = 600.0
|
||||
|
||||
# Цены GLM-4.6 ($/токен) — для отчёта сравнения стоимости
|
||||
PRICE_IN = 0.60 / 1_000_000
|
||||
PRICE_OUT = 2.20 / 1_000_000
|
||||
|
||||
_FENCE = re.compile(r"^\s*```(?:json)?\s*|\s*```\s*$")
|
||||
|
||||
JSON_INSTRUCTIONS = """
|
||||
|
||||
ФОРМАТ ОТВЕТА: верни ТОЛЬКО валидный JSON-объект (без markdown-ограждений,
|
||||
без пояснений до или после) строго по этой JSON-схеме:
|
||||
|
||||
{schema}
|
||||
"""
|
||||
|
||||
|
||||
def strip_fences(text: str) -> str:
|
||||
"""GLM любит оборачивать JSON в ```json …``` — снимаем ограждения."""
|
||||
return _FENCE.sub("", text.strip())
|
||||
|
||||
|
||||
def parse_result(text: str) -> ExtractionResult:
|
||||
return ExtractionResult.model_validate(json.loads(strip_fences(text)))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Usage:
|
||||
input_tokens: int
|
||||
output_tokens: int
|
||||
cost_usd: float
|
||||
retries: int
|
||||
|
||||
|
||||
def build_request_kwargs(lecture: Lecture) -> dict:
|
||||
schema = json.dumps(ExtractionResult.model_json_schema(),
|
||||
ensure_ascii=False, indent=1)
|
||||
return {
|
||||
"model": config.ZAI_MODEL,
|
||||
"max_tokens": MAX_TOKENS,
|
||||
"timeout": TIMEOUT_S,
|
||||
"system": build_system_prompt() + JSON_INSTRUCTIONS.format(schema=schema),
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": (f"Лекция: {lecture.id}\n"
|
||||
f"(в поле video карточек указывай id фрагмента из маркера "
|
||||
f"«=== ФРАГМЕНТ: … ===»; таймкоды локальны фрагменту)\n\n"
|
||||
f"{lecture.load_text()}"),
|
||||
}],
|
||||
}
|
||||
|
||||
|
||||
def extract_lecture_zai(lecture: Lecture,
|
||||
client: anthropic.Anthropic | None = None,
|
||||
) -> tuple[ExtractionResult, Usage]:
|
||||
if client is None:
|
||||
if not config.ZAI_API_KEY:
|
||||
raise RuntimeError("ZAI_API_KEY не задан (добавь в .env)")
|
||||
client = anthropic.Anthropic(base_url=ZAI_BASE_URL,
|
||||
api_key=config.ZAI_API_KEY)
|
||||
kwargs = build_request_kwargs(lecture)
|
||||
in_tok = out_tok = 0
|
||||
last_err = None
|
||||
for attempt in range(2):
|
||||
response = client.messages.create(**kwargs)
|
||||
in_tok += response.usage.input_tokens
|
||||
out_tok += response.usage.output_tokens
|
||||
text = next((b.text for b in response.content if b.type == "text"), "")
|
||||
try:
|
||||
result = parse_result(text)
|
||||
usage = Usage(in_tok, out_tok,
|
||||
in_tok * PRICE_IN + out_tok * PRICE_OUT, attempt)
|
||||
return result, usage
|
||||
except (json.JSONDecodeError, ValidationError) as e:
|
||||
last_err = e
|
||||
# ретрай с фидбеком: тот же запрос + ответ модели + текст ошибки
|
||||
kwargs["messages"] = kwargs["messages"][:1] + [
|
||||
{"role": "assistant", "content": text},
|
||||
{"role": "user", "content":
|
||||
f"Твой JSON не прошёл валидацию:\n{e}\n"
|
||||
f"Верни ИСПРАВЛЕННЫЙ полный JSON (только JSON, без пояснений)."},
|
||||
]
|
||||
raise RuntimeError(f"{lecture.id}: GLM не вернул валидный JSON после ретрая: {last_err}")
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сравнение извлечения Z.AI (GLM) с эталоном Opus на лекции «Принцип».
|
||||
|
||||
python scripts/zai_compare.py # извлечь (если нет) и сравнить
|
||||
python scripts/zai_compare.py --force # переизвлечь GLM-вариант
|
||||
|
||||
Эталон: data/knowledge/_Романов_принцип.json (агент Opus, проверен пилотом).
|
||||
GLM-вариант: data/eval/zai/_Романов_принцип.json (в базу знаний НЕ попадает).
|
||||
Решает вопрос масштабирования: можно ли отдать массовое извлечение дешёвой
|
||||
модели без потери качества.
|
||||
"""
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # корень в путь
|
||||
from rag import config, corpus # noqa: E402
|
||||
from rag.extract import zai # noqa: E402
|
||||
|
||||
_spec = importlib.util.spec_from_file_location(
|
||||
"quote_check", Path(__file__).parent / "quote_check.py")
|
||||
quote_check = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(quote_check)
|
||||
|
||||
REFERENCE = config.KNOWLEDGE_DIR / "_Романов_принцип.json"
|
||||
ZAI_OUT = config.EVAL_DIR / "zai" / "_Романов_принцип.json"
|
||||
|
||||
# Ключевые факты золотого набора из «Принципа» (видео П) — проверка по словам
|
||||
GOLDEN_FACTS = {
|
||||
"P1 синус-симметрия": lambda t: "синус" in t and ("туда" in t or "излишк" in t),
|
||||
"P2 2Ф+АМ": lambda t: "2ф" in t or "2 ф" in t,
|
||||
"P4 горячее/холодное": lambda t: "горяч" in t or "холодн" in t,
|
||||
"P5 3Ф+ФМ/ЧМ": lambda t: "3ф" in t or "3 ф" in t,
|
||||
"S2 стробирование питания": lambda t: "сняли" in t or "гейтир" in t or "строб" in t,
|
||||
"S3 приёмник-детектор": lambda t: "детектор" in t,
|
||||
"N6 несущая 200-400 + IR2153": lambda t: ("200" in t or "300" in t) and "ir2153" in t.replace(" ", ""),
|
||||
"T1 ΔU/рыбки": lambda t: "рыбк" in t or "δ" in t or "дельта" in t,
|
||||
"A3 добротность сама-на-себя": lambda t: "добротн" in t,
|
||||
}
|
||||
|
||||
|
||||
def describe(path: Path) -> dict:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
by_type: dict[str, int] = {}
|
||||
n_sources = 0
|
||||
flagged = 0
|
||||
for c in data["cards"]:
|
||||
by_type[c["type"]] = by_type.get(c["type"], 0) + 1
|
||||
n_sources += len(c["sources"])
|
||||
flagged += bool(c.get("needs_frame_check"))
|
||||
text = " ".join(json.dumps(c, ensure_ascii=False) for c in data["cards"]).lower()
|
||||
golden = {name: check(text) for name, check in GOLDEN_FACTS.items()}
|
||||
qc = quote_check.check_file(path)
|
||||
return {"cards": len(data["cards"]), "by_type": by_type, "sources": n_sources,
|
||||
"frame_check": flagged, "golden": golden, "qc": qc,
|
||||
"usage": data.get("_usage", {})}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--force", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
lecture = next(lec for lec in corpus.iter_lectures()
|
||||
if lec.id == "_Романов_принцип")
|
||||
if args.force or not ZAI_OUT.exists():
|
||||
print(f"Извлечение GLM ({config.ZAI_MODEL}) из «Принципа»…", flush=True)
|
||||
result, usage = zai.extract_lecture_zai(lecture)
|
||||
payload = result.model_dump()
|
||||
payload["_fragments"] = ["_Романов_принцип"]
|
||||
payload["_extractor"] = f"zai/{config.ZAI_MODEL}"
|
||||
payload["_usage"] = {"input_tokens": usage.input_tokens,
|
||||
"output_tokens": usage.output_tokens,
|
||||
"cost_usd": round(usage.cost_usd, 4),
|
||||
"retries": usage.retries}
|
||||
ZAI_OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
ZAI_OUT.write_text(json.dumps(payload, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
print(f" токены {usage.input_tokens}→{usage.output_tokens}, "
|
||||
f"${usage.cost_usd:.4f}, ретраев {usage.retries}")
|
||||
|
||||
ref, cand = describe(REFERENCE), describe(ZAI_OUT)
|
||||
print(f"\n{'':38} {'Opus (эталон)':>15} {'GLM':>15}")
|
||||
print(f"{'карточек всего':38} {ref['cards']:>15} {cand['cards']:>15}")
|
||||
types = sorted(set(ref["by_type"]) | set(cand["by_type"]))
|
||||
for t in types:
|
||||
print(f"{' ' + t:38} {ref['by_type'].get(t, 0):>15} {cand['by_type'].get(t, 0):>15}")
|
||||
print(f"{'источников':38} {ref['sources']:>15} {cand['sources']:>15}")
|
||||
print(f"{'битых таймкодов':38} {len(ref['qc']['bad_timecode']):>15} "
|
||||
f"{len(cand['qc']['bad_timecode']):>15}")
|
||||
print(f"{'слабых цитат':38} {len(ref['qc']['weak_quote']):>15} "
|
||||
f"{len(cand['qc']['weak_quote']):>15}")
|
||||
print(f"{'помечено «сверить с кадром»':38} {ref['frame_check']:>15} {cand['frame_check']:>15}")
|
||||
g_ref = sum(ref["golden"].values())
|
||||
g_cand = sum(cand["golden"].values())
|
||||
print(f"{'golden-фактов покрыто':38} {g_ref:>13}/9 {g_cand:>13}/9")
|
||||
for name in GOLDEN_FACTS:
|
||||
r, c = ref["golden"][name], cand["golden"][name]
|
||||
if not (r and c):
|
||||
print(f" {'✓' if r else '✗'} эталон | {'✓' if c else '✗'} GLM — {name}")
|
||||
if cand["qc"]["bad_timecode"]:
|
||||
print("\nБитые таймкоды GLM (галлюцинации источников!):")
|
||||
for title, video, tc in cand["qc"]["bad_timecode"][:10]:
|
||||
print(f" ✗ [{tc}] {title[:70]}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Z.AI-извлечение: сборка запроса и разбор ответа — без API."""
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from rag import corpus
|
||||
from rag.extract import zai
|
||||
|
||||
|
||||
@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),
|
||||
))
|
||||
|
||||
|
||||
VALID_JSON = ('{"lecture_id": "тест", "cards": [{"type": "принцип", "title": "т",'
|
||||
'"statement": "с", "layer": "радиотехника",'
|
||||
'"sources": [{"video": "тест__фр1", "timecode": "00:01", "quote": "контур"}]}],'
|
||||
'"asr_findings": []}')
|
||||
|
||||
|
||||
def test_request_contains_schema_and_rules(lecture):
|
||||
kw = zai.build_request_kwargs(lecture)
|
||||
assert "json-схеме" in kw["system"].lower()
|
||||
assert "ExtractionResult" in kw["system"] or "cards" in kw["system"]
|
||||
assert "НИЧЕГО НЕ ВЫДУМЫВАТЬ" in kw["system"]
|
||||
assert "=== ФРАГМЕНТ: тест__фр1 ===" in kw["messages"][0]["content"]
|
||||
|
||||
|
||||
def test_parse_plain_json():
|
||||
result = zai.parse_result(VALID_JSON)
|
||||
assert result.lecture_id == "тест"
|
||||
assert len(result.cards) == 1
|
||||
|
||||
|
||||
def test_parse_fenced_json():
|
||||
fenced = f"```json\n{VALID_JSON}\n```"
|
||||
assert zai.parse_result(fenced).lecture_id == "тест"
|
||||
|
||||
|
||||
def test_parse_garbage_raises():
|
||||
with pytest.raises(Exception):
|
||||
zai.parse_result("вот ваш JSON: непонятно что")
|
||||
Reference in New Issue
Block a user