websearch

package
v2.8.41 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package websearch holds everything about web-search providers that is not I/O: the provider manifests (providers/*.yaml, compiled to providers/compiled.json), request building, reply parsing and result cleanup.

Both hubs use it. The self-hosted Go hub sends the requests itself; the Cloudflare Worker reaches BuildRequest and ParseReply through the WASM engine and only performs the HTTPS call (or the Workers AI binding call) with the secret attached. A new HTTP search provider is a YAML file, not code.

Index

Constants

View Source
const (
	ClassNews      = "news"
	ClassDocs      = "docs"
	ClassAcademic  = "academic"
	ClassReference = "reference"
	ClassGeneral   = "general"
)

Query classes. Routing and cache lifetimes follow the class; it is logged with every search.

View Source
const (
	// DetailCompact returns title, URL, a short snippet and the score only.
	DetailCompact = "compact"
	// DetailStandard (the default) adds the full snippet, providers, canonical title and language.
	DetailStandard = "standard"
	// DetailFull adds rrfScore and the per-source scoreBreakdown.
	DetailFull = "full"
)

Detail levels for search results.

View Source
const (
	// BreakerThreshold consecutive failures open a provider's circuit.
	BreakerThreshold = 5
	// BreakerOpenMs is how long an open circuit skips the provider before one half-open probe.
	BreakerOpenMs = 60_000
	// SlowCallMs marks a successful call this slow as a soft failure for the breaker.
	SlowCallMs = 8_000
	// MaxPacingWaitMs bounds how long a search waits in a provider's pacing queue before giving up on it.
	MaxPacingWaitMs = 30_000
)
View Source
const (
	// DefaultRateLimitCooldownMs applies to a 429 without a usable Retry-After.
	DefaultRateLimitCooldownMs = 15_000
	// MaxRateLimitCooldownMs bounds any provider-requested cooldown.
	MaxRateLimitCooldownMs = 300_000

	// MaxReplyBytes bounds a provider reply read by either hub.
	MaxReplyBytes = 4 << 20
)
View Source
const CompactSnippetChars = 300

CompactSnippetChars bounds snippets in compact results.

View Source
const DefaultCacheMaxAgeMs = int64(24 * 60 * 60 * 1000)

DefaultCacheMaxAgeMs bounds a cached result's age when the request names no max_age_ms.

View Source
const DefaultMaxResults = 5

DefaultMaxResults is the result count when a request names none. With the reranker on, three results already carry the answer for 99% of the search-bench questions (AR@3); five leaves headroom.

View Source
const MaxCacheTTLMs = int64(7 * 24 * 60 * 60 * 1000)

MaxCacheTTLMs bounds a per-request cacheTtl.

View Source
const MaxMaxResults = 20

MaxMaxResults bounds maxResults.

View Source
const MaxPerSite = 2

MaxPerSite is the soft cap on results from one registrable domain (with diversity on): further results from that site move below results from other sites instead of being dropped.

View Source
const RRFK = 60.0

RRFK is the reciprocal-rank-fusion constant.

View Source
const RerankHead = 25

RerankHead is how many fused candidates a reranker sees (matches rerank.MaxCandidates).

View Source
const SnippetMaxChars = 1_200

SnippetMaxChars is the per-result snippet ceiling. Engines return ~150-character descriptions; one more excerpt and a date give an answer extractor the context it lacked while staying far below full-page text.

Variables

View Source
var ErrUnknownProvider = errors.New("websearch: unknown provider")

ErrUnknownProvider is returned for a provider id with no manifest.

Functions

func BreakerLabel

func BreakerLabel(s BreakerState, nowMs int64) string

BreakerLabel names a circuit state for telemetry.

func CacheMaterial

func CacheMaterial(provider string, in Input) string

CacheMaterial is the per-provider cache identity: provider, normalized query and the inputs that change its answer. Hubs hash it (the Worker with SHA-256) and store each provider's list on its own.

func CanonicalizeURL

func CanonicalizeURL(raw string) (string, bool)

CanonicalizeURL is the dedupe key for a result URL: https only, no credentials or fragment, lowercase host without a trailing dot, tracking parameters (utm_*, gclid, …) removed, and no trailing slash on a non-root path. ok=false drops the hit.

func CapSnippet

func CapSnippet(text string) string

CapSnippet bounds a snippet at SnippetMaxChars runes, cutting at a word boundary when one is reasonably close.

func ClassTTLMs

func ClassTTLMs(class string) int64

ClassTTLMs is the cache lifetime for a class.

func Classify

func Classify(query, timeRange, topic string) string

Classify sorts a query into news, docs, academic, reference or general. A time range or news topic always means news.

func CleanText

func CleanText(raw string) string

CleanText turns a provider field into plain single-line text: inline tags (<b>, <em>) become spaces, entities are decoded, zero-width marks dropped and whitespace collapsed.

func ComposeSnippet

func ComposeSnippet(date string, parts []string) string

ComposeSnippet builds a snippet from a description plus extra excerpts, prefixed with the publication date when it is absolute (has a year). Relative ages ("2 days ago") are dropped: they go stale in caches.

func CostOf

func CostOf(id string) float64

CostOf is a provider's list price per call (0 when unknown).

func CountMatching

func CountMatching(lists []List, f Filters) int

CountMatching counts distinct result URLs across lists that pass the filters; the waterfall stops once it reaches Plan.MinSatisfiedHits.

func CountWikipediaArticles

func CountWikipediaArticles(lists []List) int

CountWikipediaArticles counts hits that are Wikipedia article URLs (the hub tries one direct title guess when none).

func DedupeKey

func DedupeKey(raw string) string

DedupeKey is the identity used to merge results from different sources: case-insensitive host without a trailing dot or a leading "www.", no default port, dot segments resolved, percent-encoding normalized, tracking parameters dropped and no trailing slash. It is never shown to callers; results keep the first source's URL.

func ErrorCode

func ErrorCode(raw string) string

ErrorCode maps a provider failure to a stable code. Raw error text (which can carry hostnames, upstream messages or account details) is never returned to callers.

func FetchURL

func FetchURL(raw, canon string) string

FetchURL is the URL to fetch for a hit whose canonical key dropped a trailing slash: docs sites serve "/page/" and 301 "/page" to it, so fetching the key costs a redirect plus a same-host pause. "" when the key is already exact.

func HasInlineSite

func HasInlineSite(query string) bool

HasInlineSite reports whether the query already carries a site: operator.

func HostMatches

func HostMatches(host string, domains []string) bool

HostMatches reports whether host equals a rule domain or is a subdomain of one.

func HumanizeURLTitle

func HumanizeURLTitle(raw string) string

HumanizeURLTitle makes a readable title from a URL path ("Docs › Getting Started — example.com") for hits with none.

func IDs

func IDs() []string

IDs lists the known provider ids, sorted.

func LoadError

func LoadError() error

LoadError reports a broken embedded manifest file (tests assert it is nil).

func MatchesSitePrefixes

func MatchesSitePrefixes(rawURL string, prefixes []string) bool

MatchesSitePrefixes reports whether a URL falls under one of the site: path prefixes (true when there are none).

func MergeSnippets

func MergeSnippets(base, extra string) string

MergeSnippets appends the excerpts of extra (joined with " … ") that base lacks, then caps the result. Excerpt-level dedupe matters when two engines quote the same sentence among different ones.

func NormalizeDetail

func NormalizeDetail(v string) string

NormalizeDetail maps a request's detail option to compact, standard (default) or full.

func NormalizeQuery

func NormalizeQuery(q string) string

NormalizeQuery is the cache identity of a query: compatibility forms folded (the NFKC cases that matter for search text: full-width ASCII, compatibility spaces, common ligatures; Go's standard library has no full NFKC), case folded, whitespace collapsed and trailing punctuation dropped.

func NormalizeTimeRange

func NormalizeTimeRange(tr string) string

NormalizeTimeRange maps "d"/"day", "w"/"week", "m"/"month", "y"/"year" to the long form; anything else is "".

func RetryAfterMs

func RetryAfterMs(header string, now time.Time) int

RetryAfterMs reads a Retry-After header (seconds or an HTTP date) as a cooldown bounded to [2 s, 5 min]; absent or unusable gives DefaultRateLimitCooldownMs.

func SoftFailure

func SoftFailure(r CallRecord) bool

SoftFailure reports a successful call that should still count against the provider: no hits, or very slow.

Types

type AuthSpec

type AuthSpec struct {
	Header string `json:"header"`
	Prefix string `json:"prefix,omitempty"`
}

AuthSpec says which header carries the secret, and with what prefix ("Bearer ").

type BreakerState

type BreakerState struct {
	Failures  int   `json:"failures"`
	OpenUntil int64 `json:"openUntil,omitempty"`
	// Probing is set while the single half-open probe is in flight.
	Probing bool `json:"probing,omitempty"`
}

BreakerState is one provider's circuit. Hubs keep it in memory (the Worker per isolate) and pass it to the plan.

func BreakerAllow

func BreakerAllow(s BreakerState, nowMs int64) (bool, BreakerState)

BreakerAllow says whether a call may go out now and returns the state to store before it does. An open circuit refuses until OpenUntil; then exactly one probe goes out (others are refused until it reports back).

func BreakerRecord

func BreakerRecord(s BreakerState, failed bool, nowMs int64) BreakerState

BreakerRecord updates a circuit with a call's outcome: success closes it; a failure (hard, empty or slow) counts toward the threshold and reopens it after a failed probe.

type CallRecord

type CallRecord struct {
	Provider string `json:"provider"`
	// Code is "" on success, else a stable code (see ErrorCode); skipped providers carry their reason.
	Code    string  `json:"code,omitempty"`
	Ms      int64   `json:"ms"`
	Hits    int     `json:"hits"`
	CostUSD float64 `json:"costUsd"`
	// Breaker is the circuit state after the call: closed, open or half_open.
	Breaker string `json:"breaker,omitempty"`
	Skipped bool   `json:"skipped,omitempty"`
	// Cached is set when the list came from the search cache (no call, no cost).
	Cached bool `json:"cached,omitempty"`
}

CallRecord is the outcome of one provider call (or a decision not to call it).

type Capabilities

type Capabilities struct {
	// DomainFilter is "native" (an include/exclude parameter), "site" (a site: operator) or "none".
	DomainFilter string `json:"domainFilter"`
	TimeRange    bool   `json:"timeRange"`
	// Freshness is "high", "normal" or "low".
	Freshness string `json:"freshness"`
}

Capabilities drive routing: whether a provider can honor domain and time filters, and how fresh its index is.

type CollectionHit

type CollectionHit struct {
	URL     string `json:"url"`
	Title   string `json:"title"`
	Heading string `json:"heading,omitempty"`
	Snippet string `json:"snippet"`
	Text    string `json:"text,omitempty"`
}

CollectionHit is a stored-collection (BM25 / FTS) hit before shaping.

type Contribution

type Contribution struct {
	Provider string  `json:"provider"`
	Rank     int     `json:"rank"`
	Weight   float64 `json:"weight"`
	Score    float64 `json:"score"`
}

Contribution is one source's share of a fused score: weight / (k + rank), times any locale penalty.

type CostSpec

type CostSpec struct {
	USDPerRequest float64 `json:"usdPerRequest"`
	Basis         string  `json:"basis"`
}

CostSpec is the provider's list price per request, used for telemetry (an estimate, not a bill).

type CountSpec

type CountSpec struct {
	Min int `json:"min"`
	Max int `json:"max"`
}

CountSpec clamps the {count} placeholder.

type EdgeMapSpec

type EdgeMapSpec struct {
	Domains      []string `json:"domains"`
	SiteDomains  []string `json:"siteDomains"`
	SiteURLs     []string `json:"siteUrls"`
	SitePrefixes []string `json:"sitePrefixes"`
	FilterTerms  string   `json:"filterTerms"`
}

EdgeMapSpec is what a query's site: operators and include_domains say about crawling the target site directly.

func ExtractEdgeMap

func ExtractEdgeMap(query string, includeDomains []string) EdgeMapSpec

ExtractEdgeMap reads site: operators (with optional paths) and include_domains: with one or two target domains the hub may crawl the site's /llms.txt and sitemap directly. FilterTerms is the query without its site: operators.

type Entry

type Entry struct {
	URL            string   `json:"url"`
	FetchURL       string   `json:"fetchUrl,omitempty"`
	Title          string   `json:"title"`
	Content        string   `json:"content"`
	RRFScore       float64  `json:"rrfScore"`
	Providers      []string `json:"providers"`
	IsFiller       bool     `json:"isFiller,omitempty"`
	CanonicalTitle string   `json:"canonicalTitle,omitempty"`
	Lang           string   `json:"lang,omitempty"`
	// Breakdown lists each source's contribution; the scores sum to RRFScore.
	Breakdown []Contribution `json:"scoreBreakdown,omitempty"`
}

Entry is one fused result.

func Fuse

func Fuse(in FuseInput) []Entry

Fuse merges source lists with reciprocal-rank fusion (each list's weight / (k + rank)), drops hits outside the filters (and non-article Wikipedia pages), merges snippets when engines agree, demotes foreign-locale mirrors of English pages for English queries, and returns the candidate pool best-first: non-filler hits when there are enough of them, at most max(MaxResults, RerankHead) long.

type Filters

type Filters struct {
	IncludeDomains []string `json:"includeDomains"`
	ExcludeDomains []string `json:"excludeDomains"`
	SitePrefixes   []string `json:"sitePrefixes"`
}

Filters scope results to the caller's domains and site: paths.

type FinalizeOptions

type FinalizeOptions struct {
	Diversity bool   `json:"diversity"`
	Detail    string `json:"detail,omitempty"`
}

FinalizeOptions shape the final results.

type FuseInput

type FuseInput struct {
	Lists             []List  `json:"lists"`
	Filters           Filters `json:"filters"`
	Query             string  `json:"query"`
	WikipediaResolver bool    `json:"wikipediaResolver"`
	MaxResults        int     `json:"maxResults"`
}

FuseInput is everything fusion needs.

type Hit

type Hit struct {
	URL      string `json:"url"`
	FetchURL string `json:"fetchUrl,omitempty"`
	Title    string `json:"title"`
	Snippet  string `json:"snippet"`
}

Hit is one normalized result: URL is the canonical dedupe key, FetchURL the provider's exact URL when it differs.

type Input

type Input struct {
	Query          string            `json:"query"`
	Count          int               `json:"count"`
	TimeRange      string            `json:"timeRange,omitempty"`
	IncludeDomains []string          `json:"includeDomains,omitempty"`
	ExcludeDomains []string          `json:"excludeDomains,omitempty"`
	Country        string            `json:"country,omitempty"`
	Language       string            `json:"language,omitempty"`
	Category       string            `json:"category,omitempty"`
	Vars           map[string]string `json:"vars,omitempty"`
	// UseBinding builds the Workers AI binding call (request.binding) instead of the REST request.
	UseBinding bool `json:"useBinding,omitempty"`
}

Input is one provider call: the query and the caller's filters, plus operator variables (a SearXNG base URL, a Cloudflare account id, …). Secrets never appear here; the caller attaches them to the request it sends.

type Item

type Item struct {
	URL      string  `json:"url"`
	FetchURL string  `json:"fetchUrl,omitempty"`
	Title    string  `json:"title"`
	Snippet  string  `json:"snippet"`
	IsFiller bool    `json:"isFiller,omitempty"`
	Weight   float64 `json:"rrfWeight,omitempty"`
}

Item is one hit in a source list: a provider's result, an edge-map entry or a stored-collection hit.

func ShapeCollectionHits

func ShapeCollectionHits(hits []CollectionHit, f Filters) []Item

ShapeCollectionHits canonicalizes, filters and dedupes stored-collection hits.

func ShapeEdgeMapEntries

func ShapeEdgeMapEntries(entries []MapEntry, spec EdgeMapSpec, hasExternal bool, domain string) []Item

ShapeEdgeMapEntries turns site-map entries into ranked hits. Entries matching few of a multi-word query's terms are weak filler (weight 0.2) so full-text hits from search engines and collections outrank them.

type List

type List struct {
	Provider string `json:"provider"`
	Items    []Item `json:"items"`
}

List is one source's ranked hits.

type ListSpec

type ListSpec struct {
	Path            pathList `json:"path"`
	Single          bool     `json:"single,omitempty"`
	URL             string   `json:"url"`
	Title           string   `json:"title,omitempty"`
	Snippet         string   `json:"snippet,omitempty"`
	ExtraSnippets   string   `json:"extraSnippets,omitempty"`
	Compose         bool     `json:"compose,omitempty"`
	Dates           []string `json:"dates,omitempty"`
	SnippetMaxChars int      `json:"snippetMaxChars,omitempty"`
	FetchURL        *bool    `json:"fetchUrl,omitempty"`
}

ListSpec is one list (or single object) of results in the reply.

type MapEntry

type MapEntry struct {
	URL         string `json:"url"`
	Title       string `json:"title"`
	Description string `json:"description"`
	Source      string `json:"source"`
}

MapEntry is one entry from the hub's site map (llms.txt, sitemap, homepage links).

type ParamSpec

type ParamSpec struct {
	Name     string `json:"name"`
	Value    any    `json:"value"`
	Optional bool   `json:"optional,omitempty"`
	Rest     bool   `json:"rest,omitempty"`
	Binding  bool   `json:"binding,omitempty"`
	// JSONOnly parameters are left out of the HTML-fallback request (for example SearXNG's format=json).
	JSONOnly bool `json:"jsonOnly,omitempty"`
}

ParamSpec is one query-string parameter (GET) or JSON body field (POST). Value is a literal, a placeholder string ("{query}", "{count}", "{var.x}", …) or, for POST, a nested map of those. A placeholder that resolves to nothing drops the parameter.

type Plan

type Plan struct {
	OK      bool   `json:"ok"`
	Status  int    `json:"status,omitempty"`
	Error   string `json:"error,omitempty"`
	Message string `json:"message,omitempty"`

	Query          string   `json:"query"`
	MaxResults     int      `json:"maxResults"`
	IncludeDomains []string `json:"includeDomains"`
	ExcludeDomains []string `json:"excludeDomains"`
	TimeRange      string   `json:"timeRange"`
	// Mode is "waterfall" (call providers one phase at a time while results are thin) or "rrf" (call them together).
	Mode string `json:"mode"`
	// Phases are provider ids in call order: each phase runs in parallel; in waterfall mode a phase runs only while
	// fewer than MinSatisfiedHits results match. Fallback runs last, under the same thin-results rule, in both modes.
	Phases   [][]string `json:"phases"`
	Fallback []string   `json:"fallback"`
	// SkipCloudflareUnlessCeramicFailed: Cloudflare Web Search defaults to the Ceramic engine, so it only runs when a
	// direct Ceramic call in the same search failed.
	SkipCloudflareUnlessCeramicFailed bool `json:"skipCloudflareUnlessCeramicFailed,omitempty"`
	MinSatisfiedHits                  int  `json:"minSatisfiedHits"`
	HasExternal                       bool `json:"hasExternal"`
	// Inputs are the per-provider call inputs (query rewritten for Wikipedia, provider-specific domain filters).
	Inputs map[string]Input `json:"inputs"`

	Wikipedia               WikipediaPlan `json:"wikipedia"`
	EffectiveIncludeDomains []string      `json:"effectiveIncludeDomains"`
	SerpQuery               string        `json:"serpQuery"`
	EdgeMap                 EdgeMapSpec   `json:"edgeMap"`
	CanEdgeMap              bool          `json:"canEdgeMap"`

	// Skipped are providers the plan left out (open circuit, budget); Breakers are the circuit states to store now
	// (a half-open probe marks its circuit before the call goes out).
	Skipped  []CallRecord            `json:"skipped,omitempty"`
	Breakers map[string]BreakerState `json:"breakers,omitempty"`
	// BudgetUSD (request budgetUsd) and TimeoutMs (request timeoutMs, 1-60 s) bound this search; 0 = none.
	BudgetUSD float64 `json:"budgetUsd,omitempty"`
	TimeoutMs int     `json:"timeoutMs,omitempty"`
	// Class is the query class (news, docs, academic, reference, general); it orders providers for news and sets the
	// cache lifetime. CacheTTLMs is how long fresh provider lists are kept (class default or the request's cacheTtl), and
	// CacheKeys hold each planned provider's cache identity (hubs hash and store each provider's list separately).
	Class      string            `json:"class"`
	CacheTTLMs int64             `json:"cacheTtlMs"`
	CacheKeys  map[string]string `json:"cacheKeys,omitempty"`
	// Diversity caps results per site (websearch.MaxPerSite); a request turns it off with `diversity: false`.
	Diversity bool `json:"diversity"`
	// Detail is compact, standard (default) or full (see FinalizeOptions).
	Detail string `json:"detail"`
	// CacheMaxAgeMs is the caller's cache bound (0 = bypass): noCache, or max_age_ms, or the default.
	CacheMaxAgeMs int64 `json:"cacheMaxAgeMs"`
	// Unhonored lists request options this hub could not honor.
	Unhonored []string `json:"unhonored,omitempty"`
}

Plan is everything the hub needs to run one search.

func MakePlan

func MakePlan(in PlanInput) Plan

MakePlan resolves a search request into providers, phases, inputs and filters.

type PlanInput

type PlanInput struct {
	Payload json.RawMessage `json:"payload"`
	// Configured lists the providers the hub has credentials or endpoints for (by manifest id).
	Configured map[string]bool `json:"configured"`
	// CloudflareEngine is CLOUDFLARE_WEBSEARCH_PROVIDER (ceramic, exa or linkup).
	CloudflareEngine string `json:"cloudflareEngine,omitempty"`
	// EnvDefaultMode is SEARCH_DEFAULT_MODE; "waterfall" forces the waterfall everywhere.
	EnvDefaultMode string `json:"envDefaultMode,omitempty"`
	// BraveDisabled is SEARCH_DISABLE_BRAVE.
	BraveDisabled bool `json:"braveDisabled,omitempty"`
	// DefaultMode is the surface's strategy when the payload names none: "rrf" for direct search surfaces (MCP
	// search, /v1/search), "" (waterfall) for internal fan-out that must not queue behind Brave's pacing.
	DefaultMode string `json:"defaultMode,omitempty"`
	// AllowLiveFetch is false for a crawl:read-only caller: no edge-map crawl or Wikipedia title guess.
	AllowLiveFetch bool `json:"allowLiveFetch"`
	// CollectionsRequested is how many stored collections the hub will search (after access checks).
	CollectionsRequested int `json:"collectionsRequested"`
	// HasCollectionSearch is true when the hub can search stored collections at all.
	HasCollectionSearch bool `json:"hasCollectionSearch"`
	// Breakers are the hub's circuit states by provider; NowMs is the hub's clock.
	Breakers map[string]BreakerState `json:"breakers,omitempty"`
	NowMs    int64                   `json:"nowMs,omitempty"`
	// MonthCapUSD are operator caps (SEARCH_BUDGET_<PROVIDER>_USD_MONTH) and MonthSpentUSD this month's spend.
	// SpendKnown false with a cap set skips the provider (fail closed).
	MonthCapUSD   map[string]float64 `json:"monthCapUsd,omitempty"`
	MonthSpentUSD map[string]float64 `json:"monthSpentUsd,omitempty"`
	SpendKnown    bool               `json:"spendKnown,omitempty"`
}

PlanInput is a search request plus what the hub has configured. Payload is the caller's JSON body.

type QueryRules

type QueryRules struct {
	SiteFromSingleIncludeDomain bool `json:"siteFromSingleIncludeDomain,omitempty"`
	MaxWords                    int  `json:"maxWords,omitempty"`
	MaxChars                    int  `json:"maxChars,omitempty"`
}

QueryRules adapt the query text to a provider's limits.

type Replica

type Replica struct {
	URL       string `json:"url"`
	Body      string `json:"body,omitempty"`
	RetryURL  string `json:"retryUrl,omitempty"`
	RetryBody string `json:"retryBody,omitempty"`
	HTMLURL   string `json:"htmlUrl,omitempty"`
}

Replica is one replica's request.

type Reply

type Reply struct {
	Hits []Hit `json:"hits"`
	// Error is "<provider>_http_<status>" or "<provider>_parse_error"; empty on success. Its JSON name is "failure"
	// because the Worker's WASM bridge treats an "error" key as a failed call.
	Error string `json:"failure,omitempty"`
	// RateLimited is set for HTTP 429, with the cooldown the provider asked for.
	RateLimited  bool `json:"rateLimited,omitempty"`
	RetryAfterMs int  `json:"retryAfterMs,omitempty"`
}

Reply is a parsed provider reply.

func ParseHTMLReply

func ParseHTMLReply(id string, in Input, status int, body []byte) Reply

ParseHTMLReply parses a provider's HTML results page (the request's HTMLURL) with its manifest's htmlFallback parser.

func ParseReply

func ParseReply(id string, in Input, status int, retryAfter string, body []byte) Reply

ParseReply turns a provider's HTTP status, Retry-After header and body into hits (or an error).

type Request

type Request struct {
	Provider string            `json:"provider"`
	Method   string            `json:"method"`
	URL      string            `json:"url,omitempty"`
	Headers  map[string]string `json:"headers,omitempty"`
	Body     string            `json:"body,omitempty"`
	// RetryURL / RetryBody repeat the request without its optional parameters, for a reply status in RetryOn.
	RetryURL  string `json:"retryUrl,omitempty"`
	RetryBody string `json:"retryBody,omitempty"`
	RetryOn   []int  `json:"retryOn,omitempty"`
	// SecretEnv names the environment variable holding the key; send it in SecretHeader as SecretPrefix+value.
	SecretEnv    string `json:"secretEnv,omitempty"`
	SecretHeader string `json:"secretHeader,omitempty"`
	SecretPrefix string `json:"secretPrefix,omitempty"`
	TimeoutMs    int    `json:"timeoutMs"`
	MinGapMs     int    `json:"minGapMs"`
	// Binding names the Workers AI method to call with BindingBody instead of sending an HTTP request.
	Binding     string         `json:"binding,omitempty"`
	BindingBody map[string]any `json:"bindingBody,omitempty"`
	// Skip is true when the query is empty after the provider's query rules; the provider is not called.
	Skip bool `json:"skip,omitempty"`
	// HTMLURL is the request for the provider's HTML results page (JSON-only parameters left out), used when the JSON
	// reply is refused or unparseable; parse it with ParseHTMLReply.
	HTMLURL string `json:"htmlUrl,omitempty"`
	// Replicas are the same request against each configured replica, in order (the first equals URL / Body). Send to
	// the next on a transport error or a 5xx.
	Replicas []Replica `json:"replicas,omitempty"`
}

Request is a ready-to-send provider call without its secret.

func BuildRequest

func BuildRequest(id string, in Input) (*Request, error)

BuildRequest returns the request for one provider call.

type RequestSpec

type RequestSpec struct {
	Method                 string             `json:"method"`
	URL                    string             `json:"url"`
	TimeoutMs              int                `json:"timeoutMs"`
	MinGapMs               int                `json:"minGapMs"`
	Query                  QueryRules         `json:"query"`
	Params                 []ParamSpec        `json:"params"`
	RetryWithoutOptionalOn []int              `json:"retryWithoutOptionalOn,omitempty"`
	Count                  *CountSpec         `json:"count,omitempty"`
	TimeRange              map[string]string  `json:"timeRange,omitempty"`
	Vars                   map[string]VarSpec `json:"vars,omitempty"`
	Binding                string             `json:"binding,omitempty"`
}

RequestSpec is the request template.

type ResponseSpec

type ResponseSpec struct {
	Lists               []ListSpec `json:"lists"`
	MaxItemsPerCount    int        `json:"maxItemsPerCount,omitempty"`
	RetryAfterBodyField string     `json:"retryAfterBodyField,omitempty"`
	// HTMLFallback names the HTML results parser used when JSON is unavailable ("searxng").
	HTMLFallback string `json:"htmlFallback,omitempty"`
}

ResponseSpec maps a reply onto hits.

type Result

type Result struct {
	Title          string   `json:"title"`
	URL            string   `json:"url"`
	Content        string   `json:"content"`
	Score          float64  `json:"score"`
	Provider       string   `json:"provider"`
	Providers      []string `json:"providers"`
	CanonicalTitle string   `json:"canonicalTitle,omitempty"`
	Lang           string   `json:"lang,omitempty"`
	// RRFScore is the fused score and ScoreBreakdown its per-source parts (they sum to it); Score is RRFScore
	// normalized (0.95 at the top) or, when reranked, the blended reranker score.
	RRFScore       float64        `json:"rrfScore,omitempty"`
	ScoreBreakdown []Contribution `json:"scoreBreakdown,omitempty"`
}

Result is one search result as returned to callers.

func Finalize

func Finalize(pool []Entry, maxResults int, order []int, blended []float64, opts FinalizeOptions) []Result

Finalize picks the top maxResults of the pool, in rerank order when one is given (indexes into the pool's first len(order) entries, with blended scores), and scores them: blended scores as-is, else RRF normalized so the top hit is 0.95. With diversity on, at most MaxPerSite results per registrable domain lead the list (the rest follow), so the top three span at least two sites whenever the pool has two.

type Spec

type Spec struct {
	ID           string       `json:"id"`
	Name         string       `json:"name"`
	Secret       string       `json:"secret,omitempty"`
	Auth         *AuthSpec    `json:"auth,omitempty"`
	Request      RequestSpec  `json:"request"`
	Response     ResponseSpec `json:"response"`
	Cost         CostSpec     `json:"cost"`
	Capabilities Capabilities `json:"capabilities"`
}

Spec is one provider manifest (see hub/scripts/compile-search-providers.mjs for the schema checks).

func Lookup

func Lookup(id string) (*Spec, bool)

Lookup returns the manifest for a provider id.

type Summary

type Summary struct {
	Mode          string       `json:"mode"`
	Class         string       `json:"class,omitempty"`
	Cache         string       `json:"cache"`
	Providers     []CallRecord `json:"providers"`
	RerankModel   string       `json:"rerankModel,omitempty"`
	RerankMs      int64        `json:"rerankMs,omitempty"`
	RerankApplied bool         `json:"rerankApplied,omitempty"`
	TotalMs       int64        `json:"totalMs"`
	CostUSD       float64      `json:"costUsd"`
	ResultCount   int          `json:"resultCount"`
	Trace         []TraceStep  `json:"trace"`
}

Summary is one search's telemetry: the row a hub stores (with its own query hash; never the raw query) and the compact trace returned in every response.

func Summarize

func Summarize(in SummaryInput) Summary

Summarize builds a search's telemetry. Calls whose Code is raw error text are normalized with ErrorCode; skipped calls cost nothing.

type SummaryInput

type SummaryInput struct {
	Mode          string       `json:"mode"`
	Class         string       `json:"class,omitempty"`
	Cache         string       `json:"cache"`
	Calls         []CallRecord `json:"calls"`
	RerankModel   string       `json:"rerankModel,omitempty"`
	RerankMs      int64        `json:"rerankMs,omitempty"`
	RerankApplied bool         `json:"rerankApplied,omitempty"`
	TotalMs       int64        `json:"totalMs"`
	ResultCount   int          `json:"resultCount"`
}

SummaryInput is what a hub knows when a search finishes.

type TraceStep

type TraceStep struct {
	Step    string  `json:"step"`
	Code    string  `json:"code,omitempty"`
	Ms      int64   `json:"ms,omitempty"`
	Hits    int     `json:"hits,omitempty"`
	CostUSD float64 `json:"costUsd,omitempty"`
	Cached  bool    `json:"cached,omitempty"`
}

TraceStep is one step of a search, as returned to callers.

type VarSpec

type VarSpec struct {
	Required        bool `json:"required,omitempty"`
	RequiredForRest bool `json:"requiredForRest,omitempty"`
	HTTPBase        bool `json:"httpBase,omitempty"`
	// List accepts several base URLs separated by ";": replicas tried in order.
	List    bool     `json:"list,omitempty"`
	Pattern string   `json:"pattern,omitempty"`
	Enum    []string `json:"enum,omitempty"`
	Default string   `json:"default,omitempty"`
}

VarSpec validates one operator-supplied variable (a base URL, an account id, an engine name).

type WikipediaPlan

type WikipediaPlan struct {
	Resolver bool   `json:"resolver"`
	Lang     string `json:"lang"`
	Host     string `json:"host"`
	// GuessURL is the one /wiki/<Title> page the hub may fetch when no search source returned an article.
	GuessURL string `json:"guessUrl,omitempty"`
}

WikipediaPlan is set when the search resolves Wikipedia articles only.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL