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 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 + diff --git a/service/src/main/inse/persons/bio.py b/service/src/main/inse/persons/bio.py new file mode 100644 index 00000000..28c5d4a4 --- /dev/null +++ b/service/src/main/inse/persons/bio.py @@ -0,0 +1,186 @@ +""" +Bio generation for persons / authors. +""" + +import json +import logging +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 + +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) -> str: + start_time = time.time() + author_data = await get_data_for_bio(author_id) + if author_data is None: + raise NotFoundException(f"No person found for author ID {author_id}.") + + 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 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") + + 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..d95ca046 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", @@ -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 logic.generate_person_bio(author_id, include_set) + bio = await bio_logic.generate_person_bio(author_id) return model.PersonBio(bio=bio) @router.get( @@ -96,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, ): @@ -119,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) @@ -141,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) @@ -181,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[ 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..8f575de4 --- /dev/null +++ b/service/src/main/inse/persons/test_bio.py @@ -0,0 +1,48 @@ +import pytest + +from inse import config +from inse.exceptions import NotFoundException +from inse.persons import service + + +@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 len(response.bio) >= 10, f"bio is too short: {response.bio!r}" + + +@pytest.mark.anyio +@requires_elasticsearch +async def test_bio_generation_fails_for_unknown_author(): + with pytest.raises(NotFoundException): + await service.generate_person_bio(author_id="A000") 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; 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