Haiku-Suggester: source_id in Issues-Summary für korrekte Zuordnung
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Dieser Commit ist enthalten in:
@@ -1,261 +1,261 @@
|
|||||||
"""KI-gestützte Quellen-Vorschläge via Haiku."""
|
"""KI-gestützte Quellen-Vorschläge via Haiku."""
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
|
|
||||||
import aiosqlite
|
import aiosqlite
|
||||||
|
|
||||||
from agents.claude_client import call_claude
|
from agents.claude_client import call_claude
|
||||||
from config import CLAUDE_MODEL_FAST
|
from config import CLAUDE_MODEL_FAST
|
||||||
|
|
||||||
logger = logging.getLogger("osint.source_suggester")
|
logger = logging.getLogger("osint.source_suggester")
|
||||||
|
|
||||||
|
|
||||||
async def generate_suggestions(db: aiosqlite.Connection) -> int:
|
async def generate_suggestions(db: aiosqlite.Connection) -> int:
|
||||||
"""Generiert Quellen-Vorschläge basierend auf Health-Checks und Lückenanalyse."""
|
"""Generiert Quellen-Vorschläge basierend auf Health-Checks und Lückenanalyse."""
|
||||||
logger.info("Starte Quellen-Vorschläge via Haiku...")
|
logger.info("Starte Quellen-Vorschläge via Haiku...")
|
||||||
|
|
||||||
# 1. Aktuelle Quellen laden
|
# 1. Aktuelle Quellen laden
|
||||||
cursor = await db.execute(
|
cursor = await db.execute(
|
||||||
"SELECT id, name, url, domain, source_type, category, status, "
|
"SELECT id, name, url, domain, source_type, category, status, "
|
||||||
"article_count, last_seen_at "
|
"article_count, last_seen_at "
|
||||||
"FROM sources WHERE tenant_id IS NULL ORDER BY category, name"
|
"FROM sources WHERE tenant_id IS NULL ORDER BY category, name"
|
||||||
)
|
)
|
||||||
sources = [dict(row) for row in await cursor.fetchall()]
|
sources = [dict(row) for row in await cursor.fetchall()]
|
||||||
|
|
||||||
# 2. Health-Check-Probleme laden
|
# 2. Health-Check-Probleme laden
|
||||||
cursor = await db.execute("""
|
cursor = await db.execute("""
|
||||||
SELECT h.source_id, s.name, s.domain, s.url,
|
SELECT h.source_id, s.name, s.domain, s.url,
|
||||||
h.check_type, h.status, h.message
|
h.check_type, h.status, h.message
|
||||||
FROM source_health_checks h
|
FROM source_health_checks h
|
||||||
JOIN sources s ON s.id = h.source_id
|
JOIN sources s ON s.id = h.source_id
|
||||||
WHERE h.status IN ('error', 'warning')
|
WHERE h.status IN ('error', 'warning')
|
||||||
""")
|
""")
|
||||||
issues = [dict(row) for row in await cursor.fetchall()]
|
issues = [dict(row) for row in await cursor.fetchall()]
|
||||||
|
|
||||||
# 3. Alte pending-Vorschläge entfernen (älter als 30 Tage)
|
# 3. Alte pending-Vorschläge entfernen (älter als 30 Tage)
|
||||||
await db.execute(
|
await db.execute(
|
||||||
"DELETE FROM source_suggestions "
|
"DELETE FROM source_suggestions "
|
||||||
"WHERE status = 'pending' AND created_at < datetime('now', '-30 days')"
|
"WHERE status = 'pending' AND created_at < datetime('now', '-30 days')"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 4. Quellen-Zusammenfassung für Haiku
|
# 4. Quellen-Zusammenfassung für Haiku
|
||||||
categories = {}
|
categories = {}
|
||||||
for s in sources:
|
for s in sources:
|
||||||
cat = s["category"]
|
cat = s["category"]
|
||||||
if cat not in categories:
|
if cat not in categories:
|
||||||
categories[cat] = []
|
categories[cat] = []
|
||||||
categories[cat].append(s)
|
categories[cat].append(s)
|
||||||
|
|
||||||
source_summary = ""
|
source_summary = ""
|
||||||
for cat, cat_sources in sorted(categories.items()):
|
for cat, cat_sources in sorted(categories.items()):
|
||||||
active = [
|
active = [
|
||||||
s for s in cat_sources
|
s for s in cat_sources
|
||||||
if s["status"] == "active" and s["source_type"] != "excluded"
|
if s["status"] == "active" and s["source_type"] != "excluded"
|
||||||
]
|
]
|
||||||
source_summary += f"\n{cat} ({len(active)} aktiv): "
|
source_summary += f"\n{cat} ({len(active)} aktiv): "
|
||||||
source_summary += ", ".join(s["name"] for s in active[:10])
|
source_summary += ", ".join(s["name"] for s in active[:10])
|
||||||
if len(active) > 10:
|
if len(active) > 10:
|
||||||
source_summary += f" ... (+{len(active) - 10} weitere)"
|
source_summary += f" ... (+{len(active) - 10} weitere)"
|
||||||
|
|
||||||
issues_summary = ""
|
issues_summary = ""
|
||||||
if issues:
|
if issues:
|
||||||
issues_summary = "\n\nProbleme gefunden:\n"
|
issues_summary = "\n\nProbleme gefunden:\n"
|
||||||
for issue in issues[:20]:
|
for issue in issues[:20]:
|
||||||
issues_summary += (
|
issues_summary += (
|
||||||
f"- {issue['name']} ({issue['domain']}): "
|
f"- [source_id={issue['source_id']}] {issue['name']} ({issue['domain']}): "
|
||||||
f"{issue['check_type']} = {issue['status']} - {issue['message']}\n"
|
f"{issue['check_type']} = {issue['status']} - {issue['message']}\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
prompt = f"""Du bist ein OSINT-Analyst und verwaltest die Quellensammlung eines Lagebildmonitors für Sicherheitsbehörden.
|
prompt = f"""Du bist ein OSINT-Analyst und verwaltest die Quellensammlung eines Lagebildmonitors für Sicherheitsbehörden.
|
||||||
|
|
||||||
Aktuelle Quellensammlung:{source_summary}{issues_summary}
|
Aktuelle Quellensammlung:{source_summary}{issues_summary}
|
||||||
|
|
||||||
Aufgabe: Analysiere die Quellensammlung und schlage Verbesserungen vor.
|
Aufgabe: Analysiere die Quellensammlung und schlage Verbesserungen vor.
|
||||||
|
|
||||||
Beachte:
|
Beachte:
|
||||||
1. Bei Problemen (nicht erreichbar, leere Feeds): Schlage "deactivate_source" vor mit der source_id
|
1. Bei Problemen (nicht erreichbar, leere Feeds): Schlage "deactivate_source" vor und setze "source_id" auf die ID aus [source_id=X] in der Problemliste
|
||||||
2. Fehlende wichtige OSINT-Quellen: Schlage "add_source" mit konkreter RSS-Feed-URL vor
|
2. Fehlende wichtige OSINT-Quellen: Schlage "add_source" mit konkreter RSS-Feed-URL vor
|
||||||
3. Fokus auf deutschsprachige + wichtige internationale Nachrichtenquellen
|
3. Fokus auf deutschsprachige + wichtige internationale Nachrichtenquellen
|
||||||
4. Nur Quellen vorschlagen, die NICHT bereits vorhanden sind
|
4. Nur Quellen vorschlagen, die NICHT bereits vorhanden sind
|
||||||
5. Maximal 5 Vorschläge
|
5. Maximal 5 Vorschläge
|
||||||
|
|
||||||
Antworte NUR mit einem JSON-Array. Jedes Element:
|
Antworte NUR mit einem JSON-Array. Jedes Element:
|
||||||
{{
|
{{
|
||||||
"type": "add_source|deactivate_source|fix_url|remove_source",
|
"type": "add_source|deactivate_source|fix_url|remove_source",
|
||||||
"title": "Kurzer Titel",
|
"title": "Kurzer Titel",
|
||||||
"description": "Begründung",
|
"description": "Begründung",
|
||||||
"priority": "low|medium|high",
|
"priority": "low|medium|high",
|
||||||
"source_id": null,
|
"source_id": null,
|
||||||
"data": {{
|
"data": {{
|
||||||
"name": "Anzeigename",
|
"name": "Anzeigename",
|
||||||
"url": "https://...",
|
"url": "https://...",
|
||||||
"domain": "example.de",
|
"domain": "example.de",
|
||||||
"category": "international|nachrichtenagentur|qualitaetszeitung|behoerde|fachmedien|think-tank|regional|sonstige"
|
"category": "international|nachrichtenagentur|qualitaetszeitung|behoerde|fachmedien|think-tank|regional|sonstige"
|
||||||
}}
|
}}
|
||||||
}}
|
}}
|
||||||
|
|
||||||
Nur das JSON-Array, kein anderer Text."""
|
Nur das JSON-Array, kein anderer Text."""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response, usage = await call_claude(
|
response, usage = await call_claude(
|
||||||
prompt, tools=None, model=CLAUDE_MODEL_FAST,
|
prompt, tools=None, model=CLAUDE_MODEL_FAST,
|
||||||
)
|
)
|
||||||
|
|
||||||
json_match = re.search(r'\[.*\]', response, re.DOTALL)
|
json_match = re.search(r'\[.*\]', response, re.DOTALL)
|
||||||
if not json_match:
|
if not json_match:
|
||||||
logger.warning("Keine Vorschläge von Haiku erhalten (kein JSON)")
|
logger.warning("Keine Vorschläge von Haiku erhalten (kein JSON)")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
suggestions = json.loads(json_match.group(0))
|
suggestions = json.loads(json_match.group(0))
|
||||||
|
|
||||||
count = 0
|
count = 0
|
||||||
for suggestion in suggestions[:5]:
|
for suggestion in suggestions[:5]:
|
||||||
stype = suggestion.get("type", "add_source")
|
stype = suggestion.get("type", "add_source")
|
||||||
title = suggestion.get("title", "")
|
title = suggestion.get("title", "")
|
||||||
desc = suggestion.get("description", "")
|
desc = suggestion.get("description", "")
|
||||||
priority = suggestion.get("priority", "medium")
|
priority = suggestion.get("priority", "medium")
|
||||||
source_id = suggestion.get("source_id")
|
source_id = suggestion.get("source_id")
|
||||||
data = json.dumps(
|
data = json.dumps(
|
||||||
suggestion.get("data", {}), ensure_ascii=False,
|
suggestion.get("data", {}), ensure_ascii=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
# source_id validieren (muss existieren oder None sein)
|
# source_id validieren (muss existieren oder None sein)
|
||||||
if source_id is not None:
|
if source_id is not None:
|
||||||
cursor = await db.execute(
|
cursor = await db.execute(
|
||||||
"SELECT id FROM sources WHERE id = ?", (source_id,),
|
"SELECT id FROM sources WHERE id = ?", (source_id,),
|
||||||
)
|
)
|
||||||
if not await cursor.fetchone():
|
if not await cursor.fetchone():
|
||||||
source_id = None
|
source_id = None
|
||||||
|
|
||||||
# Duplikat-Check
|
# Duplikat-Check
|
||||||
cursor = await db.execute(
|
cursor = await db.execute(
|
||||||
"SELECT id FROM source_suggestions "
|
"SELECT id FROM source_suggestions "
|
||||||
"WHERE title = ? AND status = 'pending'",
|
"WHERE title = ? AND status = 'pending'",
|
||||||
(title,),
|
(title,),
|
||||||
)
|
)
|
||||||
if await cursor.fetchone():
|
if await cursor.fetchone():
|
||||||
continue
|
continue
|
||||||
|
|
||||||
await db.execute(
|
await db.execute(
|
||||||
"INSERT INTO source_suggestions "
|
"INSERT INTO source_suggestions "
|
||||||
"(suggestion_type, title, description, source_id, "
|
"(suggestion_type, title, description, source_id, "
|
||||||
"suggested_data, priority, status) "
|
"suggested_data, priority, status) "
|
||||||
"VALUES (?, ?, ?, ?, ?, ?, 'pending')",
|
"VALUES (?, ?, ?, ?, ?, ?, 'pending')",
|
||||||
(stype, title, desc, source_id, data, priority),
|
(stype, title, desc, source_id, data, priority),
|
||||||
)
|
)
|
||||||
count += 1
|
count += 1
|
||||||
|
|
||||||
await db.commit()
|
await db.commit()
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Quellen-Vorschläge: {count} neue Vorschläge generiert "
|
f"Quellen-Vorschläge: {count} neue Vorschläge generiert "
|
||||||
f"(Haiku: {usage.input_tokens} in / {usage.output_tokens} out / "
|
f"(Haiku: {usage.input_tokens} in / {usage.output_tokens} out / "
|
||||||
f"${usage.cost_usd:.4f})"
|
f"${usage.cost_usd:.4f})"
|
||||||
)
|
)
|
||||||
return count
|
return count
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Fehler bei Quellen-Vorschlägen: {e}", exc_info=True)
|
logger.error(f"Fehler bei Quellen-Vorschlägen: {e}", exc_info=True)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
async def apply_suggestion(
|
async def apply_suggestion(
|
||||||
db: aiosqlite.Connection, suggestion_id: int, accept: bool,
|
db: aiosqlite.Connection, suggestion_id: int, accept: bool,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Wendet einen Vorschlag an oder lehnt ihn ab."""
|
"""Wendet einen Vorschlag an oder lehnt ihn ab."""
|
||||||
cursor = await db.execute(
|
cursor = await db.execute(
|
||||||
"SELECT * FROM source_suggestions WHERE id = ?", (suggestion_id,),
|
"SELECT * FROM source_suggestions WHERE id = ?", (suggestion_id,),
|
||||||
)
|
)
|
||||||
suggestion = await cursor.fetchone()
|
suggestion = await cursor.fetchone()
|
||||||
if not suggestion:
|
if not suggestion:
|
||||||
raise ValueError("Vorschlag nicht gefunden")
|
raise ValueError("Vorschlag nicht gefunden")
|
||||||
|
|
||||||
suggestion = dict(suggestion)
|
suggestion = dict(suggestion)
|
||||||
|
|
||||||
if suggestion["status"] != "pending":
|
if suggestion["status"] != "pending":
|
||||||
raise ValueError(f"Vorschlag bereits {suggestion['status']}")
|
raise ValueError(f"Vorschlag bereits {suggestion['status']}")
|
||||||
|
|
||||||
new_status = "accepted" if accept else "rejected"
|
new_status = "accepted" if accept else "rejected"
|
||||||
result = {"status": new_status, "action": None}
|
result = {"status": new_status, "action": None}
|
||||||
|
|
||||||
if accept:
|
if accept:
|
||||||
stype = suggestion["suggestion_type"]
|
stype = suggestion["suggestion_type"]
|
||||||
data = (
|
data = (
|
||||||
json.loads(suggestion["suggested_data"])
|
json.loads(suggestion["suggested_data"])
|
||||||
if suggestion["suggested_data"]
|
if suggestion["suggested_data"]
|
||||||
else {}
|
else {}
|
||||||
)
|
)
|
||||||
|
|
||||||
if stype == "add_source":
|
if stype == "add_source":
|
||||||
name = data.get("name", "Unbenannt")
|
name = data.get("name", "Unbenannt")
|
||||||
url = data.get("url")
|
url = data.get("url")
|
||||||
domain = data.get("domain", "")
|
domain = data.get("domain", "")
|
||||||
category = data.get("category", "sonstige")
|
category = data.get("category", "sonstige")
|
||||||
source_type = "rss_feed" if url and any(
|
source_type = "rss_feed" if url and any(
|
||||||
x in (url or "").lower()
|
x in (url or "").lower()
|
||||||
for x in ("rss", "feed", "xml", "atom")
|
for x in ("rss", "feed", "xml", "atom")
|
||||||
) else "web_source"
|
) else "web_source"
|
||||||
|
|
||||||
if url:
|
if url:
|
||||||
cursor = await db.execute(
|
cursor = await db.execute(
|
||||||
"SELECT id FROM sources WHERE url = ? AND tenant_id IS NULL",
|
"SELECT id FROM sources WHERE url = ? AND tenant_id IS NULL",
|
||||||
(url,),
|
(url,),
|
||||||
)
|
)
|
||||||
if await cursor.fetchone():
|
if await cursor.fetchone():
|
||||||
result["action"] = "übersprungen (URL bereits vorhanden)"
|
result["action"] = "übersprungen (URL bereits vorhanden)"
|
||||||
new_status = "rejected"
|
new_status = "rejected"
|
||||||
else:
|
else:
|
||||||
await db.execute(
|
await db.execute(
|
||||||
"INSERT INTO sources "
|
"INSERT INTO sources "
|
||||||
"(name, url, domain, source_type, category, status, "
|
"(name, url, domain, source_type, category, status, "
|
||||||
"added_by, tenant_id) "
|
"added_by, tenant_id) "
|
||||||
"VALUES (?, ?, ?, ?, ?, 'active', 'haiku-vorschlag', NULL)",
|
"VALUES (?, ?, ?, ?, ?, 'active', 'haiku-vorschlag', NULL)",
|
||||||
(name, url, domain, source_type, category),
|
(name, url, domain, source_type, category),
|
||||||
)
|
)
|
||||||
result["action"] = f"Quelle '{name}' angelegt"
|
result["action"] = f"Quelle '{name}' angelegt"
|
||||||
else:
|
else:
|
||||||
result["action"] = "übersprungen (keine URL)"
|
result["action"] = "übersprungen (keine URL)"
|
||||||
new_status = "rejected"
|
new_status = "rejected"
|
||||||
|
|
||||||
elif stype == "deactivate_source":
|
elif stype == "deactivate_source":
|
||||||
source_id = suggestion["source_id"]
|
source_id = suggestion["source_id"]
|
||||||
if source_id:
|
if source_id:
|
||||||
await db.execute(
|
await db.execute(
|
||||||
"UPDATE sources SET status = 'inactive' WHERE id = ?",
|
"UPDATE sources SET status = 'inactive' WHERE id = ?",
|
||||||
(source_id,),
|
(source_id,),
|
||||||
)
|
)
|
||||||
result["action"] = "Quelle deaktiviert"
|
result["action"] = "Quelle deaktiviert"
|
||||||
else:
|
else:
|
||||||
result["action"] = "übersprungen (keine source_id)"
|
result["action"] = "übersprungen (keine source_id)"
|
||||||
|
|
||||||
elif stype == "remove_source":
|
elif stype == "remove_source":
|
||||||
source_id = suggestion["source_id"]
|
source_id = suggestion["source_id"]
|
||||||
if source_id:
|
if source_id:
|
||||||
await db.execute(
|
await db.execute(
|
||||||
"DELETE FROM sources WHERE id = ?", (source_id,),
|
"DELETE FROM sources WHERE id = ?", (source_id,),
|
||||||
)
|
)
|
||||||
result["action"] = "Quelle gelöscht"
|
result["action"] = "Quelle gelöscht"
|
||||||
else:
|
else:
|
||||||
result["action"] = "übersprungen (keine source_id)"
|
result["action"] = "übersprungen (keine source_id)"
|
||||||
|
|
||||||
elif stype == "fix_url":
|
elif stype == "fix_url":
|
||||||
source_id = suggestion["source_id"]
|
source_id = suggestion["source_id"]
|
||||||
new_url = data.get("url")
|
new_url = data.get("url")
|
||||||
if source_id and new_url:
|
if source_id and new_url:
|
||||||
await db.execute(
|
await db.execute(
|
||||||
"UPDATE sources SET url = ? WHERE id = ?",
|
"UPDATE sources SET url = ? WHERE id = ?",
|
||||||
(new_url, source_id),
|
(new_url, source_id),
|
||||||
)
|
)
|
||||||
result["action"] = f"URL aktualisiert auf {new_url}"
|
result["action"] = f"URL aktualisiert auf {new_url}"
|
||||||
else:
|
else:
|
||||||
result["action"] = "übersprungen (keine source_id oder URL)"
|
result["action"] = "übersprungen (keine source_id oder URL)"
|
||||||
|
|
||||||
await db.execute(
|
await db.execute(
|
||||||
"UPDATE source_suggestions SET status = ?, reviewed_at = CURRENT_TIMESTAMP "
|
"UPDATE source_suggestions SET status = ?, reviewed_at = CURRENT_TIMESTAMP "
|
||||||
"WHERE id = ?",
|
"WHERE id = ?",
|
||||||
(new_status, suggestion_id),
|
(new_status, suggestion_id),
|
||||||
)
|
)
|
||||||
await db.commit()
|
await db.commit()
|
||||||
|
|
||||||
result["status"] = new_status
|
result["status"] = new_status
|
||||||
return result
|
return result
|
||||||
|
|||||||
In neuem Issue referenzieren
Einen Benutzer sperren