refactor(news-keywords): unify news keyword extraction approach between batch job and on-demand
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
2026-09-15 18:45:14 +02:00
parent b98e484617
commit 04c621986d
7 changed files with 181 additions and 55 deletions
+3
View File
@@ -4,6 +4,9 @@
service/*
!service/scripts
# Keyword extraction contract, shared with background-jobs/app/llm/client.py.
!service/src/main/inse/news/keyword_extraction.py
# Data-only folders that do not belong in the job image.
service/scripts/multipliers
+63 -16
View File
@@ -1,8 +1,21 @@
import os
import sys
from pathlib import Path
from dotenv import load_dotenv
from openai import APIConnectionError, OpenAI
try:
# The job images copy this module next to sync.py, see
# service/scripts/jobs-image/Dockerfile.
import keyword_extraction
except ModuleNotFoundError:
# Running from a repo checkout, where it sits in the service package.
sys.path.append(
str(Path(__file__).resolve().parents[3] / "service/src/main/inse/news")
)
import keyword_extraction
load_dotenv()
LLM_BASE_URL = os.getenv("INSE_LLM_BASE_URL", "https://project.nes.uni-due.de/llm2/v1/")
@@ -32,24 +45,33 @@ SYSTEM_PROMPT_NAMES = ("""
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
""")
SYSTEM_PROMPT_KEYWORDS = ("""
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]}
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
""")
_client = OpenAI(
base_url=LLM_BASE_URL,
api_key=LLM_API_KEY,
timeout=30,
)
def call(system_prompt, user_prompt, model=LLM_MODEL, temperature=1.0, top_p=0.95):
def call(
system_prompt,
user_prompt,
model=LLM_MODEL,
temperature=1.0,
top_p=0.95,
top_k=64,
json_schema=None,
schema_name=None,
):
response_format = None
if json_schema is not None:
response_format = {
"type": "json_schema",
"json_schema": {
"name": schema_name or "response",
"strict": True,
"schema": json_schema,
},
}
try:
response = _client.chat.completions.create(
model=model,
@@ -59,7 +81,8 @@ def call(system_prompt, user_prompt, model=LLM_MODEL, temperature=1.0, top_p=0.9
],
temperature=temperature,
top_p=top_p,
extra_body={"top_k": 64},
extra_body={"top_k": top_k},
response_format=response_format,
)
except APIConnectionError:
return None
@@ -83,13 +106,37 @@ def extract_names(text: str) -> list[str]:
except json.JSONDecodeError:
return []
def extract_keywords(text: str) -> list[str]:
result = call(SYSTEM_PROMPT_KEYWORDS, text)
def extract_keywords(maintitle: str | None, full_content: str | None) -> list[str]:
"""Extracts an article's keywords, identically to the news detail endpoint.
Prompt, input bound, sampling and normalization all come from
keyword_extraction, so both callers write the same keywords into
aktuell_postproc regardless of which one reaches an article first.
"""
user_prompt = keyword_extraction.build_user_prompt(maintitle, full_content)
if not user_prompt:
return []
result = call(
keyword_extraction.KEYWORD_SYSTEM_PROMPT,
user_prompt,
temperature=keyword_extraction.TEMPERATURE,
top_p=keyword_extraction.TOP_P,
top_k=keyword_extraction.TOP_K,
json_schema=keyword_extraction.RESPONSE_SCHEMA,
schema_name=keyword_extraction.SCHEMA_NAME,
)
if result is None:
return []
try:
import json
data = json.loads(result)
return data.get("keywords", [])
except json.JSONDecodeError:
return []
candidates = data.get("keywords")
if not isinstance(candidates, list):
return []
return keyword_extraction.normalize_keywords(candidates)
+7 -4
View File
@@ -20,10 +20,11 @@ def sync_single_news(news_id, max_retries=3):
attempt = 0
while attempt < max_retries:
try:
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
article = es_client.get_entry("aktuell", news_id)["_source"]
news_text = article["full_content"]
is_news_relevant = llm_client.is_news_relevant(news_text)
authors = llm_client.extract_names(news_text)
keywords = llm_client.extract_keywords(news_text)
keywords = llm_client.extract_keywords(article.get("maintitle"), news_text)
new_entry = {
"news_id": news_id,
"relevant": is_news_relevant,
@@ -48,8 +49,10 @@ def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retr
attempt = 0
while attempt < max_retries:
try:
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
keywords = llm_client.extract_keywords(news_text)
article = es_client.get_entry("aktuell", news_id)["_source"]
keywords = llm_client.extract_keywords(
article.get("maintitle"), article["full_content"]
)
if not keywords:
# Empty article or unparseable LLM answer: writing an empty list
# would look like a success and block a later retry.
+3
View File
@@ -18,4 +18,7 @@ RUN pip install --no-cache-dir -r requirements.txt
# Copy the job code.
COPY background-jobs/app/ ./
# Keyword extraction contract shared with the service (inse.news.logic).
COPY service/src/main/inse/news/keyword_extraction.py ./keyword_extraction.py
COPY service/scripts/ ./service/scripts/
@@ -14,6 +14,9 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY background-jobs/app/ ./
# Keyword extraction contract shared with the service (inse.news.logic).
COPY service/src/main/inse/news/keyword_extraction.py ./keyword_extraction.py
# Writes into docker-job_test, leaving production aktuell_postproc untouched.
# A non-postproc target re-extracts entries that already have keywords (real
# content) and updates them in place, keyed on news_id (re-runs overwrite, no
@@ -0,0 +1,85 @@
"""Shared contract for the LLM keyword extraction on news articles.
Two callers extract keywords and write them into the same `keywords` field of
`aktuell_postproc`:
* the background job (`background-jobs/app/sync.py`), which covers the corpus,
* the article detail endpoint (`inse.news.logic`), which fills the gap for
articles the job has not reached yet.
The job images
install neither pydantic nor the rest of the `inse` package; they copy this
single file next to `sync.py`, see `service/scripts/jobs-image/Dockerfile` and
`service/scripts/jobs-image/news-keywords/Dockerfile`.
"""
KEYWORD_LIMIT = 6
# Safety bound on the prompt: articles have about ~2.000
# characters, so this limit is practically never reached. It only prevents a
# crawl result from overflowing the context window or stalling a page load.
KEYWORD_CONTENT_CHARS = 20000
# The result is persisted once and never recomputed,
# so re-running an article has to yield the same keywords.
TEMPERATURE = 0.0
TOP_P = 0.95
TOP_K = 64
SCHEMA_NAME = "keywords"
# Mirrors `NewsKeywords.model_json_schema()`. Spelled out so the job can
# constrain the response without pulling in pydantic; `NewsKeywords` stays the
# parser on the service side.
RESPONSE_SCHEMA = {
"properties": {
"keywords": {
"description": "The extracted keywords from the article.",
"items": {"type": "string"},
"title": "Keywords",
"type": "array",
}
},
"required": ["keywords"],
"title": "NewsKeywords",
"type": "object",
}
KEYWORD_SYSTEM_PROMPT = """\
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {"keywords": ["Schlagwort", "Schlagwort"]}
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
"""
def build_user_prompt(maintitle: str | None, full_content: str | None) -> str | None:
"""Builds the user message, or None if the article carries no text at all."""
text = " ".join(
part
for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS])
if part
).strip()
if not text:
return None
return f"Artikel:\n{text}"
def normalize_keywords(candidates: list) -> list:
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
seen = set()
keywords = []
for item in candidates:
if not isinstance(item, str):
continue
term = item.strip().strip('"').strip()
if term and term.lower() not in seen:
seen.add(term.lower())
keywords.append(term)
return keywords[:KEYWORD_LIMIT]
+17 -35
View File
@@ -18,6 +18,15 @@ from ..snippets import (
snippet_with_context,
)
from ..topics.logic import vector_search_topics_batch
from .keyword_extraction import (
KEYWORD_SYSTEM_PROMPT,
RESPONSE_SCHEMA,
SCHEMA_NAME,
TEMPERATURE,
TOP_P,
build_user_prompt,
normalize_keywords,
)
from .model import (
MatchedTopic,
MentionedPerson,
@@ -49,19 +58,6 @@ CONTENT_HIGHLIGHT = {
"require_field_match": False,
}
KEYWORD_LIMIT = 6
KEYWORD_CONTENT_CHARS = 4000
KEYWORD_SYSTEM_PROMPT = """\
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {"keywords": ["Schlagwort", "Schlagwort"]}
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
"""
RELATED_BLOCK_SIZE = 5
RELATED_TOPIC_K = 1
EXACT_ID_CAP = 1000
@@ -507,22 +503,21 @@ async def _get_article_keywords(
if cached_keywords:
return cached_keywords, postproc_id
text = " ".join(
part for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS]) if part
).strip()
if not text:
user_prompt = build_user_prompt(maintitle, full_content)
if not user_prompt:
return [], postproc_id
response = await llm.call(
system_prompt=KEYWORD_SYSTEM_PROMPT,
user_prompt=f"Artikel:\n{text}",
json_schema=NewsKeywords.model_json_schema(),
schema_name="keywords",
temperature=0.3,
user_prompt=user_prompt,
json_schema=RESPONSE_SCHEMA,
schema_name=SCHEMA_NAME,
temperature=TEMPERATURE,
top_p=TOP_P,
)
try:
keywords = _normalize_keywords(NewsKeywords.model_validate_json(response).keywords)
keywords = normalize_keywords(NewsKeywords.model_validate_json(response).keywords)
except ValidationError:
logger.warning(f"Keyword extraction for news {news_id} returned no valid JSON: {response}")
keywords = []
@@ -549,19 +544,6 @@ async def _get_article_topics(news_id: str, keywords: list) -> list:
return topics
def _normalize_keywords(candidates: list) -> list:
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
seen = set()
keywords = []
for item in candidates:
term = item.strip().strip('"').strip()
if term and term.lower() not in seen:
seen.add(term.lower())
keywords.append(term)
return keywords[:KEYWORD_LIMIT]
async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> str | None:
"""Caches the keywords and returns the postproc document id they landed in."""
try: