okami.mom/albedo

git clone https://git.nkp.pet/okami.mom/albedo

nekomimi.petweb-search: show each search's answer in the tui, folded with click to expand; strip gemini's inline links36a1020

main
1.6 KiB53 linesraw
1from __future__ import annotations
2
3from typing import cast
4
5from albedo_api import Host, PythonApi, Record
6import albedo_trace
7
8
9class WebSearch(Record):
10    """One answered search: `r.answer` and `r["answer"]` both work. It prints
11    as the answer followed by its numbered sources."""
12
13    answer: str
14    sources: list[Record]
15
16    def __str__(self) -> str:
17        lines = [self.answer, ""] if self.answer else []
18        for index, source in enumerate(self.sources, 1):
19            dated = f" ({source.published})" if source.published else ""
20            lines.append(f"[{index}] {source.title}{dated}\n    {source.url}")
21            if source.snippet:
22                lines.append(f"    {source.snippet}")
23        return "\n".join(lines)
24
25    __repr__ = __str__
26
27    def markdown(self) -> str:
28        """The answer and a list of its linked sources, for the transcript."""
29        lines = [self.answer, ""] if self.answer else []
30        lines += [f"- [{source.title}]({source.url})" for source in self.sources]
31        return "\n".join(lines)
32
33
34host: Host
35
36
37async def web_search(query: str, limit: int = 8) -> WebSearch:
38    """Search the web: a written answer and the sources behind it."""
39    found = cast(
40        dict, await host("web_search.search", {"query": query, "limit": limit})
41    )
42    result = WebSearch(
43        answer=found["answer"],
44        sources=[Record(source) for source in found["sources"]],
45    )
46    albedo_trace.note("web", query, result.markdown())
47    return result
48
49
50def setup(api: PythonApi) -> dict[str, object]:
51    global host
52    host = api.host
53    return {"web_search": web_search}