7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(search): add Brave Search as a web search provider (#1641) (#1650)
Fangorecf1e0ced8c30
diff --git a/client/src/lib/routing.ts b/client/src/lib/routing.tsindex b3dca104..e9b9161e 100644--- a/client/src/lib/routing.ts+++ b/client/src/lib/routing.ts@@ -483,6 +483,7 @@ export const platformColors: Record<string, string> = {parallel: '#0ea5e9',serpsearch: '#2563eb',keenable: '#7c3aed',+ brave: '#fb542b',beatapi: '#8b5cf6',apinex: '#06b6d4',onomeo: '#f97316',diff --git a/client/src/lib/search.ts b/client/src/lib/search.tsindex a3059171..2d381d84 100644--- a/client/src/lib/search.ts+++ b/client/src/lib/search.ts@@ -8,7 +8,7 @@ import type { SearchPlatform as SharedSearchPlatform } from '@freellmapi/shared/// Mirrors SEARCH_PLATFORMS in shared/types.ts. The client only imports types// from shared, so the list is repeated here; the two assertions below fail the// typecheck if either side gains a platform the other lacks.-export const SEARCH_PLATFORMS = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel', 'serpsearch', 'keenable'] as const+export const SEARCH_PLATFORMS = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel', 'serpsearch', 'keenable', 'brave'] as constexport type SearchPlatform = (typeof SEARCH_PLATFORMS)[number]const sharedCoversClient: SharedSearchPlatform = '' as SearchPlatformconst clientCoversShared: SearchPlatform = '' as SharedSearchPlatform@@ -30,6 +30,7 @@ export const SEARCH_PROVIDERS: { value: SearchPlatform; label: string; url: stri{ value: 'parallel', label: 'Parallel (no key needed)', url: 'https://platform.parallel.ai', keyless: true },{ value: 'serpsearch', label: 'SerpSearch (1,000 searches/month)', url: 'https://serpsearch.com/dashboard/api-keys' },{ value: 'keenable', label: 'Keenable (no key needed)', url: 'https://keenable.ai', keyless: true },+ { value: 'brave', label: 'Brave Search (free monthly credits)', url: 'https://api-dashboard.search.brave.com/app/keys' },]/** Short provider name for chips and badges ("Tavily", not the full label). */diff --git a/server/src/__tests__/services/catalog-sync.test.ts b/server/src/__tests__/services/catalog-sync.test.tsindex 064d5bfa..5897f7de 100644--- a/server/src/__tests__/services/catalog-sync.test.ts+++ b/server/src/__tests__/services/catalog-sync.test.ts@@ -833,10 +833,10 @@ describe('applyCatalog: searchEngines', () => {it('skips an engine whose platform has no search adapter in this binary', () => {const roster = searchRoster();- roster.push({ platform: 'brave', engineId: 'brave-search', displayName: 'Brave', priority: 5, enabled: true });+ roster.push({ platform: 'kagi', engineId: 'kagi-search', displayName: 'Kagi', priority: 5, enabled: true });const counts = applyCatalog(getDb(), searchCatalog(roster));expect(counts.skippedUnknownPlatform).toBeGreaterThanOrEqual(1);- expect(searchRows().map(r => r.model_id)).not.toContain('brave-search');+ expect(searchRows().map(r => r.model_id)).not.toContain('kagi-search');});it('rejects a malformed searchEngines entry before applying the cached catalog', () => {diff --git a/server/src/__tests__/services/search.test.ts b/server/src/__tests__/services/search.test.tsindex 2dc6ac15..ca2d2491 100644--- a/server/src/__tests__/services/search.test.ts+++ b/server/src/__tests__/services/search.test.ts@@ -1,7 +1,8 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { initDb, getDb } from '../../db/index.js';import { encrypt } from '../../lib/crypto.js';-import { clearAllCooldowns } from '../../services/ratelimit.js';+import { clearAllCooldowns, isOnCooldown } from '../../services/ratelimit.js';+import { BraveProvider } from '../../providers/brave.js';import {runSearch,SearchError,@@ -152,6 +153,72 @@ describe('search service', () => {expect(out).toMatchObject({ answer: 'yes', provider: 'linkup', results: [{ title: 'S', url: 'https://s', content: 'src' }] });});+ describe('Brave (#1641)', () => {+ const badKey = { error: { code: 'SUBSCRIPTION_TOKEN_INVALID', detail: 'The provided subscription token is invalid.', status: 422 }, type: 'ErrorResponse' };+ beforeEach(() => {+ getDb().prepare(`+ INSERT INTO media_models (platform, model_id, display_name, modality, priority, enabled, quota_label, meta_json)+ VALUES ('brave', 'brave-search', 'Brave Search', 'search', -1, 1, 'free monthly credits', '{}')+ `).run();+ });++ it('searches web and news with the subscription token and maps hits', async () => {+ addKey('brave');+ let fn = mockFetch(() => json({ web: { results: [{ title: 'A & B', url: 'https://a', description: 'alpha' }, { title: 'no url' }] } }));+ let out = await runSearch('cats & dogs', { maxResults: 3 });+ const url = new URL(calls(fn)[0][0]);+ expect(`${url.origin}${url.pathname}`).toBe('https://api.search.brave.com/res/v1/web/search');+ expect(url.searchParams.get('q')).toBe('cats & dogs');+ expect(url.searchParams.get('count')).toBe('3');+ expect(new Headers(calls(fn)[0][1].headers).get('x-subscription-token')).toBe('brave-test-key');+ expect(out).toMatchObject({ provider: 'brave', engine: 'brave-search', results: [{ title: 'A & B', url: 'https://a', content: 'alpha', score: 1 }] });++ fn = mockFetch(() => json({ results: [{ title: 'N', url: 'https://n', description: 'fresh' }] }));+ out = await runSearch('q', { topic: 'news' });+ expect(new URL(calls(fn)[0][0]).pathname).toBe('/res/v1/news/search');+ expect(out.results).toEqual([{ title: 'N', url: 'https://n', content: 'fresh', score: 1 }]);+ });++ it('benches a key Brave rejects (422 SUBSCRIPTION_TOKEN_INVALID), but not a key whose request was refused (422 VALIDATION)', async () => {+ const key = addKey('brave');+ mockFetch(() => json({ error: { code: 'VALIDATION', detail: 'Unable to validate request parameter(s)', status: 422 } }, 422));+ await expect(runSearch('q', { engine: 'brave-search' })).rejects.toBeInstanceOf(SearchError);+ expect(isOnCooldown('brave', 'brave-search', key)).toBe(false);++ mockFetch(() => json(badKey, 422));+ await expect(runSearch('q', { engine: 'brave-search' })).rejects.toBeInstanceOf(SearchError);+ expect(isOnCooldown('brave', 'brave-search', key)).toBe(true);+ });++ it('cools a rate-limited key down only for the one-second burst window', async () => {+ const key = addKey('brave');+ mockFetch(() => json({ error: { code: 'RATE_LIMITED', detail: 'Request rate limit exceeded for plan' } }, 429));+ await expect(runSearch('q', { engine: 'brave-search' })).rejects.toBeInstanceOf(SearchError);+ expect(isOnCooldown('brave', 'brave-search', key)).toBe(true);+ const later = Date.now() + 2_000;+ vi.spyOn(Date, 'now').mockReturnValue(later);+ expect(isOnCooldown('brave', 'brave-search', key)).toBe(false);+ });++ it('parks a key whose monthly credit is spent (429 QUOTA_LIMITED) for the long credit cooldown', async () => {+ const key = addKey('brave');+ mockFetch(() => json({ error: { code: 'QUOTA_LIMITED', detail: 'Request quota limit exceeded for plan' } }, 429));+ await expect(runSearch('q', { engine: 'brave-search' })).rejects.toBeInstanceOf(SearchError);+ const later = Date.now() + 60 * 60_000;+ vi.spyOn(Date, 'now').mockReturnValue(later);+ expect(isOnCooldown('brave', 'brave-search', key)).toBe(true);+ });++ it('validates a key with a free no-query request: bad token is invalid, VALIDATION means the key is fine', async () => {+ const brave = new BraveProvider();+ mockFetch(() => json(badKey, 422));+ expect(await brave.validateKey('bad')).toMatchObject({ valid: false });+ mockFetch(() => json({ error: { code: 'VALIDATION', detail: 'Unable to validate request parameter(s)', status: 422 } }, 422));+ expect(await brave.validateKey('good')).toBe(true);+ expect(brave.supportsKeyPolling).toBe(false);+ });+ });+describe('Parallel (keyless)', () => {function seedParallel(): void {getDb().prepare(`diff --git a/server/src/lib/key-parser.ts b/server/src/lib/key-parser.tsindex 7c4c1aa9..d853f96f 100644--- a/server/src/lib/key-parser.ts+++ b/server/src/lib/key-parser.ts@@ -53,6 +53,8 @@ export const PREFIX_MAP: Record<string, string> = {BEAT_API_: 'beatapi',SERPSEARCH_: 'serpsearch',SERP_SEARCH_: 'serpsearch',+ BRAVE_SEARCH_: 'brave',+ BRAVE_: 'brave',TYPHOON_: 'typhoon',PLUGSKY_: 'plugsky',INFERBASE_: 'inferbase',@@ -169,6 +171,7 @@ export const AUTH_JSON_PROVIDER_MAP: Record<string, string> = {onomeo: 'onomeo',iteracompute: 'iteracompute',serpsearch: 'serpsearch',+ brave: 'brave',typhoon: 'typhoon',plugsky: 'plugsky',inferbase: 'inferbase',diff --git a/server/src/lib/search-platforms.ts b/server/src/lib/search-platforms.tsindex dfe3c5ca..e899bbb1 100644--- a/server/src/lib/search-platforms.ts+++ b/server/src/lib/search-platforms.ts@@ -3,7 +3,7 @@ import type { SearchPlatform } from '@freellmapi/shared/types.js';// Runtime copy of shared/types.ts SEARCH_PLATFORMS. The server only ever// imports types from @freellmapi/shared (it is not compiled into dist), so the// list lives here too; a test pins the two together.-export const SEARCH_PLATFORMS: readonly SearchPlatform[] = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel', 'serpsearch', 'keenable'];+export const SEARCH_PLATFORMS: readonly SearchPlatform[] = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel', 'serpsearch', 'keenable', 'brave'];const SEARCH_PLATFORM_SET = new Set<string>(SEARCH_PLATFORMS);diff --git a/server/src/providers/brave.ts b/server/src/providers/brave.tsnew file mode 100644index 00000000..d21947a5--- /dev/null+++ b/server/src/providers/brave.ts@@ -0,0 +1,41 @@+import type { KeyValidationResult } from './base.js';+import { SearchOnlyProvider } from './search-only.js';+import { proxyFetch } from '../lib/proxy.js';++export const BRAVE_BASE_URL = 'https://api.search.brave.com/res/v1';++/** Brave answers a bad key with 422 (not 401) and this error code; a 422 with+ * any other code (VALIDATION) is a bad parameter and the key is fine. */+export const BRAVE_BAD_KEY_CODE = 'SUBSCRIPTION_TOKEN_INVALID';++// Brave Search API (brave.com/search/api). The key rides in X-Subscription-Token.+// Brave bills only successful requests, so the key check is a web search with+// no `q`: free, and the 422 it earns says which half failed. It is still an+// empty search, so (like Exa, #1599) the health pass sends it once per key.+export class BraveProvider extends SearchOnlyProvider {+ readonly platform = 'brave' as const;+ readonly name = 'Brave Search';++ override get supportsKeyPolling(): boolean {+ return false;+ }++ async validateKey(apiKey: string): Promise<KeyValidationResult> {+ let res: Response;+ try {+ res = await proxyFetch(`${BRAVE_BASE_URL}/web/search`, {+ method: 'GET',+ headers: { 'X-Subscription-Token': apiKey, Accept: 'application/json' },+ signal: AbortSignal.timeout(10_000),+ }, this.platform, 'search', 10_000);+ } catch (err) {+ return { valid: false, error: `${this.name} key validation inconclusive: ${err instanceof Error ? err.message : String(err)}` };+ }+ const body = await res.text().catch(() => '');+ if (res.status === 401 || res.status === 403 || body.includes(BRAVE_BAD_KEY_CODE)) {+ return { valid: false, error: `${this.name} key validation failed (HTTP ${res.status}): invalid API key` };+ }+ if (res.ok || (res.status >= 400 && res.status < 500)) return true;+ return { valid: false, error: `${this.name} key validation inconclusive (HTTP ${res.status})` };+ }+}diff --git a/server/src/providers/index.ts b/server/src/providers/index.tsindex 409a30e7..dcb6c7c3 100644--- a/server/src/providers/index.ts+++ b/server/src/providers/index.ts@@ -43,6 +43,7 @@ import { ApinexProvider } from './apinex.js';import { OnomeoProvider } from './onomeo.js';import { IteraComputeProvider } from './iteracompute.js';import { SerpSearchProvider } from './serpsearch.js';+import { BraveProvider } from './brave.js';const providers = new Map<Platform, BaseProvider>();@@ -93,6 +94,7 @@ register(new OnomeoProvider());// monthly token allowance; no free credential probe (see adapter docs).register(new IteraComputeProvider());register(new SerpSearchProvider());+register(new BraveProvider());// Free-plan grants are shared wallets, not free credits per model. Eligibility// and tested model rows belong in Oracle, never in bundled DB migrations.diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex a6a4a270..73fa4c01 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -67,6 +67,7 @@ const PLATFORMS = ['onomeo','iteracompute','serpsearch',+ 'brave','freeai','google', 'groq', 'cerebras', 'sail', 'electronhub', 'experiential', 'router9', 'septor', 'clod', 'speechify', 'blaze', 'lucidity', 'airforce', 'dreamprompting', 'waterfall', 'logfare', 'bai', 'radeon', 'nvidia', 'mistral','openrouter', 'cohere', 'tavily', 'exa', 'firecrawl', 'linkup', 'parallel', 'keenable', 'cloudflare', 'zhipu', 'ollama',diff --git a/server/src/services/search.ts b/server/src/services/search.tsindex 1591c7d7..21de6e62 100644--- a/server/src/services/search.ts+++ b/server/src/services/search.ts@@ -6,6 +6,7 @@ import { proxyFetch } from '../lib/proxy.js';import { isSearchPlatform } from '../lib/search-platforms.js';import { TAVILY_BASE_URL } from '../providers/tavily.js';import { SERPSEARCH_BASE_URL } from '../providers/serpsearch.js';+import { BRAVE_BASE_URL, BRAVE_BAD_KEY_CODE } from '../providers/brave.js';import { EXA_BASE_URL } from '../providers/exa.js';import { FIRECRAWL_BASE_URL } from '../providers/firecrawl.js';import { LINKUP_BASE_URL } from '../providers/linkup.js';@@ -316,6 +317,36 @@ const ADAPTERS: Record<string, Adapter> = {}));return { results: keepHits(hits).slice(0, n) };},+ // Brave: a bad key is a 422 carrying BRAVE_BAD_KEY_CODE (mapped to 401 so+ // coolDown benches it), a QUOTA_LIMITED 429 is spent credit (mapped to 402),+ // and any other 429 is its 1-second burst window.+ brave: async (cred, query, opts, n) => {+ const news = opts.topic === 'news';+ const url = new URL(`${BRAVE_BASE_URL}/${news ? 'news' : 'web'}/search`);+ url.searchParams.set('q', query);+ url.searchParams.set('count', String(n));+ let parsed: { web?: { results?: unknown }; results?: unknown } | null;+ try {+ parsed = await upstream(url.toString(), 'brave', {+ method: 'GET', redirect: 'error', headers: { 'X-Subscription-Token': cred.key, Accept: 'application/json' },+ }, opts.signal) as typeof parsed;+ } catch (e) {+ if (!(e instanceof SearchError)) throw e;+ if (e.status === 422 && e.message.includes(BRAVE_BAD_KEY_CODE)) throw new SearchError(e.message, 401);+ // A 429 for a spent monthly allowance (QUOTA_LIMITED) is the credits-+ // spent case, not a burst: park the key like a 402 instead of retrying+ // it every second until the month resets.+ if (e.status === 429 && /quota/i.test(e.message)) throw new SearchError(e.message, 402);+ // Brave sends no Retry-After; its burst window is one second.+ if (e.status === 429) throw new SearchError(e.message, 429, undefined, e.retryAfterMs ?? 1_000);+ throw e;+ }+ const rows = news ? parsed?.results : parsed?.web?.results;+ const hits = (Array.isArray(rows) ? rows : []).filter((r): r is Record<string, unknown> => !!r && typeof r === 'object').map(r => ({+ title: str(r.title), url: str(r.url), content: str(r.description),+ }));+ return { results: keepHits(hits).slice(0, n) };+ },tavily: (cred, query, opts, n) => tavilyShaped(`${TAVILY_BASE_URL}/search`, 'tavily', cred, query, opts, n),custom: (cred, query, opts, n) => {diff --git a/shared/types.ts b/shared/types.tsindex fa2b14f9..19bb7587 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -146,6 +146,7 @@ export type Platform =| 'parallel'| 'serpsearch'| 'keenable'+ | 'brave'| 'cloudflare'| 'zhipu'| 'ollama'@@ -276,7 +277,7 @@ export type Platform =* web_search tools), never chat. Search engine rows arrive through the* catalog's `searchEngines` registry. The server keeps its own runtime copy in* server/src/lib/search-platforms.ts (shared is type-only on the server). */-export const SEARCH_PLATFORMS = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel', 'serpsearch', 'keenable'] as const;+export const SEARCH_PLATFORMS = ['tavily', 'exa', 'firecrawl', 'linkup', 'parallel', 'serpsearch', 'keenable', 'brave'] as const;export type SearchPlatform = (typeof SEARCH_PLATFORMS)[number];export function isSearchPlatform(platform: string): platform is SearchPlatform {