""" title: SpecStream Search author: SpecStream author_url: https://specstream.ai git_url: https://github.com/Specstreamai/specstream-templates description: The live web data engine. Search the live web, read pages, and look up any domain's authority, backlinks and anchor texts from the SpecStream Link Graph, with the source behind each result. required_open_webui_version: 0.6.31 version: 1.1.0 license: MIT """ import asyncio import json import urllib.error import urllib.parse import urllib.request from typing import Any, Optional from pydantic import BaseModel, Field BASE_URL = "https://api.specstream.ai" def _call(api_key: str, method: str, path: str, body: Optional[dict] = None, timeout: int = 60) -> dict: """One HTTPS call to the SpecStream API; returns the reply's `data` object.""" if not api_key: raise RuntimeError("Add your SpecStream API key in this tool's Valves (Workspace, Agents & API at specstream.ai).") request = urllib.request.Request( BASE_URL + path, data=None if body is None else json.dumps(body).encode("utf-8"), method=method, headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", "User-Agent": "specstream-open-webui-community/1.1.0", }, ) try: with urllib.request.urlopen(request, timeout=timeout) as response: payload = json.loads(response.read().decode("utf-8", "replace")) except urllib.error.HTTPError as exc: text = exc.read().decode("utf-8", "replace") if exc.fp else "" try: message = (json.loads(text).get("error") or {}).get("message") except ValueError: message = None raise RuntimeError(message or f"SpecStream answered HTTP {exc.code}.") from None except (urllib.error.URLError, OSError, ValueError): raise RuntimeError("Could not reach SpecStream. Try again in a moment.") from None return payload.get("data", payload) if isinstance(payload, dict) else {} async def _status(emitter: Any, text: str, done: bool = False) -> None: if emitter: await emitter({"type": "status", "data": {"description": text, "done": done}}) async def _cite(emitter: Any, url: str, title: str, text: str) -> None: if emitter and url: await emitter({"type": "citation", "data": {"document": [text or title or url], "metadata": [{"source": url}], "source": {"name": title or url, "url": url}}}) class Tools: class Valves(BaseModel): api_key: str = Field(default="", description="SpecStream API key (starts with ss_live_). New accounts get $2 of credit, no card: specstream.ai", json_schema_extra={"input": {"type": "password"}}) speed: str = Field(default="", description="Leave empty for the default search ($5 per 1,000), or 'fast' ($1 per 1,000).") max_sources: int = Field(default=8, description="Most sources handed to the model per search.") max_rows: int = Field(default=20, description="Most referring domains or anchors returned per link lookup (1 to 100).") def __init__(self): self.valves = self.Valves() self.citation = False async def search_web(self, query: str, __event_emitter__: Any = None) -> str: """ Search the live web for a question and return the answer, the best passages and the sources with their URLs. Use it for any fact that may have changed since the model was trained. :param query: The question in everyday words, in any language. """ try: await _status(__event_emitter__, "Searching the live web") params = {"q": query, "passages": "true"} if self.valves.speed: params["speed"] = self.valves.speed data = await asyncio.to_thread(_call, self.valves.api_key, "GET", "/v1/web-search?" + urllib.parse.urlencode(params)) sources = (data.get("sources") or [])[: max(1, self.valves.max_sources)] for s in sources: await _cite(__event_emitter__, s.get("url"), s.get("title"), s.get("snippet")) await _status(__event_emitter__, f"Read {len(sources)} sources", True) return json.dumps({ "answer": data.get("answer"), "passages": data.get("passages"), "sources": [{k: s.get(k) for k in ("title", "url", "snippet", "published", "read_at")} for s in sources], }, ensure_ascii=False) except RuntimeError as exc: await _status(__event_emitter__, "Search failed", True) return json.dumps({"error": str(exc)}) async def read_pages(self, urls: list[str], __event_emitter__: Any = None) -> str: """ Read the main text of 1 to 20 web pages, PDFs, Word or Excel files live. :param urls: The http or https addresses to read. """ try: await _status(__event_emitter__, f"Reading {len(urls)} pages") data = await asyncio.to_thread(_call, self.valves.api_key, "POST", "/v1/extract", {"urls": urls[:20], "format": "markdown"}) results = data.get("results") or [] for r in results: if r.get("status") == "ok": await _cite(__event_emitter__, r.get("url"), r.get("title"), (r.get("text") or "")[:500]) await _status(__event_emitter__, "Pages read", True) return json.dumps([{k: r.get(k) for k in ("url", "status", "title", "published", "read_from", "text")} for r in results], ensure_ascii=False) except RuntimeError as exc: await _status(__event_emitter__, "Read failed", True) return json.dumps({"error": str(exc)}) def _limit(self) -> int: return max(1, min(100, int(self.valves.max_rows or 20))) async def domain_authority(self, domains: str, __event_emitter__: Any = None) -> str: """ Get the link authority (0 to 100), global rank, referring domain count and outbound host count of up to 100 domains, from the SpecStream index. :param domains: One domain or several separated by commas, for example "stripe.com, adyen.com". """ names = [d.strip().lower() for d in domains.replace(" ", ",").split(",") if d.strip()][:100] if not names: return json.dumps({"error": "Give at least one domain."}) try: await _status(__event_emitter__, f"Reading authority for {len(names)} domain(s)") data = await asyncio.to_thread(_call, self.valves.api_key, "GET", "/v1/authority?" + urllib.parse.urlencode({"domains": ",".join(names)}), None, 30) rows = [{k: r.get(k) for k in ("domain", "known", "domain_authority", "global_rank", "referring_domains", "outbound_hosts")} for r in (data.get("results") or [])] rows.sort(key=lambda r: -(r.get("domain_authority") or 0)) await _status(__event_emitter__, "Authority read", True) return json.dumps({"results": rows}, ensure_ascii=False) except RuntimeError as exc: await _status(__event_emitter__, "Authority read failed", True) return json.dumps({"error": str(exc)}) async def referring_domains(self, target: str, direction: str = "inbound", __event_emitter__: Any = None) -> str: """ List the domains that link to a target domain (inbound), or the domains it links out to (outbound), strongest first, with the total count and the top anchor texts. :param target: The domain to look up, for example "linear.app". :param direction: "inbound" for sites linking to the target, "outbound" for sites the target links to. """ direction = "outbound" if str(direction).lower().startswith("out") else "inbound" q = {"target": target.strip().lower(), "mode": "domains", "direction": direction, "limit": self._limit()} try: await _status(__event_emitter__, f"Reading {direction} links for {q['target']}") data = await asyncio.to_thread(_call, self.valves.api_key, "GET", "/v1/backlinks?" + urllib.parse.urlencode(q), None, 30) if direction == "outbound": out = {"target": data.get("target"), "direction": "outbound", "total_hosts": data.get("total_hosts"), "hosts": data.get("hosts") or []} await _status(__event_emitter__, "Links read", True) return json.dumps(out, ensure_ascii=False) out = { "target": data.get("target"), "direction": data.get("direction"), "authority": data.get("authority"), "counts": data.get("counts"), "referring_domains": [{k: r.get(k) for k in ("domain", "domain_authority", "pages")} for r in (data.get("referring_domains") or [])], "top_anchors": (data.get("top_anchors") or [])[:10], } await _status(__event_emitter__, "Links read", True) return json.dumps(out, ensure_ascii=False) except RuntimeError as exc: await _status(__event_emitter__, "Links read failed", True) return json.dumps({"error": str(exc)}) async def anchor_texts(self, target: str, __event_emitter__: Any = None) -> str: """ Get the anchor texts other sites use to link to a domain, and its most linked pages, ordered by the number of referring domains. :param target: The domain to look up, for example "notion.com". """ q = {"target": target.strip().lower(), "limit": self._limit()} try: await _status(__event_emitter__, f"Reading anchor texts for {q['target']}") data = await asyncio.to_thread(_call, self.valves.api_key, "GET", "/v1/anchors?" + urllib.parse.urlencode(q), None, 30) await _status(__event_emitter__, "Anchors read", True) return json.dumps(data, ensure_ascii=False) except RuntimeError as exc: await _status(__event_emitter__, "Anchors read failed", True) return json.dumps({"error": str(exc)})