Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

AI Research Agent

The AI research agent is a tool-using LLM that synthesizes search results into a comprehensive answer. It is triggered when a user searches the same query twice (the “double-search” trigger), indicating they want deeper analysis than raw search results can provide.

How it works

  1. User searches “quantum error correction”
  2. 4got returns normal search results
  3. User searches “quantum error correction” again (or clicks the “Research” button)
  4. 4got starts the AI research agent as a Server-Sent Events (SSE) stream
  5. The agent fetches top search result URLs, reads them, and synthesizes an answer
  6. Intermediate findings stream to the user in real time via the oracle box

Configuration

Edit data/ai-research.kdl:

enabled true
mode "lua"
provider "cerebras"
model "llama3.1-8b"
api-key "csk-..."
base-url "https://api.cerebras.ai/v1"
max-runtime-seconds 360
lua-timeout-seconds 180
max-tool-iterations 20
require "deluxe"

Fields

FieldDescription
enabledMaster switch (true/false)
modeExecution mode: "lua" (sandboxed) or "off". A "bash" mode was once documented here but never implemented — only "off" is special-cased.
providerLLM provider: “cerebras”, “openrouter”, “ollama”, “openai”, or any OpenAI-compatible endpoint
modelModel name (provider-specific)
api-keyAPI key for the provider
base-urlOverride the API endpoint URL. Defaults are inferred from provider name.
max-runtime-secondsKill the agent after this many seconds; 360 as shipped (Alex, 2026-05-14: “raise it universally to 6 minutes and 3 minutes for a lua job”)
lua-timeout-secondsStop one Lua run after this many seconds; 180 as shipped
max-tool-iterationsThe most tool rounds one job may take. Required while enabled: the server won’t start, and --check-config fails, without it.
requireGroup permission required to use the agent (e.g. “deluxe”). Empty = everyone.
instructions-requireThe group whose own instructions (Settings, “Custom AI instructions”) reach the agent; they win on conflict. Default: deluxe, whatever require says, so opening the AI to everyone does not open instructions that win over the server’s to everyone. "all" = everyone.
overview-requireWho gets the AI overview (below): "all" (the default, visitors included), "off" (nobody), or a group, such as "deluxe". It needs only provider, model and api-key, not enabled.
vision-requireWhose attached images the vision model (the one image descriptions use) reads, for their question: a group (the default, "deluxe"), "all", "owner" or "off". Everyone else’s attached image reaches the model as the text read off it.

AI overview

On page 1 of All, a few cited sentences above the results, from one model call over the search and the first eight results’ titles, sites and snippets (no page is read; for a search about something to look at, also the first four pictures’ titles, sites and kept descriptions, which it may cite as [P1]), streamed into a slot drawn with the page at the height it keeps. It is on by default for everyone overview-require names, wherever a provider and key are set. A person turns it off with “AI answer: Off” in the search bar’s + menu, “AI on search: Off” in Settings, No Jev, or “Use no outside services”. None is written when an instant answer already answers the search, for a site’s name or address, for a secret, on other tabs, or for a test search that does not name overview in X-4got-Want.

The call is made when the page opens the overview’s stream, not when the page is drawn, so a page read by a script, without JavaScript or for a link’s preview costs nothing. Its limits, checked when the page is drawn: 60 a minute per address, and 3,000 calls a day on the server’s key (/admin, Server-key stops; the row is overview). An overview is kept six hours for the same search and results (a failed call is not), a reload while one is being written shares that call, and a search known to have nothing gets no slot. “Dig deeper” on the card, for whoever may run the agent (require), starts the research agent in the overview’s place. With DeepSeek V4.1 Flash on DeepInfra one costs about $0.00017 (about 980 tokens in, 75 out, measured 2026-10-13). The stream is GET /api/v1/overview?k=<the slot's key>: sources, then token events, then done (or none). done’s also names the sources the answer drew on in general and cites at no point in its words, at most three: the model writes them on an “Also drawn on:” line after its answer, which is never shown.

Providers

Cerebras (recommended for free tier):

