src / providers / BraveProvider.ts
src / providers / BraveProvider.ts
import { HTTPClient } from "../http/HTTPClient";
import { ProviderError } from "../models/errors";
import { SearchOptions } from "../types/search";
import { KeyManager } from "../utils/KeyManager";
import { BaseProvider } from "./BaseProvider";
import { InternalProviderResult } from "./types/InternalProviderResult";
export const BRAVE_SEARCH_URL = "https://api.search.brave.com/res/v1/web/search";
export interface BraveProviderOptions {
keys?: string[];
keyManager?: KeyManager;
httpClient?: HTTPClient;
cooldownHours?: number;
}
/**
* Brave Search provider implementation.
* Mapped from Python `providers/brave.py` BraveProvider.
*/
export class BraveProvider extends BaseProvider {
public static readonly PROVIDER_NAME = "brave";
public static readonly DISPLAY_NAME = "Brave";
private httpClient: HTTPClient;
constructor(options: BraveProviderOptions = {}) {
super({
providerName: BraveProvider.PROVIDER_NAME,
displayName: BraveProvider.DISPLAY_NAME,
capabilities: ["web"],
keys: options.keys,
keyManager: options.keyManager,
cooldownHours: options.cooldownHours,
});
this._rotationStatusCodes = [401, 403, 429];
this.httpClient = options.httpClient ?? new HTTPClient();
}
/**
* Execute web search using Brave Web Search API endpoint with key rotation.
*/
public async search(query: string, options: SearchOptions = {}): Promise<InternalProviderResult[]> {
if (!query || !query.trim()) {
return [];
}
const numResults = options.numResults ?? 10;
const { apiKey: _k, numResults: _n, provider: _p, ...extraKwargs } = options;
const doSearch = async (apiKey: string): Promise<InternalProviderResult[]> => {
const headers: Record<string, string> = {
"X-Subscription-Token": apiKey.trim(),
Accept: "application/json",
};
const params: Record<string, string | number | boolean> = {
q: query.trim(),
count: numResults,
...(extraKwargs as Record<string, string | number | boolean>),
};
let response;
try {
response = await this.httpClient.get(BRAVE_SEARCH_URL, {
params,
headers,
});
} catch (exc: unknown) {
const err = exc instanceof Error ? exc : new Error(String(exc));
throw new ProviderError(`Brave search HTTP request failed: ${err.message}`);
}
const data = this.parseJsonResponse<Record<string, unknown>>(response);
const webSection = data.web;
if (webSection === undefined || webSection === null) {
return [];
}
if (typeof webSection !== "object" || !("results" in (webSection as Record<string, unknown>))) {
throw new ProviderError(
"Invalid response payload from Brave API: missing 'web.results' array"
);
}
const rawResults = (webSection as Record<string, unknown>).results;
if (!Array.isArray(rawResults)) {
throw new ProviderError(
"Invalid response payload from Brave API: 'web.results' field must be a list"
);
}
this._lastRawResultsCount = rawResults.length;
const candidates = rawResults.map((item: unknown) =>
this.extractCandidate((item as Record<string, unknown>) || {})
);
return this.enforceResultLimit(candidates, numResults);
};
return this.executeWithKeyRotation(doSearch);
}
private extractCandidate(rawItem: Record<string, unknown>): InternalProviderResult {
let snippetCandidate = (rawItem.description as string) || "";
let snippetSource = "description";
if (!snippetCandidate && Array.isArray(rawItem.extra_snippets)) {
snippetCandidate = rawItem.extra_snippets.join(" ");
snippetSource = "extra_snippets";
}
return {
title: String(rawItem.title || ""),
url: String(rawItem.url || ""),
snippetCandidate,
publishedDate:
(rawItem.page_age as string) ||
(rawItem.published_date as string) ||
undefined,
source: this.providerName,
score: typeof rawItem.score === "number" ? rawItem.score : undefined,
raw: rawItem,
debug: { snippetSource },
};
}
}
import { HTTPClient } from "../http/HTTPClient";
import { ProviderError } from "../models/errors";
import { SearchOptions } from "../types/search";
import { KeyManager } from "../utils/KeyManager";
import { BaseProvider } from "./BaseProvider";
import { InternalProviderResult } from "./types/InternalProviderResult";
export const BRAVE_SEARCH_URL = "https://api.search.brave.com/res/v1/web/search";
export interface BraveProviderOptions {
keys?: string[];
keyManager?: KeyManager;
httpClient?: HTTPClient;
cooldownHours?: number;
}
/**
* Brave Search provider implementation.
* Mapped from Python `providers/brave.py` BraveProvider.
*/
export class BraveProvider extends BaseProvider {
public static readonly PROVIDER_NAME = "brave";
public static readonly DISPLAY_NAME = "Brave";
private httpClient: HTTPClient;
constructor(options: BraveProviderOptions = {}) {
super({
providerName: BraveProvider.PROVIDER_NAME,
displayName: BraveProvider.DISPLAY_NAME,
capabilities: ["web"],
keys: options.keys,
keyManager: options.keyManager,
cooldownHours: options.cooldownHours,
});
this._rotationStatusCodes = [401, 403, 429];
this.httpClient = options.httpClient ?? new HTTPClient();
}
/**
* Execute web search using Brave Web Search API endpoint with key rotation.
*/
public async search(query: string, options: SearchOptions = {}): Promise<InternalProviderResult[]> {
if (!query || !query.trim()) {
return [];
}
const numResults = options.numResults ?? 10;
const { apiKey: _k, numResults: _n, provider: _p, ...extraKwargs } = options;
const doSearch = async (apiKey: string): Promise<InternalProviderResult[]> => {
const headers: Record<string, string> = {
"X-Subscription-Token": apiKey.trim(),
Accept: "application/json",
};
const params: Record<string, string | number | boolean> = {
q: query.trim(),
count: numResults,
...(extraKwargs as Record<string, string | number | boolean>),
};
let response;
try {
response = await this.httpClient.get(BRAVE_SEARCH_URL, {
params,
headers,
});
} catch (exc: unknown) {
const err = exc instanceof Error ? exc : new Error(String(exc));
throw new ProviderError(`Brave search HTTP request failed: ${err.message}`);
}
const data = this.parseJsonResponse<Record<string, unknown>>(response);
const webSection = data.web;
if (webSection === undefined || webSection === null) {
return [];
}
if (typeof webSection !== "object" || !("results" in (webSection as Record<string, unknown>))) {
throw new ProviderError(
"Invalid response payload from Brave API: missing 'web.results' array"
);
}
const rawResults = (webSection as Record<string, unknown>).results;
if (!Array.isArray(rawResults)) {
throw new ProviderError(
"Invalid response payload from Brave API: 'web.results' field must be a list"
);
}
this._lastRawResultsCount = rawResults.length;
const candidates = rawResults.map((item: unknown) =>
this.extractCandidate((item as Record<string, unknown>) || {})
);
return this.enforceResultLimit(candidates, numResults);
};
return this.executeWithKeyRotation(doSearch);
}
private extractCandidate(rawItem: Record<string, unknown>): InternalProviderResult {
let snippetCandidate = (rawItem.description as string) || "";
let snippetSource = "description";
if (!snippetCandidate && Array.isArray(rawItem.extra_snippets)) {
snippetCandidate = rawItem.extra_snippets.join(" ");
snippetSource = "extra_snippets";
}
return {
title: String(rawItem.title || ""),
url: String(rawItem.url || ""),
snippetCandidate,
publishedDate:
(rawItem.page_age as string) ||
(rawItem.published_date as string) ||
undefined,
source: this.providerName,
score: typeof rawItem.score === "number" ? rawItem.score : undefined,
raw: rawItem,
debug: { snippetSource },
};
}
}