From c02d2e4744fcb3c6d5c0372c40bdc937cb93347a Mon Sep 17 00:00:00 2001 From: Roman Date: Wed, 22 Jul 2026 19:58:20 +0200 Subject: [PATCH 1/2] updated work-classification-script + small frontend fix --- .../classify_ude_works_to_index.py | 252 +++++++++++++++--- .../run_20260722_021910_049378.json | 50 ++++ .../research-profile.component.html | 2 +- 3 files changed, 268 insertions(+), 36 deletions(-) create mode 100644 llm_evaluations/basic_applied_experimental/run_reports/run_20260722_021910_049378.json diff --git a/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py b/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py index 329842c4..0b1de043 100644 --- a/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py +++ b/llm_evaluations/basic_applied_experimental/classify_ude_works_to_index.py @@ -32,6 +32,10 @@ UDE_NAME = "University of Duisburg-Essen" AFFILIATION_YEAR_GTE = 2025 WORK_YEAR_GTE = 1950 +SELECTION_AUTHOR_COHORT = "author-cohort" +SELECTION_INSTITUTION_WORKS = "institution-works" +SELECTION_MODES = (SELECTION_AUTHOR_COHORT, SELECTION_INSTITUTION_WORKS) + AUTHOR_PAGE_SIZE = 1000 AUTHOR_BATCH_SIZE = 1000 WORK_PAGE_SIZE = 2000 @@ -854,7 +858,26 @@ def validate(result: dict[str, Any]) -> list[str]: return errors -def ude_affiliation_filter() -> dict[str, Any]: +def institution_affiliation_filter( + institution_id: str, + institution_ror: str | None, + institution_name: str, + affiliation_year_gte: int, +) -> dict[str, Any]: + institution_matches: list[dict[str, Any]] = [ + {"term": {"affiliations.institution.id": institution_id}}, + { + "match_phrase": { + "affiliations.institution.display_name": institution_name + } + }, + ] + if institution_ror: + institution_matches.insert( + 1, + {"term": {"affiliations.institution.ror": institution_ror}}, + ) + return { "nested": { "path": "affiliations", @@ -863,21 +886,13 @@ def ude_affiliation_filter() -> dict[str, Any]: "filter": [ { "bool": { - "should": [ - {"term": {"affiliations.institution.id": UDE_ID}}, - {"term": {"affiliations.institution.ror": UDE_ROR}}, - { - "match_phrase": { - "affiliations.institution.display_name": UDE_NAME - } - }, - ], + "should": institution_matches, "minimum_should_match": 1, } }, { "range": { - "affiliations.years": {"gte": AFFILIATION_YEAR_GTE} + "affiliations.years": {"gte": affiliation_year_gte} } }, ] @@ -887,12 +902,21 @@ def ude_affiliation_filter() -> dict[str, Any]: } -def author_query(group: str, after: list[Any] | None) -> dict[str, Any]: +def author_query( + group: str, + after: list[Any] | None, + institution_id: str = UDE_ID, + institution_ror: str | None = UDE_ROR, + institution_name: str = UDE_NAME, + affiliation_year_gte: int = AFFILIATION_YEAR_GTE, +) -> dict[str, Any]: last_known = { "nested": { "path": "last_known_institutions", "query": { - "match_phrase": {"last_known_institutions.display_name": UDE_NAME} + "match_phrase": { + "last_known_institutions.display_name": institution_name + } }, } } @@ -903,11 +927,30 @@ def author_query(group: str, after: list[Any] | None) -> dict[str, Any]: } } query = ( - {"bool": {"filter": [last_known, ude_affiliation_filter()]}} + { + "bool": { + "filter": [ + last_known, + institution_affiliation_filter( + institution_id, + institution_ror, + institution_name, + affiliation_year_gte, + ), + ] + } + } if group == "known" else { "bool": { - "filter": [ude_affiliation_filter()], + "filter": [ + institution_affiliation_filter( + institution_id, + institution_ror, + institution_name, + affiliation_year_gte, + ) + ], "must_not": [last_known_exists], } } @@ -924,7 +967,22 @@ def author_query(group: str, after: list[Any] | None) -> dict[str, Any]: return body -def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any]: +def work_query( + author_ids: list[str], + after: list[Any] | None, + work_year_gte: int | None = WORK_YEAR_GTE, +) -> dict[str, Any]: + filters: list[dict[str, Any]] = [ + { + "nested": { + "path": "authorships", + "query": {"terms": {"authorships.author.id": author_ids}}, + } + } + ] + if work_year_gte is not None: + filters.insert(0, {"range": {"publication_year": {"gte": work_year_gte}}}) + body: dict[str, Any] = { "size": WORK_PAGE_SIZE, "track_total_hits": False, @@ -964,15 +1022,7 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any] ], "query": { "bool": { - "filter": [ - {"range": {"publication_year": {"gte": WORK_YEAR_GTE}}}, - { - "nested": { - "path": "authorships", - "query": {"terms": {"authorships.author.id": author_ids}}, - } - }, - ] + "filter": filters } }, "sort": [{"id": "asc"}], @@ -982,6 +1032,36 @@ def work_query(author_ids: list[str], after: list[Any] | None) -> dict[str, Any] return body +def institution_work_query( + institution_id: str, + after: list[Any] | None, +) -> dict[str, Any]: + """Select all works attributed to an institution, like Publikationsliste.""" + body = work_query([], after) + body["query"] = { + "bool": { + "must": [ + { + "nested": { + "path": "authorships", + "query": { + "nested": { + "path": "authorships.institutions", + "query": { + "terms": { + "authorships.institutions.id": [institution_id] + } + }, + } + }, + } + } + ] + } + } + return body + + def choose_work_hit( current: dict[str, Any] | None, candidate: dict[str, Any], @@ -1510,14 +1590,30 @@ def classify( raise StopPipeline(f"LLM unavailable for {work_id}: {error}") -def collect_authors(es: ES) -> list[str]: +def collect_authors( + es: ES, + institution_id: str = UDE_ID, + institution_ror: str | None = UDE_ROR, + institution_name: str = UDE_NAME, + affiliation_year_gte: int = AFFILIATION_YEAR_GTE, +) -> list[str]: ids: set[str] = set() for group in ("known", "empty"): after = None total = None read = 0 while True: - result = es.search(AUTHORS_INDEX, author_query(group, after)) + result = es.search( + AUTHORS_INDEX, + author_query( + group, + after, + institution_id, + institution_ror, + institution_name, + affiliation_year_gte, + ), + ) hits = result.get("hits", {}).get("hits", []) if total is None: value = result.get("hits", {}).get("total", 0) @@ -1535,7 +1631,7 @@ def collect_authors(es: ES) -> list[str]: raise StopPipeline("Missing author search_after") print(f"Authors {group}: {read}/{total}") result = sorted(ids) - print(f"Final UDE author count: {len(result)}") + print(f"Final institution author count: {len(result)}") return result @@ -1726,6 +1822,12 @@ def run( limit: int | None, workers: int, report: dict[str, Any], + selection_mode: str = SELECTION_AUTHOR_COHORT, + institution_id: str = UDE_ID, + institution_ror: str | None = UDE_ROR, + institution_name: str = UDE_NAME, + affiliation_year_gte: int = AFFILIATION_YEAR_GTE, + work_year_gte: int | None = WORK_YEAR_GTE, preflight_only: bool = False, ) -> None: if not ES_API_KEY.strip(): @@ -1749,17 +1851,34 @@ def run( api_key=LLM_API_KEY, timeout=REQUEST_TIMEOUT, ) - authors = collect_authors(es) - count = 0 warm = False - batches = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE - for start in range(0, len(authors), AUTHOR_BATCH_SIZE): + if selection_mode == SELECTION_INSTITUTION_WORKS: + work_batches: list[tuple[str, list[str] | None]] = [ + (f"Institution works: {institution_id}", None) + ] + else: + authors = collect_authors( + es, + institution_id, + institution_ror, + institution_name, + affiliation_year_gte, + ) + batch_count = (len(authors) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE + work_batches = [ + ( + f"Author batch {start // AUTHOR_BATCH_SIZE + 1}/{batch_count}", + authors[start : start + AUTHOR_BATCH_SIZE], + ) + for start in range(0, len(authors), AUTHOR_BATCH_SIZE) + ] + + for batch_label, author_ids in work_batches: if limit is not None and count >= limit: break - batch = authors[start : start + AUTHOR_BATCH_SIZE] - print(f"\nAuthor batch {start // AUTHOR_BATCH_SIZE + 1}/{batches}") + print(f"\n{batch_label}") after = None page = 0 @@ -1767,7 +1886,12 @@ def run( if limit is not None and count >= limit: break - result = es.search(WORKS_INDEX, work_query(batch, after)) + query = ( + institution_work_query(institution_id, after) + if author_ids is None + else work_query(author_ids, after, work_year_gte) + ) + result = es.search(WORKS_INDEX, query) hits = result.get("hits", {}).get("hits", []) if not hits: break @@ -1843,15 +1967,67 @@ def main() -> None: parser.add_argument("--limit", type=int) parser.add_argument("--workers", type=int, default=MAX_WORKERS) parser.add_argument("--preflight-only", action="store_true") + parser.add_argument( + "--selection-mode", + choices=SELECTION_MODES, + default=SELECTION_AUTHOR_COHORT, + help=( + "author-cohort selects works by current affiliated authors; " + "institution-works selects every work attributed to --institution-id" + ), + ) + parser.add_argument("--institution-id", default=UDE_ID) + parser.add_argument("--institution-ror", default=UDE_ROR) + parser.add_argument("--institution-name", default=UDE_NAME) + parser.add_argument( + "--affiliation-year-gte", type=int, default=AFFILIATION_YEAR_GTE + ) + parser.add_argument("--work-year-gte", type=int, default=WORK_YEAR_GTE) + parser.add_argument( + "--all-work-years", + action="store_true", + help=( + "disable the publication-year filter in author-cohort mode, " + "including works without publication_year" + ), + ) args = parser.parse_args() if args.limit is not None and args.limit < 1: raise SystemExit("--limit must be at least 1") if args.workers < 1: raise SystemExit("--workers must be at least 1") + if args.affiliation_year_gte < 0: + raise SystemExit("--affiliation-year-gte must not be negative") + if args.work_year_gte < 0: + raise SystemExit("--work-year-gte must not be negative") + + work_year_gte = None if args.all_work_years else args.work_year_gte + + institution_id = args.institution_id.strip() + if not institution_id: + raise SystemExit("--institution-id must not be empty") + if not institution_id.startswith("https://openalex.org/"): + institution_id = f"https://openalex.org/{bare_id(institution_id)}" + + institution_ror = nullable_text(args.institution_ror) + institution_name = args.institution_name.strip() + if args.selection_mode == SELECTION_AUTHOR_COHORT and not institution_name: + raise SystemExit("--institution-name is required for author-cohort") report = new_run_report(args.limit, args.workers) report["parameters"]["preflight_only"] = args.preflight_only + report["parameters"].update( + { + "selection_mode": args.selection_mode, + "institution_id": institution_id, + "institution_ror": institution_ror, + "institution_name": institution_name, + "affiliation_year_gte": args.affiliation_year_gte, + "work_year_gte": work_year_gte, + "all_work_years": args.all_work_years, + } + ) exit_code = 0 try: @@ -1859,6 +2035,12 @@ def main() -> None: args.limit, args.workers, report, + selection_mode=args.selection_mode, + institution_id=institution_id, + institution_ror=institution_ror, + institution_name=institution_name, + affiliation_year_gte=args.affiliation_year_gte, + work_year_gte=work_year_gte, preflight_only=args.preflight_only, ) report["status"] = "completed" diff --git a/llm_evaluations/basic_applied_experimental/run_reports/run_20260722_021910_049378.json b/llm_evaluations/basic_applied_experimental/run_reports/run_20260722_021910_049378.json new file mode 100644 index 00000000..169d8c92 --- /dev/null +++ b/llm_evaluations/basic_applied_experimental/run_reports/run_20260722_021910_049378.json @@ -0,0 +1,50 @@ +{ + "run_id": "20260722_021910_049378", + "started_at": "2026-07-22T02:19:10Z", + "finished_at": "2026-07-22T09:26:37Z", + "duration_seconds": 25645.781, + "status": "completed", + "error": null, + "parameters": { + "limit": null, + "workers": 25, + "model": "gemma4-e4b", + "prompt_version": "frascati_hard_ranges_v2", + "target_index": "work-classifications", + "bulk_batch_size": 200, + "state_storage": "memory_only", + "preflight_only": false, + "selection_mode": "institution-works", + "institution_id": "https://openalex.org/I62318514", + "institution_ror": "https://ror.org/04mz5ra38", + "institution_name": "University of Duisburg-Essen", + "affiliation_year_gte": 2025, + "work_year_gte": 1950 + }, + "classification": { + "llm_completed": 32189, + "valid": 32189, + "invalid": 0, + "categories": { + "applied_research": 10001, + "basic_research": 17089, + "experimental_development": 1813, + "non_research": 3286 + }, + "validation_errors": {} + }, + "indexing": { + "newly_indexed": 32189, + "bulk_requests": 183, + "bulk_documents_submitted": 32589, + "bulk_failures": 0 + }, + "token_usage": { + "prompt_tokens": 119788565, + "cached_prompt_tokens": 110500800, + "uncached_prompt_tokens": 9287765, + "completion_tokens": 29352270, + "real_total_usage": 38640035 + }, + "throughput_indexed_per_hour": 4518.5 +} diff --git a/webapp/src/app/modules/publication-detail/research-profile/research-profile.component.html b/webapp/src/app/modules/publication-detail/research-profile/research-profile.component.html index 54400cd9..80bf9d20 100644 --- a/webapp/src/app/modules/publication-detail/research-profile/research-profile.component.html +++ b/webapp/src/app/modules/publication-detail/research-profile/research-profile.component.html @@ -41,7 +41,7 @@ + [disabled]="false" /> } From daf71a6dae6c7505ce2c15ec98a7c5fecdc3b7de Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 23 Jul 2026 14:19:42 +0200 Subject: [PATCH 2/2] refactor: update llm.call to async await for improved performance --- service/src/main/inse/integrations/llm.py | 12 ++++++------ service/src/main/inse/keywords/logic.py | 2 +- service/src/main/inse/news/logic.py | 2 +- service/src/main/inse/persons/logic.py | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/service/src/main/inse/integrations/llm.py b/service/src/main/inse/integrations/llm.py index 180edfbc..101ce92c 100644 --- a/service/src/main/inse/integrations/llm.py +++ b/service/src/main/inse/integrations/llm.py @@ -1,9 +1,9 @@ -from openai import OpenAI, APIConnectionError +from openai import APIConnectionError from openai import AsyncOpenAI from .. import config from typing import Optional, Dict, Any import asyncio -def call( +async def call( system_prompt: str, user_prompt: str, model: str = None, @@ -16,18 +16,18 @@ def call( if model is None: model = config.settings.llm_model - + response_format = None if json_schema is not None: response_format = _get_response_format(schema = json_schema,schema_name=schema_name) - - client = OpenAI( + + client = AsyncOpenAI( base_url=config.settings.llm_api_url, api_key=config.settings.llm_api_key, timeout=timeout, ) try: - response = client.chat.completions.create( + response = await client.chat.completions.create( model=model, messages=[ {"role": "system", "content": system_prompt}, diff --git a/service/src/main/inse/keywords/logic.py b/service/src/main/inse/keywords/logic.py index 964c5364..b2bdcb2e 100644 --- a/service/src/main/inse/keywords/logic.py +++ b/service/src/main/inse/keywords/logic.py @@ -82,7 +82,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor user_prompt += f"""Input:{text}""" - keywords = llm.call( + keywords = await llm.call( system_prompt=system_prompt, user_prompt=user_prompt, json_schema = ExtractedKeywordsLLM.model_json_schema(), diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 3ced9bf5..bb423948 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -292,7 +292,7 @@ async def _get_article_keywords( if not text: return [] - raw = llm.call( + raw = await llm.call( system_prompt=KEYWORD_SYSTEM_PROMPT, user_prompt=f"Artikel:\n{text}", temperature=0.3, diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 43db5add..0168d39a 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -444,7 +444,7 @@ async def generate_person_bio( user_prompt = f"Daten zur Person:\n{person_json}" - bio = llm.call( + bio = await llm.call( system_prompt=system_prompt, user_prompt=user_prompt, temperature=0.8,