Phase 1 M6-R1 (Deep Research in OpenWebUI) + Phase 2 M8 geplant (GPT Researcher hinter IAP)

Phase 1 (GNAI-022, umgesetzt 14.11.2026 auf ghostnet-ki):
- Pipe-Function gnai-deep-research (files/gnai-deep-research-pipe.py, sha256-gepinnt):
  iterativer plan->SearXNG->fetch->Synthese-Loop mit [n]-Zitationen, Engine direkt
  via http://llama-cpp:8080/v1, SSRF-Guard, Fetch-Caps, Streaming via event_emitter
- open_webui-Rolle: DB-Seeding (function-Tabelle type=pipe, is_active, public read
  access_grant) + sha256-Verify + PIPE-OK-Verify; Defaults/Valves in defaults/main.yml
- Verifikation: webui.yml produktiver Lauf ok=35 changed=3 failed=0, Health 200,
  zweiter Lauf idempotent changed=0; E2E via API (temp. Key) ist Betreiberschritt (GNAI-022 Abschnitt 5)

Phase 2 (GNAI-023, M8 in GNAI-001): GPT Researcher (30.683 Sterne, v3.8.0) auf
ghostnet-ki im Production-Netz, LLM via OPENAI_BASE_URL=llama.cpp, Suche ueber
bestehende SearXNG; oeffentlich nur research.ghostnet.selfhost.eu via NPM +
oauth2-proxy v7.15.5 (auth_request, Keycloak-OIDC Realm Ghost.net, Client
gnai-research) — Härtungs-Checkliste in GNAI-023 Abschnitt 3/4.

Doku: GNAI-000/GNAI-001/ai-README aktualisiert; GNAI-022 (Deep Research) und
GNAI-023 (IAP-Plan) neu.

Hinweis: roles/open_webui und ai/README enthalten neben diesen Aenderungen den
bislang uncommitteten Theme-Stand (GNAI-021, produktiv live seit 14.11.2026).

Link-Check: nur bekannte GNAI-021-Links broken (Datei fehlt im Working Tree).

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
2026-11-15 05:36:42 +01:00
co-authored by Mistral Vibe
parent b9b7a982ea
commit 3df56d62c4
10 changed files with 807 additions and 3 deletions
@@ -43,3 +43,17 @@ Embedding-Modell wird nicht benötigt.
Lang laufende Research-Loops (mehrere search_web/fetch_url-Runden) brauchen
auf dem NPM-Proxy-Host `chat.ghostnet.selfhost.eu` erhöhte Proxy-Timeouts
(siehe GNAI-020 Abschnitt NPM).
## Deep Research (GNAI-022, M6-R1 / Phase 1)
Die Pipe-Function `gnai-deep-research` (`files/gnai-deep-research-pipe.py`,
Content per sha256 gepinnt) wird idempotent in die `function`-Tabelle von
`webui.db` geseeded (type `pipe`, `is_active=1`) und erhält einen public read
`access_grant` (resource_type `model`) — dadurch erscheint sie im
Model-Selector als „gnai-deep-research". Valves (Engine, SearXNG, Iterationen,
Fetch-Limits) liegen in `defaults/main.yml`. Der Loop ruft die Engine direkt
über `http://llama-cpp:8080/v1` (kein OWUI-Auth nötig) und SearXNG über
`http://searxng:8080`; Seiten-Fetch mit SSRF-Guard (keine privaten/loopback/
link-local IPs), Redirect-Chain mit Re-Validierung, Content-Cap und Timeout.
Nach jeder Code-Änderung `sha256sum` neu berechnen und
`open_webui_deep_research_pipe_sha256` aktualisieren.
@@ -33,6 +33,25 @@ open_webui_engine_model_id: swift-1.5-qwen3.8-27b-q6k
# with a public read grant. API callers pass this id in `tool_ids`.
open_webui_web_search_tool_id: gnai-web-search
# Deep-Research pipe (GNAI-022, M6-R1 / Roadmap Phase 1): iterative
# plan->search->fetch->synthesize loop exposed as a pipe "model" in the
# model selector. Seeded idempotently into webui.db; content pinned by
# sha256 (recompute after every edit of files/gnai-deep-research-pipe.py:
# sha256sum files/gnai-deep-research-pipe.py).
open_webui_deep_research_function_id: gnai-deep-research
open_webui_deep_research_pipe_sha256: "1458b6a91b0aa159954e58318e3d263726e743b3c4d6088cadfe26c40a2400d7"
open_webui_deep_research_valves:
ENGINE_BASE_URL: "{{ open_webui_engine_base_url }}"
ENGINE_MODEL_ID: "{{ open_webui_engine_model_id }}"
SEARXNG_URL: "http://searxng:8080"
MAX_ITERATIONS: 5
QUERIES_PER_ROUND: 4
RESULTS_PER_QUERY: 6
PAGES_PER_ROUND: 5
FETCH_TIMEOUT_S: 12.0
FETCH_MAX_BYTES: 200000
TEMPERATURE: 0.3
# Engine endpoint inside the shared Production network. llama.cpp itself
# has no auth; OpenWebUI just needs a non-empty key value, supplied via a
# Podman secret (never in git).
@@ -0,0 +1,326 @@
"""
title: gnai-deep-research
author: ghostnet.ai
description: Iterativer Deep-Research-Loop (plan -> SearXNG-Suche -> Seiten-Fetch -> Synthese mit Quellenangaben) als Pipe-Model. Ruft die Production-Engine direkt ueber das interne Netz (llama.cpp, kein Host-Port) und die bestehende SearXNG-Instanz. Läuft serverseitig in OpenWebUI (v0.13.3).
license: MIT
"""
import ipaddress
import json
import re
import socket
from typing import Any, AsyncIterator
from urllib.parse import urlparse
import httpx
from pydantic import BaseModel, Field
try:
from bs4 import BeautifulSoup
except ImportError: # pragma: no cover - bs4 ist im OpenWebUI-Image vorhanden
BeautifulSoup = None
PLANNER_SYSTEM = (
"You are a research planner. Given the user's research question and the "
"conversation so far, produce a JSON object {\"queries\": [str, ...]} with "
"up to {qpr} concrete, diverse web search queries (English and the user's "
"language). Answer with JSON only, no prose."
)
SYNTH_SYSTEM = (
"You are a research analyst. You receive search results and fetched page "
"excerpts, each tagged with a citation number [n]. Decide whether the "
"material answers the user's research question.\n"
"If more research is needed, answer JSON only: "
"{\"status\": \"continue\", \"next_queries\": [str, ...]} with up to {qpr} "
"follow-up queries that close the gaps.\n"
"If done, answer JSON only: {\"status\": \"done\", \"report\": \"<markdown "
"report in the user's language, cite claims with [n] markers>\"}.\n"
"Never invent citations; only use numbers of sources actually provided."
)
class Pipe:
class Valves(BaseModel):
ENGINE_BASE_URL: str = Field(
default="http://llama-cpp:8080/v1",
description="OpenAI-kompatibles Engine-Ende im Production-Netz (llama.cpp, ohne Auth).",
)
ENGINE_MODEL_ID: str = Field(
default="swift-1.5-qwen3.8-27b-q6k",
description="Modell- alias auf der Engine (muss zum Model-Store passen).",
)
SEARXNG_URL: str = Field(
default="http://searxng:8080",
description="Interne SearXNG-Instanz (Egress-Netz).",
)
MAX_ITERATIONS: int = Field(default=5, ge=1, le=10)
QUERIES_PER_ROUND: int = Field(default=4, ge=1, le=8)
RESULTS_PER_QUERY: int = Field(default=6, ge=1, le=20)
PAGES_PER_ROUND: int = Field(default=5, ge=1, le=10)
FETCH_TIMEOUT_S: float = Field(default=12.0, gt=0, le=60)
FETCH_MAX_BYTES: int = Field(default=200_000, ge=10_000, le=1_000_000)
TEMPERATURE: float = Field(default=0.3, ge=0, le=2)
def __init__(self):
self.valves = self.Valves()
# ---------- helpers ----------
@staticmethod
def _user_text(body: dict, metadata: dict | None) -> str:
md = metadata or {}
prompt = md.get("user_prompt")
if prompt:
return str(prompt)
for msg in reversed(body.get("messages", [])):
if msg.get("role") != "user":
continue
content = msg.get("content")
if isinstance(content, str):
return content
if isinstance(content, list):
return "\n".join(
p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") == "text"
)
return ""
@staticmethod
def _history(body: dict) -> list[dict]:
out = []
for msg in body.get("messages", []):
if msg.get("role") not in ("user", "assistant"):
continue
content = msg.get("content")
if isinstance(content, list):
content = "\n".join(
p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") == "text"
)
if isinstance(content, str) and content:
out.append({"role": msg["role"], "content": content})
return out[-8:]
@staticmethod
def _extract_json(text: str) -> dict:
text = text.strip()
m = re.search(r"\{.*\}", text, re.DOTALL)
if m:
try:
return json.loads(m.group(0))
except json.JSONDecodeError:
pass
try:
return json.loads(text)
except json.JSONDecodeError:
return {}
@staticmethod
def _safe_url(url: str) -> bool:
"""SSRF-Schutz: nur http(s), keine privaten/loopback/reserved IPs."""
try:
p = urlparse(url)
if p.scheme not in ("http", "https") or not p.hostname:
return False
if p.hostname.lower() in ("localhost", "127.0.0.1", "::1"):
return False
infos = socket.getaddrinfo(p.hostname, None)
for info in infos:
ip = ipaddress.ip_address(info[4][0])
if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved:
return False
return True
except Exception:
return False
async def _engine(self, client: httpx.AsyncClient, messages: list[dict]) -> str:
resp = await client.post(
f"{self.valves.ENGINE_BASE_URL.rstrip('/')}/chat/completions",
json={
"model": self.valves.ENGINE_MODEL_ID,
"messages": messages,
"temperature": self.valves.TEMPERATURE,
"stream": False,
},
timeout=180.0,
)
resp.raise_for_status()
data = resp.json()
return data["choices"][0]["message"]["content"] or ""
async def _search(self, client: httpx.AsyncClient, query: str) -> list[dict]:
try:
resp = await client.get(
f"{self.valves.SEARXNG_URL.rstrip('/')}/search",
params={"q": query, "format": "json", "safesearch": "1"},
timeout=20.0,
)
resp.raise_for_status()
results = resp.json().get("results", [])
return [
{"url": r.get("url", ""), "title": r.get("title", ""), "snippet": r.get("content", "")}
for r in results
if r.get("url")
][: self.valves.RESULTS_PER_QUERY]
except Exception:
return []
async def _fetch(self, client: httpx.AsyncClient, url: str) -> str:
"""holt eine Seite mit Redirect-Chain (jede Hop neu validiert) und Content-Cap."""
current = url
for _ in range(3):
if not self._safe_url(current):
return ""
try:
resp = await client.get(
current,
follow_redirects=False,
timeout=self.valves.FETCH_TIMEOUT_S,
headers={"User-Agent": "gnai-deep-research/0.1 (+selfhosted research pipe)"},
)
except Exception:
return ""
if resp.is_redirect:
location = resp.headers.get("location", "")
if not location:
return ""
from urllib.parse import urljoin
current = urljoin(current, location)
continue
if resp.status_code != 200:
return ""
ctype = resp.headers.get("content-type", "")
if "html" not in ctype and "text" not in ctype and "json" not in ctype and "xml" not in ctype:
return ""
raw = b""
async for chunk in resp.aiter_bytes(65536):
raw += chunk
if len(raw) > self.valves.FETCH_MAX_BYTES:
raw = raw[: self.valves.FETCH_MAX_BYTES]
break
text = raw.decode("utf-8", errors="replace")
if "html" in ctype and BeautifulSoup is not None:
text = BeautifulSoup(text, "html.parser").get_text("\n")
text = re.sub(r"\n{3,}", "\n\n", text)
return text[: self.valves.FETCH_MAX_BYTES]
return ""
async def _emit(self, emitter: Any, text: str) -> None:
if emitter is not None:
try:
await emitter({"type": "status", "data": {"description": text, "done": False}})
except Exception:
pass
# ---------- pipe ----------
async def pipe(
self,
body: dict,
__metadata__: dict | None = None,
__user__: dict | None = None,
__event_emitter__: Any = None,
) -> AsyncIterator[str] | str:
v = self.valves
question = self._user_text(body, __metadata__)
if not question:
return "No user question found in the request."
history = self._history(body)
if history and history[-1]["role"] == "user" and history[-1]["content"] == question:
history = history[:-1]
sources: list[dict] = [] # {n, url, title}
seen_urls: set[str] = set()
async def run() -> AsyncIterator[str]:
nonlocal sources
async with httpx.AsyncClient(timeout=30.0) as client:
queries: list[str] = []
for round_no in range(1, v.MAX_ITERATIONS + 1):
# 1) planen (Runde 1) bzw. Luecken schliessen (Folgerunden)
if round_no == 1 or not queries:
plan_msgs = [
{"role": "system", "content": PLANNER_SYSTEM.format(qpr=v.QUERIES_PER_ROUND)},
*history,
{"role": "user", "content": f"Research question: {question}"},
]
await self._emit(__event_emitter__, f"Runde {round_no}: plane Suchanfragen …")
plan = self._extract_json(await self._engine(client, plan_msgs))
queries = [q for q in plan.get("queries", []) if isinstance(q, str)][: v.QUERIES_PER_ROUND]
if not queries:
queries = [question]
# 2) suchen
await self._emit(__event_emitter__, f"Runde {round_no}: {len(queries)} Suchanfragen …")
found: list[dict] = []
for q in queries:
for r in await self._search(client, q):
if r["url"] not in seen_urls:
seen_urls.add(r["url"])
r["query"] = q
found.append(r)
# 3) Top-Seiten fetchen (mit SSRF-Guard)
pages: list[dict] = []
for r in found[: v.PAGES_PER_ROUND]:
await self._emit(__event_emitter__, f"Lese {r['url'][:100]} …")
text = await self._fetch(client, r["url"])
if text:
sources.append({"n": len(sources) + 1, "url": r["url"], "title": r["title"] or r["url"]})
pages.append({"n": sources[-1]["n"], "url": r["url"], "title": sources[-1]["title"], "text": text[:8000]})
findings = "\n\n".join(
f"[{p['n']}] {p['title']} ({p['url']})\n{p['text']}" for p in pages
) or "(keine neuen Seiteninhalte)"
snippets = "\n".join(
f"- {r['title']}: {r['snippet'][:200]} ({r['url']})" for r in found[:10]
)
# 4) synthetisieren / Luecken bewerten
synth_msgs = [
{"role": "system", "content": SYNTH_SYSTEM.format(qpr=v.QUERIES_PER_ROUND)},
*history,
{"role": "user", "content": f"Research question: {question}\n\nSearch-result snippets:\n{snippets}\n\nFetched pages:\n{findings}"},
]
await self._emit(__event_emitter__, f"Runde {round_no}: synthetisiere Zwischenergebnis …")
verdict = self._extract_json(await self._engine(client, synth_msgs))
if verdict.get("status") == "done" and verdict.get("report"):
report = str(verdict["report"])
if sources:
report += "\n\n## Quellen\n" + "\n".join(
f"[{s['n']}] {s['title']} — {s['url']}" for s in sources
)
yield report
return
queries = [
q for q in verdict.get("next_queries", []) if isinstance(q, str)
][: v.QUERIES_PER_ROUND]
if not queries:
break
# Max-Iterationen erreicht: trotzdem ein Report aus dem akkumulierten Material
if sources:
final_msgs = [
{"role": "system", "content": SYNTH_SYSTEM.format(qpr=0)},
*history,
{"role": "user", "content": f"Research question: {question}\n\nAccumulated sources (iteration limit reached, write the best possible report now):\n" + "\n\n".join(
f"[{s['n']}] {s['title']} ({s['url']})" for s in sources
)},
]
verdict = self._extract_json(await self._engine(client, final_msgs))
report = verdict.get("report") or "(kein Report erzeugt)"
report += "\n\n## Quellen\n" + "\n".join(
f"[{s['n']}] {s['title']} — {s['url']}" for s in sources
)
yield report
return
yield "Recherche ohne brauchbare Quellen. Bitte Frage präzisieren."
if body.get("stream"):
return run()
# non-streaming: Generator konsumieren und als eine Completion zurückgeben
chunks: list[str] = []
async for chunk in run():
chunks.append(chunk)
return "".join(chunks)
@@ -420,6 +420,121 @@
changed_when: false
when: not ansible_check_mode
- name: Stage the deep-research pipe source and verify its pinned sha256
# GNAI-022 (M6-R1 Phase 1): the pipe content is pinned by sha256 so a
# silent upstream edit can never reach the server; the DB sync task below
# reports the real change.
block:
- name: Stage the pipe source
ansible.builtin.copy:
src: files/gnai-deep-research-pipe.py
dest: /tmp/gnai-deep-research-pipe.py
mode: "0600"
changed_when: false
- name: Verify the pipe sha256 against the pinned value
ansible.builtin.command:
argv:
- sha256sum
- /tmp/gnai-deep-research-pipe.py
register: open_webui_pipe_hash
changed_when: false
failed_when: >-
open_webui_pipe_hash.stdout.split()[0] != open_webui_deep_research_pipe_sha256
- name: Ensure the deep-research pipe exists, is active and publicly readable in OpenWebUI
# Pipe functions (type='pipe') appear as models in the selector with
# id=function.id; the public read grant on resource_type='model' makes it
# visible to every authenticated OIDC user. Valves are stored as plain
# JSON (no secret fields). Idempotent; touches only the app DB.
ansible.builtin.shell: |
set -euo pipefail
python3 - "{{ open_webui_data_dir }}/webui.db" \
/tmp/gnai-deep-research-pipe.py \
'{{ open_webui_deep_research_valves | to_json }}' \
"{{ open_webui_deep_research_function_id }}" <<'PYEOF'
import json, sqlite3, sys, time, uuid
db, content_path, valves_raw, fn_id = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
content = open(content_path).read()
valves = json.loads(valves_raw)
meta = json.dumps({"description": "Iterativer Deep-Research-Loop (plan -> SearXNG -> fetch -> Synthese) auf der Production-Engine. GNAI-022 / GNAI-001 M6-R1."})
now = int(time.time())
con = sqlite3.connect(db)
changed = False
row = con.execute("select content, valves, meta, type, is_active, is_global from function where id=?", (fn_id,)).fetchone()
if not row:
con.execute(
"insert into function (id, version_id, user_id, name, type, content, meta, valves, is_active, is_global, updated_at, created_at)"
" values (?,?,?,?,?,?,?,?,?,?,?,?)",
(fn_id, str(uuid.uuid4()), "openwebui", "gnai-deep-research", "pipe", content, meta, json.dumps(valves), 1, 0, now, now),
)
changed = True
elif (
row[0] != content
or json.loads(row[1] or "{}") != valves
or row[2] != meta
or row[3] != "pipe"
or row[4] != 1
or row[5] != 0
):
con.execute(
"update function set content=?, valves=?, meta=?, type='pipe', is_active=1, is_global=0, updated_at=?, version_id=? where id=?",
(content, json.dumps(valves), meta, now, str(uuid.uuid4()), fn_id),
)
changed = True
grant = con.execute(
"select id from access_grant where resource_type='model' and resource_id=? and principal_type='user' and principal_id='*' and permission='read'",
(fn_id,),
).fetchone()
if not grant:
con.execute(
"insert into access_grant (id, resource_type, resource_id, principal_type, principal_id, permission, created_at)"
" values (?,?,?,?,?,?,?)",
(str(uuid.uuid4()), "model", fn_id, "user", "*", "read", now),
)
changed = True
con.commit()
print("CHANGED" if changed else "UNCHANGED")
PYEOF
args:
executable: /bin/bash
when: not ansible_check_mode
register: open_webui_pipe_sync
changed_when: open_webui_pipe_sync.stdout_lines | first == 'CHANGED'
- name: Verify the deep-research pipe row and grant in webui.db
ansible.builtin.shell: |
set -euo pipefail
python3 - "{{ open_webui_data_dir }}/webui.db" "{{ open_webui_deep_research_function_id }}" <<'PYEOF'
import json, sqlite3, sys
con = sqlite3.connect(sys.argv[1])
fn_id = sys.argv[2]
row = con.execute("select type, is_active, valves from function where id=?", (fn_id,)).fetchone()
assert row, "function row missing"
assert row[0] == "pipe" and row[1] == 1, "pipe not active"
valves = json.loads(row[2])
assert valves.get("SEARXNG_URL"), "SEARXNG_URL valve missing"
grant = con.execute(
"select count(*) from access_grant where resource_type='model' and resource_id=? and principal_type='user' and principal_id='*' and permission='read'",
(fn_id,),
).fetchone()[0]
assert grant == 1, "public read grant missing"
print("PIPE-OK")
PYEOF
args:
executable: /bin/bash
register: open_webui_pipe_verify
changed_when: false
failed_when: "'PIPE-OK' not in open_webui_pipe_verify.stdout"
when: not ansible_check_mode
- name: Remove the staged pipe source
ansible.builtin.file:
path: /tmp/gnai-deep-research-pipe.py
state: absent
changed_when: false
when: not ansible_check_mode
- name: Wait for the OpenWebUI health endpoint
ansible.builtin.uri:
url: "http://{{ open_webui_host_addr }}:{{ open_webui_host_port }}/health"