Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ VIDEO_SORA_BASE_URL=
# --- Web Search ---------------------------------------------------------------

TAVILY_API_KEY=
BRAVE_API_KEY=
BAIDU_API_KEY=

# --- Proxy (optional) --------------------------------------------------------

Expand Down
50 changes: 43 additions & 7 deletions app/api/web-search/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,74 @@
* Web Search API
*
* POST /api/web-search
* Simple JSON request/response using Tavily search.
* Simple JSON request/response supporting multiple search providers.
*/

import { searchWithTavily, formatSearchResultsAsContext } from '@/lib/web-search/tavily';
import { searchWithTavily } from '@/lib/web-search/tavily';
import { searchWithBrave } from '@/lib/web-search/brave';
import { searchWithBaidu } from '@/lib/web-search/baidu';
import { formatSearchResultsAsContext } from '@/lib/web-search/tavily';
import { resolveWebSearchApiKey } from '@/lib/server/provider-config';
import { createLogger } from '@/lib/logger';
import { apiError, apiSuccess } from '@/lib/server/api-response';
import type { WebSearchProviderId } from '@/lib/web-search/types';

const log = createLogger('WebSearch');

export async function POST(req: Request) {
try {
const body = await req.json();
const { query, apiKey: clientApiKey } = body as {
const {
query,
apiKey: clientApiKey,
provider = 'tavily',
baiduSubSources,
} = body as {
query?: string;
apiKey?: string;
provider?: WebSearchProviderId;
baiduSubSources?: { webSearch?: boolean; baike?: boolean; scholar?: boolean };
};

if (!query || !query.trim()) {
return apiError('MISSING_REQUIRED_FIELD', 400, 'query is required');
}

const apiKey = resolveWebSearchApiKey(clientApiKey);
if (!apiKey) {
// Brave Search doesn't require an API key
const needsApiKey = provider !== 'brave';
const apiKey = needsApiKey ? resolveWebSearchApiKey(provider, clientApiKey) : '';

if (needsApiKey && !apiKey) {
const providerNames: Record<string, string> = {
tavily: 'Tavily',
baidu: 'Baidu',
};
const name = providerNames[provider] || provider;
return apiError(
'MISSING_API_KEY',
400,
'Tavily API key is not configured. Set it in Settings → Web Search or set TAVILY_API_KEY env var.',
`${name} API key is not configured. Set it in Settings → Web Search or set the corresponding env var.`,
);
}

const result = await searchWithTavily({ query: query.trim(), apiKey });
let result;
switch (provider) {
case 'brave':
result = await searchWithBrave({ query: query.trim() });
break;
case 'baidu':
result = await searchWithBaidu({
query: query.trim(),
apiKey,
subSources: baiduSubSources,
});
break;
case 'tavily':
default:
result = await searchWithTavily({ query: query.trim(), apiKey });
break;
}

const context = formatSearchResultsAsContext(result);

return apiSuccess({
Expand Down
3 changes: 3 additions & 0 deletions app/generation-preview/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,9 @@ function GenerationPreviewContent() {
body: JSON.stringify({
query: currentSession.requirements.requirement,
apiKey: wsApiKey || undefined,
provider: wsSettings.webSearchProviderId,
baiduSubSources:
wsSettings.webSearchProviderId === 'baidu' ? wsSettings.baiduSubSources : undefined,
}),
signal,
});
Expand Down
15 changes: 15 additions & 0 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { nanoid } from 'nanoid';
import { storePdfBlob } from '@/lib/utils/image-storage';
import type { UserRequirements } from '@/lib/types/generation';
import { useSettingsStore } from '@/lib/store/settings';
import { WEB_SEARCH_PROVIDERS } from '@/lib/web-search/constants';
import { useUserProfileStore, AVATAR_OPTIONS } from '@/lib/store/user-profile';
import {
StageListItem,
Expand Down Expand Up @@ -247,6 +248,20 @@ function HomePage() {
return;
}

// Block if web search is enabled but the selected provider is unusable
if (form.webSearch) {
const settings = useSettingsStore.getState();
const wsProvider = WEB_SEARCH_PROVIDERS[settings.webSearchProviderId];
const wsCfg = settings.webSearchProvidersConfig[settings.webSearchProviderId];
const isUsable =
wsProvider &&
(!wsProvider.requiresApiKey || !!wsCfg?.apiKey || !!wsCfg?.isServerConfigured);
if (!isUsable) {
toast.warning(t('toolbar.webSearchProviderUnavailable'));
return;
}
}

setError(null);

try {
Expand Down
49 changes: 39 additions & 10 deletions components/generation/generation-toolbar.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use client';

import { useState, useRef, useMemo } from 'react';
import { toast } from 'sonner';
import { Bot, Check, ChevronLeft, Globe, Paperclip, FileText, X, Globe2 } from 'lucide-react';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
Expand Down Expand Up @@ -64,14 +65,19 @@ export function GenerationToolbar({
const fileInputRef = useRef<HTMLInputElement>(null);
const [isDragging, setIsDragging] = useState(false);

// Check if the selected web search provider has a valid config (API key or server-configured)
const webSearchProvider = WEB_SEARCH_PROVIDERS[webSearchProviderId];
const webSearchConfig = webSearchProvidersConfig[webSearchProviderId];
const webSearchAvailable = webSearchProvider
? !webSearchProvider.requiresApiKey ||
!!webSearchConfig?.apiKey ||
!!webSearchConfig?.isServerConfigured
: false;
// Check if ANY web search provider is usable (has API key, server-configured, or doesn't need key)
const webSearchAvailable = Object.values(WEB_SEARCH_PROVIDERS).some((provider) => {
const cfg = webSearchProvidersConfig[provider.id];
return !provider.requiresApiKey || !!cfg?.apiKey || !!cfg?.isServerConfigured;
});

// Check if the *selected* provider can actually execute a search
const isSelectedProviderUsable = (() => {
const provider = WEB_SEARCH_PROVIDERS[webSearchProviderId];
if (!provider) return false;
const cfg = webSearchProvidersConfig[provider.id];
return !provider.requiresApiKey || !!cfg?.apiKey || !!cfg?.isServerConfigured;
})();

// Configured LLM providers (only those with valid credentials + models + endpoint)
const configuredProviders = providersConfig
Expand Down Expand Up @@ -276,7 +282,15 @@ export function GenerationToolbar({
<Popover>
<PopoverTrigger asChild>
<button className={webSearch ? pillActive : pillMuted}>
<Globe2 className={cn('size-3.5', webSearch && 'animate-pulse')} />
{webSearch && WEB_SEARCH_PROVIDERS[webSearchProviderId]?.icon ? (
<img
src={WEB_SEARCH_PROVIDERS[webSearchProviderId].icon}
alt=""
className="size-3.5 rounded-sm object-contain"
/>
) : (
<Globe2 className={cn('size-3.5', webSearch && 'animate-pulse')} />
)}
{webSearch && (
<span>{WEB_SEARCH_PROVIDERS[webSearchProviderId]?.name || 'Search'}</span>
)}
Expand All @@ -285,7 +299,13 @@ export function GenerationToolbar({
<PopoverContent align="start" className="w-64 p-3 space-y-3">
{/* Toggle */}
<button
onClick={() => onWebSearchChange(!webSearch)}
onClick={() => {
if (!webSearch && !isSelectedProviderUsable) {
toast.warning(t('toolbar.webSearchProviderUnavailable'));
return;
}
onWebSearchChange(!webSearch);
}}
className={cn(
'w-full flex items-center gap-2.5 rounded-lg border px-3 py-2.5 text-left transition-all',
webSearch
Expand Down Expand Up @@ -331,6 +351,15 @@ export function GenerationToolbar({
<div
className={cn('flex items-center gap-1.5', !available && 'opacity-50')}
>
{provider.icon ? (
<img
src={provider.icon}
alt=""
className="size-4 rounded-sm object-contain"
/>
) : (
<Globe2 className="size-4" />
)}
{provider.name}
{cfg?.isServerConfigured && (
<span className="text-[9px] px-1 py-0 rounded border text-muted-foreground">
Expand Down
Loading
Loading