provider "cerebras"
model "llama3.1-8b"
api-key "csk-..."
base-url "https://api.cerebras.ai/v1"

Cerebras offers free API access for Llama 3.1 8B with extremely fast inference (~1000 tok/s). Good enough for research synthesis.

OpenRouter (access to many models):

provider "openrouter"
model "anthropic/claude-sonnet-4-20250514"
api-key "sk-or-..."

Ollama (local, no API key needed):

provider "ollama"
model "llama3.1:8b"
base-url "http://localhost:11434/v1"

Any OpenAI-compatible API:

provider "custom"
model "your-model"
api-key "your-key"
base-url "https://your-api.example.com/v1"

Metaprompt customization

The agent’s system prompt is loaded from data/metaprompt.md. This file controls the agent’s personality, tool usage patterns, and output format.

Key sections in the default metaprompt:

  • Context: explains to the LLM where it is and what 4got does
  • Tools: describes each tool and when to use it
  • Behavior rules: answer straight from “What the pages say” when it covers the question, eta() right before every fetch() or lua() in the same response, send() only beside the call it announces
  • Final answer format: the answer in the first sentence, as short as the question allows (under 120 words for most, never more than 200), light Markdown, no recap and no list of sources
  • Context management: how to use pin() and forget() to manage the limited context window

Before it, the server writes the agent’s environment: the CPU, memory, timeouts, model and the end of its training data, the Lua benchmarks run at boot, past jobs’ durations, and the model’s speed on this server, measured over its last 100 streamed calls (the average wait for its first word, then its tokens a second), with a worked step for its estimates of how long a job will take. After the metaprompt comes the invocation context: today’s date, and how the run began, triggered manually or not (Alex, 2026-05-22: “that’s even more useful context”): Dig deeper pressed, the same search made again, Ambient research’s questions answered, or !! before the search; or not: the person’s settings research every search, or Ambient research’s classifier (Jev) judged the search wanted it. A program calling the API is said to be one. Nothing of the person’s is in it.

You can customize the metaprompt to change the agent’s behavior. For example, to make it more concise:

Add to metaprompt.md:

## Output length
Keep your final answer under 200 words. Be direct.

Or to make it focus on academic sources:

## Source priority
Prefer academic sources (arxiv.org, scholar.google.com, .edu domains) over news articles.
Always check if there's a relevant arXiv paper.

Tool reference

send(text)

Shows a short line among the steps, beside the call it announces. The answer itself is the final message, never a send(). send("clear") folds the steps so far away: the box’s foot then offers “view thinking process”, which opens and closes them (debug mode keeps every step in view).

send("Found that Rust 1.84 adds async trait support. Checking release notes...")

eta(seconds, job_name)

Updates the ETA countdown timer shown to the user. Call before any slow operation (fetching URLs, running code). The box’s corner counts it down as “ai eta 3:31”; a download (the opening read of the results, or fetch’s pages) gives its own estimate beside it from the pages done so far, “download eta 4:30”, with “(woops!)” when it will end after the AI expected.

eta(5, "fetching rust-lang.org blog")

fetch(url)

Fetches a URL and returns the page’s text (its article, when it has one), at most 100 KB a page, with a 10-second timeout; depth=2 also follows same-domain links, as many as the room left in the context holds. A result longer than 12 KB comes in parts, each ending with how many tokens are left: count_only says how long a result is (about N tokens, its KB, lines and parts) without reading it in, and part reads one. psychoscrape and youtube_transcript take the same two arguments, and asking again for a result’s size or another part downloads nothing. show_lines (up to 60, on these and on lua) is how many lines of the result’s block the person sees before it scrolls.

fetch("https://blog.rust-lang.org/")
fetch("https://example.com/long-article", count_only=true)
fetch("https://example.com/long-article", part=2)

lua(code)

Executes Lua code in a sandboxed environment. What it prints shows on the page as it prints it (in batches at most four a second), and the whole output comes back to the model when the job ends; the metaprompt asks a job that may run over about 3 seconds to print its progress as it goes. Available standard libraries:

  • string: string.find, string.sub, string.gsub, string.format, etc.
  • table: table.insert, table.remove, table.sort, table.concat
  • math: math.floor, math.ceil, math.random, math.pi, etc.
  • json_decode(s): Parse a JSON string into a Lua table
  • json_encode(t): Serialize a Lua table to JSON
  • http_get(url): Fetch a URL and return the body as a string (uses the Go HTTP client with timeouts)

