Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

feat: add SerpApi web search provider

nash_su6fc392dea929
diff --git a/src/components/layout/research-panel.tsx b/src/components/layout/research-panel.tsx
index d2b611fb..151bf8e9 100644
--- a/src/components/layout/research-panel.tsx
+++ b/src/components/layout/research-panel.tsx
@@ -34,7 +34,7 @@ export function ResearchPanel() {
const topic = inputValue.trim()
if (!topic || !project) return
if (searchApiConfig.provider === "none" || !searchApiConfig.apiKey) {
- window.alert("Web Search not configured. Go to Settings → Web Search to add a Tavily API key.")
+ window.alert("Web Search not configured. Go to Settings → Web Search to add a Tavily or SerpApi API key.")
return
}
queueResearch(normalizePath(project.path), topic, llmConfig, searchApiConfig)
diff --git a/src/components/review/review-view.tsx b/src/components/review/review-view.tsx
index 1d96b514..343f6ab4 100644
--- a/src/components/review/review-view.tsx
+++ b/src/components/review/review-view.tsx
@@ -39,7 +39,7 @@ export function ReviewView() {
if (action === "__deep_research__" && project) {
const searchConfig = useWikiStore.getState().searchApiConfig
if (searchConfig.provider === "none" || !searchConfig.apiKey) {
- window.alert("Web Search not configured. Go to Settings → Web Search to add a Tavily API key first.")
+ window.alert("Web Search not configured. Go to Settings → Web Search to add a Tavily or SerpApi API key first.")
return
}
const item = items.find((i) => i.id === id)
diff --git a/src/components/settings/sections/web-search-section.tsx b/src/components/settings/sections/web-search-section.tsx
index 3c15e219..94088139 100644
--- a/src/components/settings/sections/web-search-section.tsx
+++ b/src/components/settings/sections/web-search-section.tsx
@@ -1,22 +1,65 @@
+import { useState } from "react"
+import { ChevronDown, ChevronRight } from "lucide-react"
import { useTranslation } from "react-i18next"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
-import type { SettingsDraft, DraftSetter } from "../settings-types"
+import {
+ useWikiStore,
+ type SearchApiConfig,
+ type SearchProvider,
+ type SearchProviderOverride,
+} from "@/stores/wiki-store"
+import { SERPAPI_ENGINE_OPTIONS, resolveSearchConfig } from "@/lib/web-search"
-interface Props {
- draft: SettingsDraft
- setDraft: DraftSetter
-}
+const SEARCH_PROVIDERS = [
+ {
+ id: "tavily",
+ label: "Tavily",
+ hint: "General web search for Deep Research",
+ keyPlaceholder: "Enter your Tavily API key (tavily.com)",
+ },
+ {
+ id: "serpapi",
+ label: "SerpApi",
+ hint: "Google, Bing, DuckDuckGo, Scholar, News, Images, Videos, YouTube",
+ keyPlaceholder: "Enter your SerpApi API key (serpapi.com)",
+ },
+] as const
-export function WebSearchSection({ draft, setDraft }: Props) {
+export function WebSearchSection() {
const { t } = useTranslation()
- const options = [
- { value: "none" as const, label: "Disabled" },
- { value: "tavily" as const, label: "Tavily" },
- ]
+ const searchApiConfig = useWikiStore((s) => s.searchApiConfig)
+ const setSearchApiConfig = useWikiStore((s) => s.setSearchApiConfig)
+ const resolvedConfig = resolveSearchConfig(searchApiConfig)
+ const [expanded, setExpanded] = useState<Record<string, boolean>>({})
+ const [savedId, setSavedId] = useState<string | null>(null)
+
+ async function persist(next: SearchApiConfig) {
+ const { saveSearchApiConfig } = await import("@/lib/project-store")
+ setSearchApiConfig(next)
+ await saveSearchApiConfig(next)
+ }
+
+ function updateProvider(id: Exclude<SearchProvider, "none">, patch: SearchProviderOverride) {
+ const currentConfigs = resolvedConfig.providerConfigs ?? {}
+ const merged = { ...(currentConfigs[id] ?? {}), ...patch }
+ const nextConfigs = { ...currentConfigs, [id]: merged }
+ const next = resolveSearchConfig({
+ ...resolvedConfig,
+ providerConfigs: nextConfigs,
+ })
+ persist(next).catch(() => {})
+ setSavedId(id)
+ setTimeout(() => setSavedId((cur) => (cur === id ? null : cur)), 1500)
+ }
+
+ function toggleActive(id: Exclude<SearchProvider, "none">) {
+ const nextProvider = resolvedConfig.provider === id ? "none" : id
+ persist(resolveSearchConfig({ ...resolvedConfig, provider: nextProvider })).catch(() => {})
+ }
return (
- <div className="space-y-6">
+ <div className="space-y-4">
<div>
<h2 className="text-xl font-semibold">{t("settings.sections.webSearch.title")} (Deep Research)</h2>
<p className="mt-1 text-sm text-muted-foreground">
@@ -25,38 +68,138 @@ export function WebSearchSection({ draft, setDraft }: Props) {
</div>
<div className="space-y-2">
- <Label>{t("settings.sections.webSearch.provider", { defaultValue: "Search Provider" })}</Label>
- <div className="flex flex-wrap gap-2">
- {options.map((p) => {
- const active = draft.searchProvider === p.value
- return (
- <button
- key={p.value}
- type="button"
- onClick={() => setDraft("searchProvider", p.value)}
- className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
- active
- ? "border-primary bg-primary text-primary-foreground"
- : "border-border hover:bg-accent"
- }`}
- >
- {p.label}
- </button>
- )
- })}
- </div>
+ {SEARCH_PROVIDERS.map((provider) => {
+ const override = resolvedConfig.providerConfigs?.[provider.id]
+ const isActive = resolvedConfig.provider === provider.id
+ const hasConfig = !!override?.apiKey
+ const isExpanded = !!expanded[provider.id]
+ return (
+ <div
+ key={provider.id}
+ className={`rounded-lg border transition-colors ${
+ isActive ? "border-primary/60 bg-primary/5" : "border-border"
+ }`}
+ >
+ <div className="flex items-center gap-3 px-3 py-2.5">
+ <button
+ type="button"
+ onClick={() => setExpanded((prev) => ({ ...prev, [provider.id]: !prev[provider.id] }))}
+ className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent"
+ title={isExpanded ? "Collapse" : "Expand"}
+ >
+ {isExpanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
+ </button>
+
+ <button
+ type="button"
+ onClick={() => setExpanded((prev) => ({ ...prev, [provider.id]: !prev[provider.id] }))}
+ className="min-w-0 flex-1 text-left"
+ >
+ <div className="flex items-center gap-2">
+ <span className="truncate text-sm font-medium">{provider.label}</span>
+ {hasConfig && !isActive && (
+ <span className="shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
+ Configured
+ </span>
+ )}
+ {isActive && (
+ <span className="shrink-0 rounded-full bg-primary/20 px-1.5 py-0.5 text-[10px] font-medium text-primary">
+ Active
+ </span>
+ )}
+ {savedId === provider.id && (
+ <span className="shrink-0 text-[10px] text-emerald-600">Saved</span>
+ )}
+ </div>
+ <div className="mt-0.5 truncate text-xs text-muted-foreground">
+ {provider.hint}
+ </div>
+ </button>
+
+ <button
+ type="button"
+ onClick={() => toggleActive(provider.id)}
+ className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border transition-colors ${
+ isActive
+ ? "border-primary bg-primary"
+ : "border-muted-foreground/30 bg-muted-foreground/20 hover:bg-muted-foreground/30"
+ }`}
+ aria-label={isActive ? "Deactivate" : "Activate"}
+ >
+ <span
+ className={`inline-block h-3.5 w-3.5 rounded-full bg-white shadow-sm ring-1 ring-black/10 transition-transform ${
+ isActive ? "translate-x-4" : "translate-x-0.5"
+ }`}
+ />
+ </button>
+ </div>
+
+ {isExpanded && (
+ <div className="space-y-4 border-t bg-background/50 px-4 py-3">
+ <div className="space-y-2">
+ <Label>API Key</Label>
+ <Input
+ type="password"
+ value={override?.apiKey ?? ""}
+ onChange={(e) => updateProvider(provider.id, { apiKey: e.target.value })}
+ placeholder={provider.keyPlaceholder}
+ />
+ </div>
+
+ {provider.id === "serpapi" && (
+ <SerpApiEnginePicker
+ value={override?.serpApiEngine ?? resolvedConfig.serpApiEngine ?? "google"}
+ onChange={(serpApiEngine) => updateProvider("serpapi", { serpApiEngine })}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ )
+ })}
</div>
+ </div>
+ )
+}
+
+function SerpApiEnginePicker({
+ value,
+ onChange,
+}: {
+ value: string
+ onChange: (value: string) => void
+}) {
+ const isCustom = value.length > 0 && !SERPAPI_ENGINE_OPTIONS.some((e) => e.value === value)
- {draft.searchProvider !== "none" && (
- <div className="space-y-2">
- <Label>API Key</Label>
- <Input
- type="password"
- value={draft.searchApiKey}
- onChange={(e) => setDraft("searchApiKey", e.target.value)}
- placeholder="Enter your Tavily API key (tavily.com)"
- />
- </div>
+ return (
+ <div className="space-y-2">
+ <Label>Search engine / category</Label>
+ <div className="flex flex-wrap gap-1.5">
+ {SERPAPI_ENGINE_OPTIONS.map((engine) => (
+ <button
+ key={engine.value}
+ type="button"
+ onClick={() => onChange(engine.value)}
+ className={`rounded-md border px-2.5 py-1 text-xs transition-colors ${
+ value === engine.value
+ ? "border-primary bg-primary text-primary-foreground"
+ : "border-border hover:bg-accent"
+ }`}
+ title={engine.hint}
+ >
+ {engine.label}
+ </button>
+ ))}
+ </div>
+ <Input
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder="Custom SerpApi engine, e.g. google_finance"
+ />
+ {isCustom && (
+ <p className="text-xs text-muted-foreground">
+ Custom engine will be sent as the SerpApi `engine` parameter.
+ </p>
)}
</div>
)
diff --git a/src/components/settings/settings-types.ts b/src/components/settings/settings-types.ts
index aae8b94d..69b380af 100644
--- a/src/components/settings/settings-types.ts
+++ b/src/components/settings/settings-types.ts
@@ -37,10 +37,6 @@ export interface SettingsDraft {
multimodalApiMode: CustomApiMode | undefined
multimodalConcurrency: number
- // Web search
- searchProvider: "tavily" | "none"
- searchApiKey: string
-
// Output preferences
outputLanguage: string
maxHistoryMessages: number
diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsx
index 99d2f74a..db7d64f3 100644
--- a/src/components/settings/settings-view.tsx
+++ b/src/components/settings/settings-view.tsx
@@ -67,7 +67,6 @@ const CATEGORIES: Category[] = [
function initialDraft(
llm: ReturnType<typeof useWikiStore.getState>["llmConfig"],
- search: ReturnType<typeof useWikiStore.getState>["searchApiConfig"],
embed: ReturnType<typeof useWikiStore.getState>["embeddingConfig"],
multimodal: ReturnType<typeof useWikiStore.getState>["multimodalConfig"],
outputLanguage: ReturnType<typeof useWikiStore.getState>["outputLanguage"],
@@ -98,8 +97,6 @@ function initialDraft(
multimodalCustomEndpoint: multimodal.customEndpoint,
multimodalApiMode: multimodal.apiMode,
multimodalConcurrency: multimodal.concurrency,
- searchProvider: search.provider,
- searchApiKey: search.apiKey,
outputLanguage,
maxHistoryMessages,
proxyEnabled: proxy.enabled,
@@ -113,8 +110,6 @@ export function SettingsView() {
const { t } = useTranslation()
const llmConfig = useWikiStore((s) => s.llmConfig)
const setLlmConfig = useWikiStore((s) => s.setLlmConfig)
- const searchApiConfig = useWikiStore((s) => s.searchApiConfig)
- const setSearchApiConfig = useWikiStore((s) => s.setSearchApiConfig)
const embeddingConfig = useWikiStore((s) => s.embeddingConfig)
const setEmbeddingConfig = useWikiStore((s) => s.setEmbeddingConfig)
const multimodalConfig = useWikiStore((s) => s.multimodalConfig)
@@ -140,7 +135,6 @@ export function SettingsView() {
const [draft, setDraftState] = useState<SettingsDraft>(() =>
initialDraft(
llmConfig,
- searchApiConfig,
embeddingConfig,
multimodalConfig,
outputLanguage,
@@ -162,7 +156,6 @@ export function SettingsView() {
setDraftState((prev) =>
initialDraft(
llmConfig,
- searchApiConfig,
embeddingConfig,
multimodalConfig,
outputLanguage,
@@ -173,7 +166,6 @@ export function SettingsView() {
)
}, [
llmConfig,
- searchApiConfig,
embeddingConfig,
multimodalConfig,
outputLanguage,
@@ -188,7 +180,6 @@ export function SettingsView() {
const handleSave = useCallback(async () => {
const {
saveLlmConfig,
- saveSearchApiConfig,
saveEmbeddingConfig,
saveMultimodalConfig,
saveOutputLanguage,
@@ -204,7 +195,6 @@ export function SettingsView() {
maxContextSize: draft.maxContextSize,
apiMode: draft.provider === "custom" ? draft.apiMode : undefined,
}
- const newSearch = { provider: draft.searchProvider, apiKey: draft.searchApiKey }
const newEmbed = {
enabled: draft.embeddingEnabled,
endpoint: draft.embeddingEndpoint,
@@ -239,8 +229,6 @@ export function SettingsView() {
setLlmConfig(newLlm)
await saveLlmConfig(newLlm)
- setSearchApiConfig(newSearch)
- await saveSearchApiConfig(newSearch)
setEmbeddingConfig(newEmbed)
await saveEmbeddingConfig(newEmbed)
setMultimodalConfig(newMultimodal)
@@ -270,7 +258,6 @@ export function SettingsView() {
}, [
draft,
setLlmConfig,
- setSearchApiConfig,
setEmbeddingConfig,
setOutputLanguage,
setProxyConfig,
@@ -290,7 +277,7 @@ export function SettingsView() {
case "multimodal":
return <MultimodalSection draft={draft} setDraft={setDraft} />
case "web-search":
- return <WebSearchSection draft={draft} setDraft={setDraft} />
+ return <WebSearchSection />
case "network":
return <NetworkSection draft={draft} setDraft={setDraft} />
case "output":
diff --git a/src/lib/web-search.test.ts b/src/lib/web-search.test.ts
new file mode 100644
index 00000000..6c825250
--- /dev/null
+++ b/src/lib/web-search.test.ts
@@ -0,0 +1,99 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { webSearch } from "./web-search"
+
+const fetchMock = vi.fn<typeof fetch>()
+
+function jsonResponse(body: unknown, init?: ResponseInit): Response {
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ ...init,
+ })
+}
+
+describe("webSearch", () => {
+ beforeEach(() => {
+ fetchMock.mockReset()
+ vi.stubGlobal("fetch", fetchMock)
+ })
+
+ it("normalizes Tavily results", async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({
+ results: [
+ { title: "A", url: "https://www.example.com/a", content: "Alpha" },
+ ],
+ }))
+
+ const out = await webSearch("alpha", { provider: "tavily", apiKey: "tvly" }, 3)
+
+ expect(fetchMock).toHaveBeenCalledWith("https://api.tavily.com/search", expect.objectContaining({
+ method: "POST",
+ }))
+ expect(out).toEqual([
+ { title: "A", url: "https://www.example.com/a", snippet: "Alpha", source: "example.com" },
+ ])
+ })
+
+ it("calls SerpApi Google Search and normalizes organic results", async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({
+ organic_results: [
+ { title: "Serp result", link: "https://www.serp.example/page", snippet: "Snippet" },
+ { title: "Second", link: "https://docs.example/item", snippet: "More" },
+ ],
+ }))
+
+ const out = await webSearch("knowledge graph", { provider: "serpapi", apiKey: "serp" }, 1)
+ const [url, init] = fetchMock.mock.calls[0]
+ const parsed = new URL(String(url))
+
+ expect(parsed.origin + parsed.pathname).toBe("https://serpapi.com/search")
+ expect(parsed.searchParams.get("engine")).toBe("google")
+ expect(parsed.searchParams.get("q")).toBe("knowledge graph")
+ expect(parsed.searchParams.get("api_key")).toBe("serp")
+ expect(parsed.searchParams.get("num")).toBe("1")
+ expect(init).toEqual(expect.objectContaining({ method: "GET" }))
+ expect(out).toEqual([
+ { title: "Serp result", url: "https://www.serp.example/page", snippet: "Snippet", source: "serp.example" },
+ ])
+ })
+
+ it("uses SerpApi provider-specific config and selected engine", async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({
+ news_results: [
+ { title: "News", link: "https://news.example/story", snippet: "Fresh" },
+ ],
+ }))
+
+ const out = await webSearch(
+ "ai policy",
+ {
+ provider: "serpapi",
+ apiKey: "",
+ providerConfigs: {
+ tavily: { apiKey: "tavily-key" },
+ serpapi: { apiKey: "serp-key", serpApiEngine: "google_news" },
+ },
+ },
+ 5,
+ )
+ const parsed = new URL(String(fetchMock.mock.calls[0][0]))
+
+ expect(parsed.searchParams.get("engine")).toBe("google_news")
+ expect(parsed.searchParams.get("api_key")).toBe("serp-key")
+ expect(out).toEqual([
+ { title: "News", url: "https://news.example/story", snippet: "Fresh", source: "news.example" },
+ ])
+ })
+
+ it("surfaces SerpApi JSON errors", async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse({ error: "Invalid API key" }))
+
+ await expect(webSearch("x", { provider: "serpapi", apiKey: "bad" }, 5))
+ .rejects.toThrow("SerpApi search failed: Invalid API key")
+ })
+
+ it("requires a configured search provider and key", async () => {
+ await expect(webSearch("x", { provider: "none", apiKey: "" }, 5))
+ .rejects.toThrow("Tavily or SerpApi API key")
+ })
+})
diff --git a/src/lib/web-search.ts b/src/lib/web-search.ts
index 4491aa06..30c93f38 100644
--- a/src/lib/web-search.ts
+++ b/src/lib/web-search.ts
@@ -1,4 +1,4 @@
-import type { SearchApiConfig } from "@/stores/wiki-store"
+import type { SearchApiConfig, SearchProvider, SearchProviderConfigs, SerpApiEngine } from "@/stores/wiki-store"
import { getHttpFetch, isFetchNetworkError } from "@/lib/tauri-fetch"
export interface WebSearchResult {
@@ -8,20 +8,71 @@ export interface WebSearchResult {
source: string
}
+export const SERPAPI_ENGINE_OPTIONS: { value: SerpApiEngine; label: string; hint: string }[] = [
+ { value: "google", label: "Google Web", hint: "SerpApi Google Search API organic results" },
+ { value: "google_news", label: "Google News", hint: "News-focused results" },
+ { value: "google_scholar", label: "Google Scholar", hint: "Academic papers and citations" },
+ { value: "google_patents", label: "Google Patents", hint: "Patent search results" },
+ { value: "bing", label: "Bing", hint: "Bing organic results" },
+ { value: "duckduckgo", label: "DuckDuckGo", hint: "DuckDuckGo organic results" },
+ { value: "google_images", label: "Google Images", hint: "Image search results" },
+ { value: "google_videos", label: "Google Videos", hint: "Video search results" },
+ { value: "youtube", label: "YouTube", hint: "YouTube video results" },
+]
+
+export function resolveSearchConfig(config: SearchApiConfig): SearchApiConfig {
+ const providerConfigs: SearchProviderConfigs = config.providerConfigs ?? {
+ ...(config.provider !== "none" && config.apiKey
+ ? { [config.provider]: { apiKey: config.apiKey, serpApiEngine: config.serpApiEngine } }
+ : {}),
+ }
+
+ const activeProvider = config.provider as SearchProvider
+ if (activeProvider === "none") {
+ return {
+ ...config,
+ provider: "none",
+ apiKey: "",
+ serpApiEngine: config.serpApiEngine ?? providerConfigs.serpapi?.serpApiEngine ?? "google",
+ providerConfigs,
+ }
+ }
+
+ const activeOverride = providerConfigs[activeProvider]
+ return {
+ ...config,
+ provider: activeProvider,
+ apiKey: activeOverride?.apiKey ?? config.apiKey ?? "",
+ serpApiEngine: activeOverride?.serpApiEngine ?? config.serpApiEngine ?? "google",
+ providerConfigs,
+ }
+}
+
export async function webSearch(
query: string,
config: SearchApiConfig,
maxResults: number = 10,
): Promise<WebSearchResult[]> {
- if (config.provider === "none" || !config.apiKey) {
- throw new Error("Web search not configured. Add a Tavily API key in Settings.")
+ const resolved = resolveSearchConfig(config)
+ if (resolved.provider === "none" || !resolved.apiKey) {
+ throw new Error("Web search not configured. Add a Tavily or SerpApi API key in Settings.")
}
- switch (config.provider) {
+ switch (resolved.provider) {
case "tavily":
- return tavilySearch(query, config.apiKey, maxResults)
+ return tavilySearch(query, resolved.apiKey, maxResults)
+ case "serpapi":
+ return serpApiSearch(query, resolved.apiKey, maxResults, resolved.serpApiEngine ?? "google")
default:
- throw new Error(`Unknown search provider: ${config.provider}`)
+ throw new Error(`Unknown search provider: ${resolved.provider}`)
+ }
+}
+
+function hostnameFromUrl(url: string): string {
+ try {
+ return new URL(url).hostname.replace("www.", "")
+ } catch {
+ return ""
}
}
@@ -67,6 +118,92 @@ async function tavilySearch(
title: r.title ?? "Untitled",
url: r.url ?? "",
snippet: r.content ?? "",
- source: new URL(r.url).hostname.replace("www.", ""),
+ source: hostnameFromUrl(r.url ?? ""),
}))
}
+
+async function serpApiSearch(
+ query: string,
+ apiKey: string,
+ maxResults: number,
+ engine: SerpApiEngine,
+): Promise<WebSearchResult[]> {
+ const params = new URLSearchParams({
+ engine,
+ q: query,
+ api_key: apiKey,
+ num: String(maxResults),
+ })
+
+ const httpFetch = await getHttpFetch()
+ let response: Response
+ try {
+ response = await httpFetch(`https://serpapi.com/search?${params.toString()}`, {
+ method: "GET",
+ headers: { Accept: "application/json" },
+ })
+ } catch (err) {
+ if (isFetchNetworkError(err)) {
+ throw new Error(
+ "Network error reaching serpapi.com. Check your connectivity and whether the SerpApi API key is still valid.",
+ )
+ }
+ throw err
+ }
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => "Unknown error")
+ throw new Error(`SerpApi search failed (${response.status}): ${errorText}`)
+ }
+
+ const data = await response.json()
+ if (typeof data.error === "string" && data.error.trim()) {
+ throw new Error(`SerpApi search failed: ${data.error}`)
+ }
+
+ return normalizeSerpApiResults(data, maxResults)
+}
+
+function normalizeSerpApiResults(data: {
+ organic_results?: unknown[]
+ news_results?: unknown[]
+ images_results?: unknown[]
+ video_results?: unknown[]
+ videos_results?: unknown[]
+ shopping_results?: unknown[]
+}, maxResults: number): WebSearchResult[] {
+ const rawResults =
+ data.organic_results ??
+ data.news_results ??
+ data.images_results ??
+ data.video_results ??
+ data.videos_results ??
+ data.shopping_results ??
+ []
+
+ return rawResults
+ .slice(0, maxResults)
+ .map((item) => normalizeSerpApiResult(item))
+}
+
+function normalizeSerpApiResult(item: unknown): WebSearchResult {
+ const r = item as {
+ title?: string
+ link?: string
+ url?: string
+ source?: string
+ snippet?: string
+ summary?: string
+ description?: string
+ thumbnail?: string
+ original?: string
+ displayed_link?: string
+ }
+ const url = r.link ?? r.url ?? r.original ?? r.thumbnail ?? ""
+ return {
+ title: r.title ?? "Untitled",
+ url,
+ snippet: r.snippet ?? r.summary ?? r.description ?? "",
+ source: hostnameFromUrl(url) || r.source || r.displayed_link || "",
+ }
+}
diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.ts
index ff5891cc..292dbd7b 100644
--- a/src/stores/wiki-store.ts
+++ b/src/stores/wiki-store.ts
@@ -19,9 +19,31 @@ interface LlmConfig {
apiMode?: CustomApiMode
}
+export type SearchProvider = "tavily" | "serpapi" | "none"
+export type SerpApiEngine =
+ | "google"
+ | "google_news"
+ | "google_scholar"
+ | "google_patents"
+ | "bing"
+ | "duckduckgo"
+ | "google_images"
+ | "google_videos"
+ | "youtube"
+ | string
+
+export interface SearchProviderOverride {
+ apiKey?: string
+ serpApiEngine?: SerpApiEngine
+}
+
+export type SearchProviderConfigs = Partial<Record<Exclude<SearchProvider, "none">, SearchProviderOverride>>
+
interface SearchApiConfig {
- provider: "tavily" | "none"
+ provider: SearchProvider
apiKey: string
+ serpApiEngine?: SerpApiEngine
+ providerConfigs?: SearchProviderConfigs
}
interface EmbeddingConfig {
@@ -228,6 +250,8 @@ export const useWikiStore = create<WikiState>((set) => ({
searchApiConfig: {
provider: "none",
apiKey: "",
+ serpApiEngine: "google",
+ providerConfigs: {},
},
embeddingConfig: {