from __future__ import annotations import json import time from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path from typing import Any from openai import OpenAI PROJECT_ROOT = Path(__file__).resolve().parent CLASSIFICATION_DATA_DIR = PROJECT_ROOT / "classification_data" LLM_RESULTS_DIR = PROJECT_ROOT / "llm_results" PROMPT_FILE = PROJECT_ROOT / "prompt_frascati.txt" RUN_SUMMARY_FILE = LLM_RESULTS_DIR / "run_summary.json" LLM_BASE_URL = "https://project.nes.uni-due.de/llm2/v1/" LLM_API_KEY = "c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212" LLM_MODEL = "gemma4-e4b" SKIP_IF_ALREADY_EXISTS = True WARM_UP_PREFIX_CACHE = True MAX_WORKERS = 10 MAX_TOKENS = 2048 TEMPERATURE = 0 TOP_P = 1.0 TOP_K = 64 RETRY_ATTEMPTS = 3 RETRY_DELAY_SECONDS = 2.0 REQUEST_TIMEOUT_SECONDS = 180.0 SCHEMA_NAME = "frascati_research_orientation" CATEGORIES = { "basic_research", "applied_research", "experimental_development", "non_research", } PASTEUR_QUADRANTS = { "pure_basic", "use_inspired_basic", "pure_applied", "not_applicable", } CONFIDENCE_VALUES = {"high", "medium", "low"} SIGNAL_VALUES = { "title", "abstract", "venue", "work_type", "topics", "funders", "year", "language", } RESPONSE_SCHEMA: dict[str, Any] = { "type": "object", "properties": { "primary_category": {"type": "string", "enum": sorted(CATEGORIES)}, "applied_orientation_score": { "anyOf": [ {"type": "integer", "minimum": 0, "maximum": 100}, {"type": "null"}, ] }, "pasteur_quadrant": { "type": "string", "enum": sorted(PASTEUR_QUADRANTS), }, "confidence": {"type": "string", "enum": sorted(CONFIDENCE_VALUES)}, "signals_used": { "type": "array", "items": {"type": "string", "enum": sorted(SIGNAL_VALUES)}, }, "insufficient_context": {"type": "boolean"}, "rationale": {"type": "string", "minLength": 1}, }, "required": [ "primary_category", "applied_orientation_score", "pasteur_quadrant", "confidence", "signals_used", "insufficient_context", "rationale", ], "additionalProperties": False, } def read_json(path: Path) -> Any: with path.open("r", encoding="utf-8") as file: return json.load(file) def write_json(path: Path, data: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) temp_path = path.with_suffix(path.suffix + ".tmp") temp_path.write_text( json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8", ) temp_path.replace(path) def load_prompt() -> str: if not PROMPT_FILE.exists(): raise FileNotFoundError(PROMPT_FILE) prompt = PROMPT_FILE.read_text(encoding="utf-8").strip() if not prompt: raise RuntimeError(f"Prompt file is empty: {PROMPT_FILE}") return prompt def person_filename(person_id: str) -> str: return person_id.rstrip("/").rsplit("/", 1)[-1] def clean_json_content(content: str) -> str: cleaned = content.strip() if cleaned.startswith("```"): lines = cleaned.splitlines()[1:] if lines and lines[-1].strip() == "```": lines = lines[:-1] cleaned = "\n".join(lines).strip() return cleaned def is_number(value: Any) -> bool: return isinstance(value, (int, float)) and not isinstance(value, bool) def validate_classification(classification: dict[str, Any]) -> list[str]: errors: list[str] = [] category = classification.get("primary_category") score = classification.get("applied_orientation_score") quadrant = classification.get("pasteur_quadrant") confidence = classification.get("confidence") signals = classification.get("signals_used") insufficient_context = classification.get("insufficient_context") rationale = classification.get("rationale") if category not in CATEGORIES: errors.append("invalid_primary_category") if quadrant not in PASTEUR_QUADRANTS: errors.append("invalid_pasteur_quadrant") if confidence not in CONFIDENCE_VALUES: errors.append("invalid_confidence") if not isinstance(signals, list): errors.append("signals_used_must_be_list") else: if any(signal not in SIGNAL_VALUES for signal in signals): errors.append("invalid_signals_used") if len(signals) != len(set(signals)): errors.append("signals_used_must_be_unique") if not isinstance(insufficient_context, bool): errors.append("insufficient_context_must_be_boolean") if not isinstance(rationale, str) or not rationale.strip(): errors.append("rationale_missing_or_empty") if category == "non_research": if score is not None: errors.append("non_research_score_must_be_null") if quadrant != "not_applicable": errors.append("non_research_quadrant_must_be_not_applicable") if category == "basic_research": if not is_number(score): errors.append("basic_research_score_missing") elif quadrant == "use_inspired_basic" and not 25 <= score <= 45: errors.append("basic_research_score_outside_expected_range") elif quadrant != "use_inspired_basic" and not 0 <= score <= 30: errors.append("basic_research_score_outside_expected_range") if quadrant not in {"pure_basic", "use_inspired_basic"}: errors.append("basic_research_quadrant_mismatch") if category == "applied_research": if not is_number(score): errors.append("applied_research_score_missing") elif not 31 <= score <= 70: errors.append("applied_research_score_outside_expected_range") if quadrant != "pure_applied": errors.append("applied_research_quadrant_mismatch") if category == "experimental_development": if not is_number(score): errors.append("experimental_development_score_missing") elif not 71 <= score <= 100: errors.append("experimental_development_score_outside_expected_range") if quadrant != "pure_applied": errors.append("experimental_development_quadrant_mismatch") return errors def store_classification(classification: dict[str, Any]) -> dict[str, Any]: stored = dict(classification) stored["classification_reason"] = stored.pop("rationale") return stored def value_from(value: Any, field: str) -> int: if value is None: return 0 if isinstance(value, dict): return int(value.get(field, 0) or 0) return int(getattr(value, field, 0) or 0) def empty_usage() -> dict[str, int]: return { "prompt_tokens": 0, "uncached_prompt_tokens": 0, "completion_tokens": 0, "real_total_usage": 0, } def usage_dict(usage: Any) -> dict[str, int]: prompt_tokens = value_from(usage, "prompt_tokens") completion_tokens = value_from(usage, "completion_tokens") details = ( usage.get("prompt_tokens_details") if isinstance(usage, dict) else getattr(usage, "prompt_tokens_details", None) ) cached_tokens = min( value_from(details, "cached_tokens"), prompt_tokens, ) uncached_prompt_tokens = max( prompt_tokens - cached_tokens, 0, ) return { "prompt_tokens": prompt_tokens, "uncached_prompt_tokens": uncached_prompt_tokens, "completion_tokens": completion_tokens, "real_total_usage": (uncached_prompt_tokens + completion_tokens), } def normalize_usage_record(usage: Any) -> dict[str, int]: if not isinstance(usage, dict): return empty_usage() prompt_tokens = int(usage.get("prompt_tokens") or 0) completion_tokens = int(usage.get("completion_tokens") or 0) if "uncached_prompt_tokens" in usage: uncached_prompt_tokens = int(usage.get("uncached_prompt_tokens") or 0) elif "cached_prompt_tokens" in usage: cached_prompt_tokens = min( int(usage.get("cached_prompt_tokens") or 0), prompt_tokens, ) uncached_prompt_tokens = max( prompt_tokens - cached_prompt_tokens, 0, ) else: uncached_prompt_tokens = prompt_tokens uncached_prompt_tokens = min( max(uncached_prompt_tokens, 0), prompt_tokens, ) return { "prompt_tokens": prompt_tokens, "uncached_prompt_tokens": uncached_prompt_tokens, "completion_tokens": completion_tokens, "real_total_usage": (uncached_prompt_tokens + completion_tokens), } def normalize_result_for_storage( result: dict[str, Any], ) -> dict[str, Any]: debug = result.get("llm_debug") if isinstance(debug, dict): debug["usage"] = normalize_usage_record(debug.get("usage")) return result def deduplicate_works(works: Any) -> list[dict[str, Any]]: if not isinstance(works, list): raise ValueError("works must be a list") works_by_id: dict[str, dict[str, Any]] = {} for work in works: if not isinstance(work, dict): raise ValueError("Each work must be an object") work_id = work.get("work_id") if not isinstance(work_id, str) or not work_id: raise ValueError("Each work must have a non-empty work_id") existing = works_by_id.get(work_id) if existing is None: works_by_id[work_id] = work elif existing != work: raise ValueError(f"Conflicting input records for work_id {work_id}") return list(works_by_id.values()) def make_error_result( work: dict[str, Any], started: float, errors: list[str], attempts: int, ) -> dict[str, Any]: return { "work_id": work.get("work_id"), "doi": work.get("doi"), "input": work.get("input"), "classification": None, "llm_debug": { "status": "error", "content": None, "finish_reason": None, "duration_seconds": round(time.perf_counter() - started, 3), "attempt_count": attempts, "attempt_errors": errors, "usage": empty_usage(), "error": errors[-1] if errors else "Unknown error", "validation_errors": [], }, } def classify_work( client: OpenAI, system_prompt: str, work: dict[str, Any], ) -> dict[str, Any]: input_data = work.get("input") if not isinstance(input_data, dict): raise ValueError(f"Missing input for {work.get('work_id')}") started = time.perf_counter() attempt_errors: list[str] = [] for attempt in range(1, RETRY_ATTEMPTS + 1): try: response = client.chat.completions.create( model=LLM_MODEL, messages=[ {"role": "system", "content": system_prompt}, { "role": "user", "content": json.dumps( input_data, ensure_ascii=False, indent=2, ), }, ], temperature=TEMPERATURE, max_tokens=MAX_TOKENS, top_p=TOP_P, response_format={ "type": "json_schema", "json_schema": { "name": SCHEMA_NAME, "strict": True, "schema": RESPONSE_SCHEMA, }, }, extra_body={"top_k": TOP_K}, ) if not response.choices: raise RuntimeError("LLM response has no choices") choice = response.choices[0] content = choice.message.content or "" if not content.strip(): raise RuntimeError("LLM response content is empty") classification = json.loads(clean_json_content(content)) if not isinstance(classification, dict): raise ValueError("LLM response is not a JSON object") return { "work_id": work.get("work_id"), "doi": work.get("doi"), "input": input_data, "classification": store_classification(classification), "llm_debug": { "status": "ok", "content": content, "finish_reason": choice.finish_reason, "duration_seconds": round(time.perf_counter() - started, 3), "attempt_count": attempt, "attempt_errors": attempt_errors, "usage": usage_dict(response.usage), "error": None, "validation_errors": validate_classification(classification), }, } except Exception as exception: attempt_errors.append(f"{type(exception).__name__}: {exception}") status_code = getattr(exception, "status_code", None) if status_code == 400 or type(exception).__name__ == "BadRequestError": return make_error_result(work, started, attempt_errors, attempt) if attempt < RETRY_ATTEMPTS: time.sleep(RETRY_DELAY_SECONDS * attempt) return make_error_result( work, started, attempt_errors, len(attempt_errors), ) def make_summary(results: list[dict[str, Any]]) -> dict[str, Any]: usage = empty_usage() durations: list[float] = [] parsed_ok = 0 api_errors = 0 validation_errors = 0 for result in results: debug = result.get("llm_debug") or {} result_usage = normalize_usage_record(debug.get("usage")) for key in usage: usage[key] += result_usage[key] duration = debug.get("duration_seconds") if isinstance(duration, (int, float)): durations.append(float(duration)) errors = debug.get("validation_errors") or [] if debug.get("status") == "ok" and not errors: parsed_ok += 1 elif debug.get("status") != "ok": api_errors += 1 if errors: validation_errors += 1 works_total = len(results) duration_sum = round(sum(durations), 3) return { "works_total": works_total, "parsed_ok": parsed_ok, "api_errors": api_errors, "validation_errors": validation_errors, "usage": usage, "average_usage_per_work": { key: (round(value / works_total, 2) if works_total else 0.0) for key, value in usage.items() }, "duration_seconds_sum_of_requests": duration_sum, "average_duration_seconds_per_work": ( round(duration_sum / len(durations), 3) if durations else 0.0 ), } def make_output( person: dict[str, Any], results: list[dict[str, Any]] ) -> dict[str, Any]: return { "person": person, "config": { "base_url": LLM_BASE_URL, "model": LLM_MODEL, "prompt_file": PROMPT_FILE.name, "classification_data_dir": CLASSIFICATION_DATA_DIR.name, "output_dir": LLM_RESULTS_DIR.name, "temperature": TEMPERATURE, "max_tokens": MAX_TOKENS, "top_p": TOP_P, "top_k": TOP_K, "max_workers": MAX_WORKERS, "skip_if_already_exists": SKIP_IF_ALREADY_EXISTS, "response_format": "json_schema", "schema_name": SCHEMA_NAME, "strict_schema": True, }, "summary": make_summary(results), "results": results, } def load_existing_results( output_path: Path, works_by_id: dict[str, dict[str, Any]], ) -> dict[str, dict[str, Any]]: if not output_path.exists(): return {} data = read_json(output_path) results = data.get("results", []) if isinstance(data, dict) else [] existing: dict[str, dict[str, Any]] = {} for result in results: if not isinstance(result, dict): continue work_id = result.get("work_id") if not isinstance(work_id, str) or work_id not in works_by_id: continue debug = result.get("llm_debug") or {} reusable = ( debug.get("status") == "ok" and isinstance(result.get("classification"), dict) and result.get("input") == works_by_id[work_id].get("input") ) if not reusable: continue previous = existing.get(work_id) if previous is None: existing[work_id] = result elif previous != result: raise ValueError(f"Conflicting existing results for work_id {work_id}") return existing def save_results( output_path: Path, person: dict[str, Any], work_ids: list[str], results_by_id: dict[str, dict[str, Any]], ) -> list[dict[str, Any]]: ordered = [ normalize_result_for_storage(results_by_id[work_id]) for work_id in work_ids if work_id in results_by_id ] write_json(output_path, make_output(person, ordered)) return ordered def process_person( input_path: Path, client: OpenAI, system_prompt: str, warm_up_needed: bool, ) -> tuple[dict[str, Any], bool]: data = read_json(input_path) if not isinstance(data, dict): raise ValueError(f"Root is not an object in {input_path}") person = data.get("person") if not isinstance(person, dict): raise ValueError(f"person is not an object in {input_path}") person_id = person.get("id") if not isinstance(person_id, str) or not person_id: raise ValueError(f"Missing person id in {input_path}") works = deduplicate_works(data.get("works")) works_by_id = {work["work_id"]: work for work in works} work_ids = list(works_by_id) output_path = LLM_RESULTS_DIR / f"{person_filename(person_id)}_results.json" results_by_id = ( load_existing_results(output_path, works_by_id) if SKIP_IF_ALREADY_EXISTS else {} ) pending = [ works_by_id[work_id] for work_id in work_ids if work_id not in results_by_id ] requested_count = len(pending) warm_up_succeeded = False if not pending: print(f"Skip LLM calls: {output_path.name}") if pending and warm_up_needed: work = pending.pop(0) print(f"Prefix cache warm-up: {work['work_id']}") result = classify_work(client, system_prompt, work) results_by_id[work["work_id"]] = result saved = save_results(output_path, person, work_ids, results_by_id) print(f"{person.get('display_name')}: {len(saved)}/{len(works)}") if (result.get("llm_debug") or {}).get("status") != "ok": error = (result.get("llm_debug") or {}).get("error") raise RuntimeError( "Prefix cache warm-up failed. Parallel processing was not started. " f"Error: {error}" ) warm_up_succeeded = True if pending: executor = ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(pending))) futures = { executor.submit(classify_work, client, system_prompt, work): work for work in pending } try: for future in as_completed(futures): work = futures[future] result = future.result() results_by_id[work["work_id"]] = result saved = save_results(output_path, person, work_ids, results_by_id) print(f"{person.get('display_name')}: {len(saved)}/{len(works)}") except KeyboardInterrupt: for future in futures: future.cancel() save_results(output_path, person, work_ids, results_by_id) executor.shutdown(wait=False, cancel_futures=True) print("Interrupted. Completed results were saved.") raise else: executor.shutdown(wait=True) final_results = save_results(output_path, person, work_ids, results_by_id) output = make_output(person, final_results) return { "person": person, "source_file": input_path.relative_to(PROJECT_ROOT).as_posix(), "output_file": output_path.relative_to(PROJECT_ROOT).as_posix(), "summary": output["summary"], "skipped": requested_count == 0, "works_reused": len(works) - requested_count, "works_requested": requested_count, }, warm_up_succeeded def make_run_summary( person_runs: list[dict[str, Any]], ) -> dict[str, Any]: summary: dict[str, Any] = { "persons_total": len(person_runs), "persons_skipped": sum(bool(item.get("skipped")) for item in person_runs), "works_total": 0, "works_reused": 0, "works_requested": 0, "parsed_ok": 0, "api_errors": 0, "validation_errors": 0, } usage = empty_usage() duration_sum = 0.0 for item in person_runs: person_summary = item["summary"] for key in ( "works_total", "parsed_ok", "api_errors", "validation_errors", ): summary[key] += int(person_summary.get(key) or 0) summary["works_reused"] += int(item.get("works_reused") or 0) summary["works_requested"] += int(item.get("works_requested") or 0) person_usage = normalize_usage_record(person_summary.get("usage")) for key in usage: usage[key] += person_usage[key] duration_sum += float( person_summary.get("duration_seconds_sum_of_requests") or 0 ) works_total = summary["works_total"] summary["usage"] = usage summary["average_usage_per_work"] = { key: (round(value / works_total, 2) if works_total else 0.0) for key, value in usage.items() } summary["duration_seconds_sum_of_requests"] = round( duration_sum, 3, ) summary["average_duration_seconds_per_work"] = ( round(duration_sum / works_total, 3) if works_total else 0.0 ) return { "config": { "base_url": LLM_BASE_URL, "model": LLM_MODEL, "prompt_file": PROMPT_FILE.name, "classification_data_dir": (CLASSIFICATION_DATA_DIR.name), "output_dir": LLM_RESULTS_DIR.name, "max_workers": MAX_WORKERS, "skip_if_already_exists": (SKIP_IF_ALREADY_EXISTS), }, "summary": summary, "persons": person_runs, } def main() -> None: if LLM_API_KEY == "тут код" or not LLM_API_KEY.strip(): raise RuntimeError("Set LLM_API_KEY in run_llm.py") if not CLASSIFICATION_DATA_DIR.exists(): raise FileNotFoundError(CLASSIFICATION_DATA_DIR) if not PROMPT_FILE.exists(): raise FileNotFoundError(PROMPT_FILE) input_files = sorted(CLASSIFICATION_DATA_DIR.glob("A*.json")) if not input_files: raise FileNotFoundError(f"No A*.json files found in {CLASSIFICATION_DATA_DIR}") LLM_RESULTS_DIR.mkdir(parents=True, exist_ok=True) client = OpenAI( base_url=LLM_BASE_URL, api_key=LLM_API_KEY, timeout=REQUEST_TIMEOUT_SECONDS, ) system_prompt = load_prompt() person_runs: list[dict[str, Any]] = [] prefix_cache_warmed = False try: for input_file in input_files: print(f"Processing: {input_file.name}") person_run, warmed = process_person( input_file, client, system_prompt, WARM_UP_PREFIX_CACHE and not prefix_cache_warmed, ) prefix_cache_warmed = prefix_cache_warmed or warmed person_runs.append(person_run) write_json( RUN_SUMMARY_FILE, make_run_summary(person_runs), ) except KeyboardInterrupt: write_json( RUN_SUMMARY_FILE, make_run_summary(person_runs), ) print("Classification interrupted safely.") return run_summary = make_run_summary(person_runs) write_json(RUN_SUMMARY_FILE, run_summary) print("Classification completed.") print(f"Persons: {run_summary['summary']['persons_total']}") print(f"Skipped: {run_summary['summary']['persons_skipped']}") print(f"Works: {run_summary['summary']['works_total']}") print(f"Reused: {run_summary['summary']['works_reused']}") print(f"Requested: {run_summary['summary']['works_requested']}") print(f"Parsed OK: {run_summary['summary']['parsed_ok']}") print(f"Validation errors: {run_summary['summary']['validation_errors']}") print(f"API errors: {run_summary['summary']['api_errors']}") if __name__ == "__main__": main()