"""Извлечение карточек через 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}")