Example:

local data = http_get("https://api.example.com/data.json")
local parsed = json_decode(data)
for _, item in ipairs(parsed.results) do
    print(item.title .. ": " .. item.score)
end

pin(text)

Pins a short note to the agent’s context that will never be evicted during context window management. Use to preserve key findings across a long research session. Keep pins to 1-2 sentences.

pin("Key finding: the paper by Smith et al. (2026) shows 99.9% error correction rate using surface codes.")

forget(tool_call_id)

Removes a previous tool result from the agent’s context to free up space. Use after extracting what you need from a large fetch result.

forget("call_abc123")

friction(description)

Silently logs an improvement suggestion. These are recorded for the server operator to review. The user never sees them.

friction("No academic search engine configured - adding arXiv would improve research quality")

Double-search trigger UX

The research agent activates when a user searches the same query twice. The UI flow:

  1. First search: normal results displayed
  2. Second search (same query): a research box appears above results with a live SSE stream
  3. The agent’s steps (its send() lines, its code, its tools’ results) appear in the box’s lower part
  4. The eta() timer shows beside the box’s name
  5. The answer appears above the steps as the model writes it (“Stream AI responses” in Settings, on unless turned off), its Markdown drawn as it comes, each [oN] citation numbered by its entry’s first page (the server numbers the pages a run reads, so two entries of one page share a number) and drawn as a source chip, or as that number under “AI citations: Numbers”, with a card of its pages on hover or tap; when complete, the foot offers the pages the answer cites (“5 sources”), copy and download context: the conversation the model was sent (the system prompt, with this server’s environment section named in one line rather than shown, the tools, every message and tool result) and its replies, labelled, with the pages behind each [oN] entry at the end. A kept answer (the same search researched within a day, begun the same way, with the same settings, region, time range and engine weights) is replayed with the download of the run that wrote it, the asker’s own instructions, tapped answers and how the run began as placeholders; a run that fails offers what was sent before it failed.

The SSE endpoint is GET /api/v1/research?q=<query>; the page adds from=, how the run began (dig, double, asked, page or ambient), and without it the agent is told a program asked through the API. It returns events:

  • text — a step line (send(), or the server’s own progress)
  • eta — ETA update from eta()
  • token — a piece of the model’s words as it writes them; aside says the words so far were said on the way to a tool call (the page moves them into the steps), unsay that they were tool calls written as text
  • context — the download: what the model was sent, as Markdown
  • done — final answer, stream ends
  • error — error message, stream ends

Lua sandbox capabilities

The Lua sandbox (mode "lua") provides a safe execution environment:

Allowed:

  • All standard string/table/math operations
  • json_decode() and json_encode() for data processing
  • http_get() for fetching URLs (through Go’s HTTP client with timeout and SSRF protection)
  • print() for output (captured as the tool result)
  • tostring(), tonumber(), type(), pairs(), ipairs(), unpack()

Blocked:

  • File system access (io, os)
  • require(), dofile(), loadfile()
  • debug library
  • Arbitrary package loading
  • Long-running loops (killed by max-runtime-seconds)

On the old “bash mode” warning: earlier revisions of these docs claimed mode "bash" gave the agent shell access on the host and urged running 4got in a container because of it. No bash mode was ever implemented — the agent runs Lua in a sandbox, and mode is only ever checked against "off". Containerising 4got remains sensible practice; it is simply not required by this setting.

Friction feedback system

The friction() tool lets the agent report issues it encounters during research. These are logged to the database and can be reviewed by the server operator.

Common friction reports:

  • Missing engine types (e.g. “no academic engine for arXiv queries”)
  • Poor result quality for specific query types
  • Timeout issues with upstream services
  • Suggestions for new oracle types

Friction logs are stored in the ai_research table and can be queried via the admin panel.