add LLM response schema to keyword extraction
This commit is contained in:
@@ -4,16 +4,16 @@
|
||||
Business logic for the "aktuell" news index on the INSE cluster.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from inse.exceptions import ElasticsearchException
|
||||
|
||||
from ..integrations import elasticsearch, llm
|
||||
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
||||
from ..topics.logic import vector_search_topics_batch
|
||||
from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||
from .model import (MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsKeywords, NewsPage)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -294,12 +294,19 @@ async def _get_article_keywords(
|
||||
if not text:
|
||||
return [], postproc_id
|
||||
|
||||
raw = await llm.call(
|
||||
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,
|
||||
)
|
||||
keywords = _parse_keywords(raw)
|
||||
|
||||
try:
|
||||
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 = []
|
||||
|
||||
if keywords:
|
||||
postproc_id = await _store_keywords(news_id, postproc_id, keywords)
|
||||
@@ -359,24 +366,12 @@ async def get_article_topics_from_index(news_id: str) -> list:
|
||||
return matched
|
||||
|
||||
|
||||
def _parse_keywords(raw: str) -> list:
|
||||
raw = (raw or "").strip()
|
||||
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
if isinstance(parsed, list):
|
||||
candidates = parsed
|
||||
elif isinstance(parsed, dict):
|
||||
candidates = parsed.get("keywords", [])
|
||||
else:
|
||||
candidates = []
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
candidates = re.split(r"[,\n]", raw)
|
||||
|
||||
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 = str(item).strip().strip('"').strip()
|
||||
term = item.strip().strip('"').strip()
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
keywords.append(term)
|
||||
|
||||
@@ -3,7 +3,11 @@
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class NewsKeywords(BaseModel):
|
||||
keywords: List[str] = Field(description="The extracted keywords from the article.")
|
||||
|
||||
|
||||
class NewsArticle(BaseModel):
|
||||
|
||||
Reference in New Issue
Block a user