From 21482f3c6f25b1509efd04ef1d3515427c33b094 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 22 Aug 2026 13:59:29 +0200 Subject: [PATCH 1/8] refactor: move bio logic to a separate module --- service/src/main/inse/persons/bio.py | 185 +++++++++++++++++++++++ service/src/main/inse/persons/logic.py | 172 --------------------- service/src/main/inse/persons/service.py | 4 +- 3 files changed, 187 insertions(+), 174 deletions(-) create mode 100644 service/src/main/inse/persons/bio.py diff --git a/service/src/main/inse/persons/bio.py b/service/src/main/inse/persons/bio.py new file mode 100644 index 00000000..860251e4 --- /dev/null +++ b/service/src/main/inse/persons/bio.py @@ -0,0 +1,185 @@ +""" +Bio generation for persons / authors. +""" + +import json +import logging +import time + +from pydantic import ValidationError + +from inse.integrations import elasticsearch +from inse.model import ESIndex +from inse.persons.model import PersonBio + +from .. import config +from ..integrations import llm + +logger = logging.getLogger(__name__) + + +async def _fetch_author_display_name(author_id: str) -> str | None: + query = { + "query_string": { + "default_field": "_id", + "query": author_id, + } + } + + response = await elasticsearch.search( + index=ESIndex.OPENALEX_AUTHORS, + query=query, + source=["display_name"], + ) + + hits = response.get("hits", {}).get("hits", []) + + if not hits: + return None + + return hits[0].get("_source", {}).get("display_name") + + +async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: + WORK_SOURCE_FIELDS = [ + "title", + "display_name", + "abstract", + "cited_by_count", + "primary_topic", + ] + + author_url = f"https://openalex.org/{author_id.strip()}" + + authorship_query = { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": [{"term": {"authorships.author.id": author_url}}], + } + }, + } + } + + body = { + "size": 100, + "sort": [{"cited_by_count": {"order": "desc"}}], + "_source": WORK_SOURCE_FIELDS, + "query": authorship_query, + "aggs": { + "primary_topics": { + "terms": {"field": "primary_topic.id", "size": 5}, + "aggs": { + "topic_name": { + "top_hits": { + "size": 1, + "_source": ["primary_topic.display_name"], + } + } + }, + } + }, + } + + response = await elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=body, + ) + + works = [] + for hit in response.get("hits", {}).get("hits", []): + works.append(hit.get("_source", {})) + + topics = [] + buckets = ( + response.get("aggregations", {}).get("primary_topics", {}).get("buckets", []) + ) + for bucket in buckets: + topic_hits = bucket.get("topic_name", {}).get("hits", {}).get("hits", []) + display_name = None + if topic_hits: + primary_topic = topic_hits[0].get("_source", {}).get("primary_topic", {}) + display_name = primary_topic.get("display_name") + topics.append( + { + "id": bucket.get("key"), + "display_name": display_name, + "count": bucket.get("doc_count"), + } + ) + + return works, topics + + +def _build_papers(works: list) -> list: + papers = [] + for work in works: + name = work.get("title") or work.get("display_name") + abstract = work.get("abstract") + papers.append( + { + "name": name, + "abstract": abstract, + "stats": { + "cited_by_count": work.get("cited_by_count"), + }, + } + ) + return papers + + +async def get_data_for_bio(author_id: str) -> dict | None: + display_name = await _fetch_author_display_name(author_id) + if display_name is None: + return None + + works, top_topics = await _fetch_works_and_topics(author_id) + papers = _build_papers(works) + + author_data = { + "display_name": display_name, + "topics": top_topics, + "papers": papers, + } + return author_data + + +async def generate_person_bio( + author_id: str, include: set[str] | None = None +) -> str: + start_time = time.time() + author_data = await get_data_for_bio(author_id) + if author_data is None: + return "No person found." + + person_json = json.dumps(author_data, ensure_ascii=False) + + system_prompt = """\ + Beschreibe in zwei Sätzen das Hauptforschungsfeld des Autors. Formuliere dabei allgemeinverständlich, sodass auch Personen ohne Fachwissen einen Einblick in die Forschung gewinnen. Nenne keine konkreten Publikationen oder Einzelwerke, sondern konzentriere dich auf die übergeordneten Forschungsinteressen und Themen. Verzichte auf bloße Aufzählungen und verbinde die Informationen zu einem flüssigen Text. + Beschreibe anschließend in ein bis zwei Sätzen die wirtschaftliche Relevanz der Forschung anhand von Anwendungen, Technologien oder Branchen, die davon profitieren könnten. + Verwende insgesamt maximal 100 bis 120 Wörter. Formuliere die Antwort so, dass sie ohne weitere Anpassungen direkt als Kurzbiografie verwendet werden kann. Verwende keine Superlative oder übertriebene Formulierungen, sondern bleibe sachlich und informativ. Gebe den Text als One-Liner zurück, ohne Zeilenumbrüche oder Aufzählungen. Verwende keine Gedankenstriche (– oder —) zur Gliederung von Sätzen. Formuliere stattdessen mit Kommas, Klammern oder zwei getrennten Sätzen. + Gib ausschließlich ein JSON-Objekt zurück, das den Text im Feld "bio" enthält. + """ + + user_prompt = f"Daten zur Person:\n{person_json}" + + response = await llm.call( + system_prompt=system_prompt, + user_prompt=user_prompt, + json_schema=PersonBio.model_json_schema(), + schema_name="bio", + temperature=0.8, + top_p=0.95, + ) + + try: + bio = PersonBio.model_validate_json(response).bio + except ValidationError: + logger.warning(f"Bio generation for author {author_id} returned no valid JSON: {response}") + bio = "Etwas ist schiefgelaufen." + + elapsed_time = time.time() - start_time + logger.info(f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds") + + return bio diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index a75ae61a..f6355cf8 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -4,13 +4,10 @@ Business logic for persons / authors. """ import hashlib -import json import logging import time from datetime import datetime -from pydantic import ValidationError - from inse.exceptions import ( BadRequestException, ElasticsearchException, @@ -26,13 +23,11 @@ from inse.persons.model import ( CareerMetrics, CustomAuthor, CustomAuthorsListResponse, - PersonBio, ) from inse.persons.query_builder import build_authors_search_rescored from inse.works.logic import enrich_topic_descriptions from .. import config, util -from ..integrations import llm logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" @@ -220,100 +215,6 @@ async def count_authors_by_last_name(last_name: str) -> int: return await _count_authors(query) -async def _fetch_author_display_name(author_id: str) -> str | None: - query = { - "query_string": { - "default_field": "_id", - "query": author_id, - } - } - - response = await elasticsearch.search( - index=INDEX_NAME, - query=query, - source=["display_name"], - ) - - hits = response.get("hits", {}).get("hits", []) - - if not hits: - return None - - return hits[0].get("_source", {}).get("display_name") - - -async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: - WORK_SOURCE_FIELDS = [ - "title", - "display_name", - "abstract", - "cited_by_count", - "primary_topic", - ] - - author_url = f"https://openalex.org/{author_id.strip()}" - - authorship_query = { - "nested": { - "path": "authorships", - "query": { - "bool": { - "filter": [{"term": {"authorships.author.id": author_url}}], - } - }, - } - } - - body = { - "size": 100, - "sort": [{"cited_by_count": {"order": "desc"}}], - "_source": WORK_SOURCE_FIELDS, - "query": authorship_query, - "aggs": { - "primary_topics": { - "terms": {"field": "primary_topic.id", "size": 5}, - "aggs": { - "topic_name": { - "top_hits": { - "size": 1, - "_source": ["primary_topic.display_name"], - } - } - }, - } - }, - } - - response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, - body=body, - ) - - works = [] - for hit in response.get("hits", {}).get("hits", []): - works.append(hit.get("_source", {})) - - topics = [] - buckets = ( - response.get("aggregations", {}).get("primary_topics", {}).get("buckets", []) - ) - for bucket in buckets: - topic_hits = bucket.get("topic_name", {}).get("hits", {}).get("hits", []) - display_name = None - if topic_hits: - primary_topic = topic_hits[0].get("_source", {}).get("primary_topic", {}) - display_name = primary_topic.get("display_name") - topics.append( - { - "id": bucket.get("key"), - "display_name": display_name, - "count": bucket.get("doc_count"), - } - ) - - return works, topics - - async def _get_publication_years_for_author(author_id: str) -> list[int]: author_url = f"https://openalex.org/{author_id.strip()}" @@ -427,79 +328,6 @@ async def get_career_metrics_for_author(author_id: str) -> CareerMetrics: return _compute_career_metrics(publication_years) -def _build_papers(works: list) -> list: - papers = [] - for work in works: - name = work.get("title") or work.get("display_name") - abstract = work.get("abstract") - papers.append( - { - "name": name, - "abstract": abstract, - "stats": { - "cited_by_count": work.get("cited_by_count"), - }, - } - ) - return papers - - -async def get_data_for_bio(author_id: str) -> dict | None: - display_name = await _fetch_author_display_name(author_id) - if display_name is None: - return None - - works, top_topics = await _fetch_works_and_topics(author_id) - papers = _build_papers(works) - - author_data = { - "display_name": display_name, - "topics": top_topics, - "papers": papers, - } - return author_data - - -async def generate_person_bio( - author_id: str, include: set[str] | None = None -) -> str: - start_time = time.time() - author_data = await get_data_for_bio(author_id) - if author_data is None: - return "No person found." - - person_json = json.dumps(author_data, ensure_ascii=False) - - system_prompt = """\ - Beschreibe in zwei Sätzen das Hauptforschungsfeld des Autors. Formuliere dabei allgemeinverständlich, sodass auch Personen ohne Fachwissen einen Einblick in die Forschung gewinnen. Nenne keine konkreten Publikationen oder Einzelwerke, sondern konzentriere dich auf die übergeordneten Forschungsinteressen und Themen. Verzichte auf bloße Aufzählungen und verbinde die Informationen zu einem flüssigen Text. - Beschreibe anschließend in ein bis zwei Sätzen die wirtschaftliche Relevanz der Forschung anhand von Anwendungen, Technologien oder Branchen, die davon profitieren könnten. - Verwende insgesamt maximal 100 bis 120 Wörter. Formuliere die Antwort so, dass sie ohne weitere Anpassungen direkt als Kurzbiografie verwendet werden kann. Verwende keine Superlative oder übertriebene Formulierungen, sondern bleibe sachlich und informativ. Gebe den Text als One-Liner zurück, ohne Zeilenumbrüche oder Aufzählungen. Verwende keine Gedankenstriche (– oder —) zur Gliederung von Sätzen. Formuliere stattdessen mit Kommas, Klammern oder zwei getrennten Sätzen. - Gib ausschließlich ein JSON-Objekt zurück, das den Text im Feld "bio" enthält. - """ - - user_prompt = f"Daten zur Person:\n{person_json}" - - response = await llm.call( - system_prompt=system_prompt, - user_prompt=user_prompt, - json_schema=PersonBio.model_json_schema(), - schema_name="bio", - temperature=0.8, - top_p=0.95, - ) - - try: - bio = PersonBio.model_validate_json(response).bio - except ValidationError: - logger.warning(f"Bio generation for author {author_id} returned no valid JSON: {response}") - bio = "Etwas ist schiefgelaufen." - - elapsed_time = time.time() - start_time - logger.info(f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds") - - return bio - - async def get_person_by_id( author_id: str, include: str | None = None ) -> CustomAuthorsListResponse: diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index 3f66255c..337ddd08 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -9,7 +9,7 @@ from fastapi import APIRouter, HTTPException, Path, Query, status from inse.models.openalex.authors_list_response import AuthorsListResponse -from . import logic, model +from . import bio as bio_logic, logic, model router = APIRouter( prefix="/api/inse-service", @@ -75,7 +75,7 @@ async def generate_person_bio( if include else None ) - bio = await logic.generate_person_bio(author_id, include_set) + bio = await bio_logic.generate_person_bio(author_id, include_set) return model.PersonBio(bio=bio) @router.get( -- 2.56.1 From 7da36d8777b82925e845aaf19182d15af28945f9 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 22 Aug 2026 14:04:03 +0200 Subject: [PATCH 2/8] remove unused 'include' parameter --- service/src/main/inse/persons/bio.py | 4 +-- service/src/main/inse/persons/service.py | 30 +---------------------- webapp/src/app/api/api/persons.service.ts | 20 --------------- 3 files changed, 2 insertions(+), 52 deletions(-) diff --git a/service/src/main/inse/persons/bio.py b/service/src/main/inse/persons/bio.py index 860251e4..23e8dbce 100644 --- a/service/src/main/inse/persons/bio.py +++ b/service/src/main/inse/persons/bio.py @@ -145,9 +145,7 @@ async def get_data_for_bio(author_id: str) -> dict | None: return author_data -async def generate_person_bio( - author_id: str, include: set[str] | None = None -) -> str: +async def generate_person_bio(author_id: str) -> str: start_time = time.time() author_data = await get_data_for_bio(author_id) if author_data is None: diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index 337ddd08..3e94985b 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -32,23 +32,7 @@ async def search_persons( query: Annotated[ str, Query(description="Search query (e.g., Arman AND Arzani)") ] = None, - include: Annotated[ - str | None, - Query( - description=( - "Comma-separated include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, sources, counts_by_year, works_api_url, dates, " - "cited_by_count_boost" - ), - example="topics_full,topic_share", - ), - ] = None, ): - include_set = ( - {tag.strip().lower() for tag in include.split(",") if tag.strip()} - if include - else None - ) return await logic.search_persons(author_id, query) @@ -62,20 +46,8 @@ async def generate_person_bio( author_id: Annotated[ str, Query(description="OpenAlex author ID (e.g., A5093075883)") ], - include: Annotated[ - str | None, - Query( - description=("Comma-separated list to include tags"), - example="topics_full,topic_share", - ), - ] = None, ): - include_set = ( - {tag.strip().lower() for tag in include.split(",") if tag.strip()} - if include - else None - ) - bio = await bio_logic.generate_person_bio(author_id, include_set) + bio = await bio_logic.generate_person_bio(author_id) return model.PersonBio(bio=bio) @router.get( diff --git a/webapp/src/app/api/api/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index 8f9ef03d..b8502f7c 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.service.ts @@ -52,13 +52,11 @@ export class PersonsService extends BaseService { * Generates a bio for a person by author ID. * @endpoint get /api/inse-service/persons/bio * @param authorId OpenAlex author ID (e.g., A5093075883) - * @param include Comma-separated list to include tags * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public generatePersonBio( authorId: string, - include?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -69,7 +67,6 @@ export class PersonsService extends BaseService { ): Observable; public generatePersonBio( authorId: string, - include?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -80,7 +77,6 @@ export class PersonsService extends BaseService { ): Observable>; public generatePersonBio( authorId: string, - include?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -91,7 +87,6 @@ export class PersonsService extends BaseService { ): Observable>; public generatePersonBio( authorId: string, - include?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -112,11 +107,6 @@ export class PersonsService extends BaseService { authorId, 'author_id', ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); let localVarHeaders = this.defaultHeaders; @@ -403,14 +393,12 @@ export class PersonsService extends BaseService { * @endpoint get /api/inse-service/persons/search * @param authorId OpenAlex author ID (e.g., A5093075883) * @param query Search query (e.g., Arman AND Arzani) - * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public searchPersons( authorId?: string, query?: string, - include?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -422,7 +410,6 @@ export class PersonsService extends BaseService { public searchPersons( authorId?: string, query?: string, - include?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -434,7 +421,6 @@ export class PersonsService extends BaseService { public searchPersons( authorId?: string, query?: string, - include?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -446,7 +432,6 @@ export class PersonsService extends BaseService { public searchPersons( authorId?: string, query?: string, - include?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -466,11 +451,6 @@ export class PersonsService extends BaseService { query, 'query', ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); let localVarHeaders = this.defaultHeaders; -- 2.56.1 From eb5d6830a57f15bf0c5f2303baf7c0d840486276 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 22 Aug 2026 14:12:03 +0200 Subject: [PATCH 3/8] test: add tests for person bio generation --- service/src/main/inse/persons/test_bio.py | 52 +++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 service/src/main/inse/persons/test_bio.py diff --git a/service/src/main/inse/persons/test_bio.py b/service/src/main/inse/persons/test_bio.py new file mode 100644 index 00000000..87c7f4fd --- /dev/null +++ b/service/src/main/inse/persons/test_bio.py @@ -0,0 +1,52 @@ +import pytest + +from inse import config +from inse.persons import service + +NO_PERSON_FOUND = "No person found." + + +@pytest.fixture() +def anyio_backend(): + return "asyncio" + + +def elasticsearch_configured(): + return bool( + config.settings.elasticsearch_url and config.settings.elasticsearch_api_key + ) + + +def llm_configured(): + return bool( + config.settings.llm_api_url + and config.settings.llm_api_key + and config.settings.llm_model + ) + + +requires_elasticsearch = pytest.mark.skipif( + not elasticsearch_configured(), reason="Elasticsearch is not configured" +) +requires_elasticsearch_and_llm = pytest.mark.skipif( + not (elasticsearch_configured() and llm_configured()), + reason="Elasticsearch and/or LLM are not configured", +) + + +@pytest.mark.anyio +@requires_elasticsearch_and_llm +async def test_bio_is_generated_for_person(): + response = await service.generate_person_bio(author_id="A5093075883") + + assert response.bio != "No person found.", "author was not found in Elasticsearch" + assert response.bio != "Etwas ist schiefgelaufen." , "the LLM returned no valid bio" + assert len(response.bio) >= 10, f"bio is too short: {response.bio!r}" + + +@pytest.mark.anyio +@requires_elasticsearch +async def test_bio_reports_unknown_author(): + response = await service.generate_person_bio(author_id="A000") + + assert response.bio == "No person found.", "author was not found in Elasticsearch" -- 2.56.1 From 7d3792c7b4e7815f7d8a0b9c865c6bf12751d5d9 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 22 Aug 2026 14:14:17 +0200 Subject: [PATCH 4/8] fix: update parameter documentation to use 'examples' instead of 'example' --- service/src/main/inse/persons/service.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index 3e94985b..d95ca046 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -68,7 +68,7 @@ async def get_person_by_id( "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " "last_known_institutions, ..." ), - example="topics_full,topic_share", + examples="topics_full,topic_share", ), ] = None, ): @@ -91,11 +91,11 @@ async def search_persons_by_name( "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " "last_known_institutions, ..." ), - example="topics_full,topic_share", + examples="topics_full,topic_share", ), ], - limit:Annotated[int | None, Query(description=("Limit of search page results"),example ="2")]= None, - page_offset : Annotated[int | None, Query(description=("Offset of the result page"),example="2")] = None, + limit:Annotated[int | None, Query(description=("Limit of search page results"),examples ="2")]= None, + page_offset : Annotated[int | None, Query(description=("Offset of the result page"),examples="2")] = None, ): return await logic.search_persons_by_name(author_name=author_name, include=include, page_offset=page_offset, limit=limit) @@ -113,7 +113,7 @@ async def search_persons_autocomplete( "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " "last_known_institutions, ..." ), - example="topics_full,topic_share" + examples="topics_full,topic_share" )]): return await logic.search_persons_autocomplete(author_name=author_name, include=include) @@ -153,7 +153,7 @@ async def search_persons_list( str | None, Query( description="Comma-separated include tags", - example="topics_full,topic_share", + examples="topics_full,topic_share", ), ] = None, year_filter_enabled: Annotated[ -- 2.56.1 From 3147de9fcbd4c18330078557454b2606267109b1 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 22 Aug 2026 16:20:36 +0200 Subject: [PATCH 5/8] improve error handling in bio generation and update tests --- service/src/main/inse/persons/bio.py | 11 +++++++---- service/src/main/inse/persons/test_bio.py | 12 ++++-------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/service/src/main/inse/persons/bio.py b/service/src/main/inse/persons/bio.py index 23e8dbce..28c5d4a4 100644 --- a/service/src/main/inse/persons/bio.py +++ b/service/src/main/inse/persons/bio.py @@ -8,6 +8,7 @@ import time from pydantic import ValidationError +from inse.exceptions import NotFoundException, UpstreamAPIException from inse.integrations import elasticsearch from inse.model import ESIndex from inse.persons.model import PersonBio @@ -149,7 +150,7 @@ async def generate_person_bio(author_id: str) -> str: start_time = time.time() author_data = await get_data_for_bio(author_id) if author_data is None: - return "No person found." + raise NotFoundException(f"No person found for author ID {author_id}.") person_json = json.dumps(author_data, ensure_ascii=False) @@ -173,9 +174,11 @@ async def generate_person_bio(author_id: str) -> str: try: bio = PersonBio.model_validate_json(response).bio - except ValidationError: - logger.warning(f"Bio generation for author {author_id} returned no valid JSON: {response}") - bio = "Etwas ist schiefgelaufen." + except ValidationError as error: + logger.warning( + f"Bio generation for author {author_id} returned no valid bio: {response}" + ) + raise UpstreamAPIException("Bio generation failed.") from error elapsed_time = time.time() - start_time logger.info(f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds") diff --git a/service/src/main/inse/persons/test_bio.py b/service/src/main/inse/persons/test_bio.py index 87c7f4fd..8f575de4 100644 --- a/service/src/main/inse/persons/test_bio.py +++ b/service/src/main/inse/persons/test_bio.py @@ -1,10 +1,9 @@ import pytest from inse import config +from inse.exceptions import NotFoundException from inse.persons import service -NO_PERSON_FOUND = "No person found." - @pytest.fixture() def anyio_backend(): @@ -39,14 +38,11 @@ requires_elasticsearch_and_llm = pytest.mark.skipif( async def test_bio_is_generated_for_person(): response = await service.generate_person_bio(author_id="A5093075883") - assert response.bio != "No person found.", "author was not found in Elasticsearch" - assert response.bio != "Etwas ist schiefgelaufen." , "the LLM returned no valid bio" assert len(response.bio) >= 10, f"bio is too short: {response.bio!r}" @pytest.mark.anyio @requires_elasticsearch -async def test_bio_reports_unknown_author(): - response = await service.generate_person_bio(author_id="A000") - - assert response.bio == "No person found.", "author was not found in Elasticsearch" +async def test_bio_generation_fails_for_unknown_author(): + with pytest.raises(NotFoundException): + await service.generate_person_bio(author_id="A000") -- 2.56.1 From 613640a73006ba776a866725a52128279cdbe5a1 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 22 Aug 2026 16:41:28 +0200 Subject: [PATCH 6/8] add AI-generated badge to bio --- .../app/modules/person/person.component.html | 12 ++++++- .../app/modules/person/person.component.scss | 31 ++++++++++++++++++- .../app/modules/person/person.component.ts | 2 ++ webapp/src/app/shared/ui/icons.ts | 1 + 4 files changed, 44 insertions(+), 2 deletions(-) diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index 66e9ab07..58bada17 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -122,7 +122,17 @@ [size]="150" [diameter]="150"> } @else if (personBio() != null) { -

Biografie

+
+

Biografie

+ + {{ AI_GENERATED_ICON }} + KI-generiert + +

{{ personBio() }}

} diff --git a/webapp/src/app/modules/person/person.component.scss b/webapp/src/app/modules/person/person.component.scss index 1081434a..ab068a7d 100644 --- a/webapp/src/app/modules/person/person.component.scss +++ b/webapp/src/app/modules/person/person.component.scss @@ -217,12 +217,41 @@ box-shadow: var(--sg-shadow-sm); } +.bio-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 18px; +} + .bio-card h3 { - margin: 0 0 18px; + margin: 0; font-size: 14px; font-weight: 700; } +.ai-badge { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 2px 8px; + border-radius: 999px; + background: var(--sg-warning-soft); + color: var(--sg-warning); + font-size: 11px; + font-weight: 600; + line-height: 1.4; + white-space: nowrap; + cursor: help; +} + +.ai-badge mat-icon { + width: 14px; + height: 14px; + font-size: 14px; +} + .bio-card p { margin: 0; color: var(--sg-text); diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index 123b9b37..4e1968db 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -49,6 +49,7 @@ import { LinkTabNavBarItem, } from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component'; import { + AI_GENERATED_ICON, APARTMENT_ICON, BOOKMARK_BORDER_ICON, BOOKMARK_ICON, @@ -95,6 +96,7 @@ export class PersonComponent { readonly VERIFIED_ICON = VERIFIED_ICON; readonly DESCRIPTION_ICON = DESCRIPTION_ICON; readonly PERSON_ICON = PERSON_ICON; + readonly AI_GENERATED_ICON = AI_GENERATED_ICON; private readonly router = inject(Router); private readonly activatedRoute = inject(ActivatedRoute); diff --git a/webapp/src/app/shared/ui/icons.ts b/webapp/src/app/shared/ui/icons.ts index e30d45e8..d89491d4 100644 --- a/webapp/src/app/shared/ui/icons.ts +++ b/webapp/src/app/shared/ui/icons.ts @@ -96,6 +96,7 @@ export const TUNE_ICON = 'tune' as const; // ============================================================================ // 5. Status, Feedback & Indicators Icons // ============================================================================ +export const AI_GENERATED_ICON = 'auto_awesome' as const; export const BOOKMARK_BORDER_ICON = 'bookmark_border' as const; export const CHECK_ICON = 'check' as const; export const CHECK_CIRCLE_ICON = 'check_circle' as const; // similar to check but with circle -- 2.56.1 From 5343c3204d47cfe623e469ac74b1df8022805cc1 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 22 Aug 2026 16:48:55 +0200 Subject: [PATCH 7/8] execute pipeline --- service/src/main/inse/news/logic.py | 1 + 1 file changed, 1 insertion(+) diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index da4ca3eb..aa2625ed 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -874,3 +874,4 @@ async def _related_search_terms(query_text: str) -> list: terms.append(term) return terms + -- 2.56.1 From 5c50c2976006814d376a90a88efb075c5e39815b Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Sat, 22 Aug 2026 17:03:34 +0200 Subject: [PATCH 8/8] fix build: ensure client is closed after API calls --- service/src/main/inse/integrations/llm.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/service/src/main/inse/integrations/llm.py b/service/src/main/inse/integrations/llm.py index 7860ad8a..55c7b92c 100644 --- a/service/src/main/inse/integrations/llm.py +++ b/service/src/main/inse/integrations/llm.py @@ -43,6 +43,8 @@ async def call( ) except APIConnectionError: return "Etwas ist schiefgelaufen. Bitte versuche es später erneut." + finally: + await client.close() return response.choices[0].message.content or ( "Etwas ist schiefgelaufen. Bitte versuche es erneut." @@ -126,5 +128,7 @@ async def call_stream( print(f"LLM streaming failed: {type(e).__name__}: {e}") traceback.print_exc() return "" + finally: + await client.close() return full_content \ No newline at end of file -- 2.56.1