Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

(feat/search) Search Categories (#2019)

Nicolasf3c73d00c000
diff --git a/apps/api/src/__tests__/lib/search-query-builder.test.ts b/apps/api/src/__tests__/lib/search-query-builder.test.ts
new file mode 100644
index 000000000..3f6af7c50
--- /dev/null
+++ b/apps/api/src/__tests__/lib/search-query-builder.test.ts
@@ -0,0 +1,241 @@
+import { describe, it, expect } from '@jest/globals';
+import {
+ buildSearchQuery,
+ getCategoryFromUrl,
+ getDefaultResearchSites
+} from '../../lib/search-query-builder';
+
+describe('Search Query Builder', () => {
+ describe('buildSearchQuery', () => {
+ it('should return base query when no categories provided', () => {
+ const result = buildSearchQuery('machine learning');
+ expect(result.query).toBe('machine learning');
+ expect(result.categoryMap.size).toBe(0);
+ });
+
+ it('should return base query when empty categories array provided', () => {
+ const result = buildSearchQuery('machine learning', []);
+ expect(result.query).toBe('machine learning');
+ expect(result.categoryMap.size).toBe(0);
+ });
+
+ it('should add GitHub filter for simple github category', () => {
+ const result = buildSearchQuery('web scraping', ['github']);
+ expect(result.query).toBe('web scraping (site:github.com)');
+ expect(result.categoryMap.get('github.com')).toBe('github');
+ expect(result.categoryMap.size).toBe(1);
+ });
+
+ it('should add default research sites for simple research category', () => {
+ const result = buildSearchQuery('neural networks', ['research']);
+ expect(result.query).toContain('neural networks (');
+ expect(result.query).toContain('site:arxiv.org');
+ expect(result.query).toContain('site:nature.com');
+ expect(result.query).toContain('site:ieee.org');
+ expect(result.query).toContain(' OR ');
+
+ // Check category map
+ expect(result.categoryMap.get('arxiv.org')).toBe('research');
+ expect(result.categoryMap.get('nature.com')).toBe('research');
+ expect(result.categoryMap.size).toBe(14); // All default research sites
+ });
+
+ it('should handle multiple simple categories', () => {
+ const result = buildSearchQuery('firecrawl', ['github', 'research']);
+ expect(result.query).toContain('firecrawl (');
+ expect(result.query).toContain('site:github.com');
+ expect(result.query).toContain('site:arxiv.org');
+ expect(result.query).toContain(' OR ');
+
+ expect(result.categoryMap.get('github.com')).toBe('github');
+ expect(result.categoryMap.get('arxiv.org')).toBe('research');
+ expect(result.categoryMap.size).toBe(15); // 1 GitHub + 14 research
+ });
+
+ it('should handle GitHub category as object', () => {
+ const result = buildSearchQuery('code review', [
+ { type: 'github' }
+ ]);
+ expect(result.query).toBe('code review (site:github.com)');
+ expect(result.categoryMap.get('github.com')).toBe('github');
+ });
+
+ it('should use custom research sites when provided', () => {
+ const result = buildSearchQuery('quantum computing', [
+ {
+ type: 'research',
+ sites: ['arxiv.org', 'nature.com']
+ }
+ ]);
+ expect(result.query).toBe('quantum computing (site:arxiv.org OR site:nature.com)');
+ expect(result.categoryMap.size).toBe(2);
+ expect(result.categoryMap.get('arxiv.org')).toBe('research');
+ expect(result.categoryMap.get('nature.com')).toBe('research');
+ });
+
+ it('should handle mixed string and object categories', () => {
+ const result = buildSearchQuery('AI research', [
+ 'github',
+ {
+ type: 'research',
+ sites: ['arxiv.org']
+ }
+ ]);
+ expect(result.query).toBe('AI research (site:github.com OR site:arxiv.org)');
+ expect(result.categoryMap.get('github.com')).toBe('github');
+ expect(result.categoryMap.get('arxiv.org')).toBe('research');
+ expect(result.categoryMap.size).toBe(2);
+ });
+
+ it('should handle special characters in base query', () => {
+ const result = buildSearchQuery('C++ programming', ['github']);
+ expect(result.query).toBe('C++ programming (site:github.com)');
+ });
+
+ it('should handle quotes in base query', () => {
+ const result = buildSearchQuery('"exact phrase" search', ['github']);
+ expect(result.query).toBe('"exact phrase" search (site:github.com)');
+ });
+
+ it('should ignore invalid category types', () => {
+ const result = buildSearchQuery('test', ['invalid' as any]);
+ expect(result.query).toBe('test');
+ expect(result.categoryMap.size).toBe(0);
+ });
+
+ it('should ignore invalid category objects', () => {
+ const result = buildSearchQuery('test', [
+ { type: 'invalid' as any }
+ ]);
+ expect(result.query).toBe('test');
+ expect(result.categoryMap.size).toBe(0);
+ });
+ });
+
+ describe('getCategoryFromUrl', () => {
+ const categoryMap = new Map([
+ ['github.com', 'github'],
+ ['arxiv.org', 'research'],
+ ['nature.com', 'research'],
+ ['ieee.org', 'research']
+ ]);
+
+ it('should identify GitHub URLs', () => {
+ expect(getCategoryFromUrl('https://github.com/user/repo', categoryMap))
+ .toBe('github');
+ expect(getCategoryFromUrl('https://www.github.com/user/repo', categoryMap))
+ .toBe('github');
+ expect(getCategoryFromUrl('http://github.com/user/repo', categoryMap))
+ .toBe('github');
+ });
+
+ it('should identify research URLs from category map', () => {
+ expect(getCategoryFromUrl('https://arxiv.org/abs/2024.12345', categoryMap))
+ .toBe('research');
+ expect(getCategoryFromUrl('https://www.nature.com/articles/s12345', categoryMap))
+ .toBe('research');
+ expect(getCategoryFromUrl('https://ieeexplore.ieee.org/document/12345', categoryMap))
+ .toBe('research');
+ });
+
+ it('should return undefined for unknown URLs', () => {
+ expect(getCategoryFromUrl('https://example.com', categoryMap))
+ .toBeUndefined();
+ expect(getCategoryFromUrl('https://google.com', categoryMap))
+ .toBeUndefined();
+ });
+
+ it('should handle invalid URLs gracefully', () => {
+ expect(getCategoryFromUrl('not-a-url', categoryMap))
+ .toBeUndefined();
+ expect(getCategoryFromUrl('', categoryMap))
+ .toBeUndefined();
+ expect(getCategoryFromUrl('ftp://example.com', categoryMap))
+ .toBeUndefined();
+ });
+
+ it('should be case-insensitive', () => {
+ expect(getCategoryFromUrl('https://GitHub.com/user/repo', categoryMap))
+ .toBe('github');
+ expect(getCategoryFromUrl('https://ArXiv.org/abs/2024.12345', categoryMap))
+ .toBe('research');
+ });
+
+ it('should work with subdomains', () => {
+ expect(getCategoryFromUrl('https://api.github.com/user/repo', categoryMap))
+ .toBe('github');
+ expect(getCategoryFromUrl('https://export.arxiv.org/abs/2024.12345', categoryMap))
+ .toBe('research');
+ });
+
+ it('should work with empty category map', () => {
+ const emptyMap = new Map<string, string>();
+ // GitHub is hardcoded, so it should still work
+ expect(getCategoryFromUrl('https://github.com/user/repo', emptyMap))
+ .toBe('github');
+ // Others should return undefined
+ expect(getCategoryFromUrl('https://arxiv.org/abs/2024.12345', emptyMap))
+ .toBeUndefined();
+ });
+ });
+
+ describe('getDefaultResearchSites', () => {
+ it('should return array of default research sites', () => {
+ const sites = getDefaultResearchSites();
+ expect(Array.isArray(sites)).toBe(true);
+ expect(sites.length).toBeGreaterThan(0);
+ expect(sites).toContain('arxiv.org');
+ expect(sites).toContain('nature.com');
+ expect(sites).toContain('ieee.org');
+ expect(sites).toContain('scholar.google.com');
+ });
+
+ it('should return a new array each time (no mutation)', () => {
+ const sites1 = getDefaultResearchSites();
+ const sites2 = getDefaultResearchSites();
+ expect(sites1).not.toBe(sites2); // Different array instances
+ expect(sites1).toEqual(sites2); // But same content
+ });
+ });
+
+ describe('Integration tests', () => {
+ it('should handle complex real-world query', () => {
+ const result = buildSearchQuery(
+ 'machine learning "neural networks" site:stackoverflow.com',
+ ['github', 'research']
+ );
+
+ // Should append category filters to existing query
+ expect(result.query).toContain('machine learning "neural networks" site:stackoverflow.com');
+ expect(result.query).toContain('(site:github.com OR site:arxiv.org');
+
+ // Check URLs can be categorized
+ const githubUrl = 'https://github.com/tensorflow/tensorflow';
+ const arxivUrl = 'https://arxiv.org/abs/2024.12345';
+
+ expect(getCategoryFromUrl(githubUrl, result.categoryMap)).toBe('github');
+ expect(getCategoryFromUrl(arxivUrl, result.categoryMap)).toBe('research');
+ });
+
+ it('should handle empty query with categories', () => {
+ const result = buildSearchQuery('', ['github']);
+ expect(result.query).toBe(' (site:github.com)');
+ });
+
+ it('should build correct query for multiple custom research sites', () => {
+ const customSites = ['pubmed.ncbi.nlm.nih.gov', 'biorxiv.org', 'medrxiv.org'];
+ const result = buildSearchQuery('COVID-19 research', [
+ { type: 'research', sites: customSites }
+ ]);
+
+ expect(result.query).toBe(
+ 'COVID-19 research (site:pubmed.ncbi.nlm.nih.gov OR site:biorxiv.org OR site:medrxiv.org)'
+ );
+
+ // All sites should be mapped to research
+ customSites.forEach(site => {
+ expect(result.categoryMap.get(site)).toBe('research');
+ });
+ });
+ });
+});
diff --git a/apps/api/src/controllers/v2/search.ts b/apps/api/src/controllers/v2/search.ts
index 2630363c9..f3815db91 100644
--- a/apps/api/src/controllers/v2/search.ts
+++ b/apps/api/src/controllers/v2/search.ts
@@ -26,6 +26,8 @@ import { calculateCreditsToBeBilled } from "../../lib/scrape-billing";
import { supabase_service } from "../../services/supabase";
import { SearchResult, SearchV2Response } from "../../lib/entities";
import { ScrapeJobTimeoutError } from "../../lib/error";
+import { z } from "zod";
+import { buildSearchQuery, getCategoryFromUrl, CategoryOption } from "../../lib/search-query-builder";
interface DocumentWithCostTracking {
document: Document;
@@ -196,8 +198,14 @@ export async function searchController(
// After transformation, sources is always an array of objects
const searchTypes = [...new Set(req.body.sources.map((s: any) => s.type))];
+ // Build search query with category filters
+ const { query: searchQuery, categoryMap } = buildSearchQuery(
+ req.body.query,
+ req.body.categories as CategoryOption[]
+ );
+
const searchResponse = await search({
- query: req.body.query,
+ query: searchQuery,
advanced: false,
num_results: num_results_buffer,
tbs: req.body.tbs,
@@ -215,6 +223,22 @@ export async function searchController(
);
}
+ // Add category labels to web results
+ if (searchResponse.web && searchResponse.web.length > 0) {
+ searchResponse.web = searchResponse.web.map(result => ({
+ ...result,
+ category: getCategoryFromUrl(result.url, categoryMap),
+ }));
+ }
+
+ // Add category labels to news results
+ if (searchResponse.news && searchResponse.news.length > 0) {
+ searchResponse.news = searchResponse.news.map(result => ({
+ ...result,
+ category: result.url ? getCategoryFromUrl(result.url, categoryMap) : undefined,
+ }));
+ }
+
// Apply limit to each result type separately
let totalResultsCount = 0;
@@ -288,6 +312,7 @@ export async function searchController(
title: doc.title || searchResponse.web![index].title,
description: doc.description || searchResponse.web![index].description,
position: searchResponse.web![index].position,
+ category: searchResponse.web![index].category,
markdown: doc.markdown,
html: doc.html,
rawHtml: doc.rawHtml,
@@ -332,6 +357,7 @@ export async function searchController(
const scrapedDoc = newsDocs.find(doc => doc.url === newsItem.url);
return {
...newsItem,
+ category: newsItem.category,
markdown: scrapedDoc?.markdown,
html: scrapedDoc?.html,
rawHtml: scrapedDoc?.rawHtml,
@@ -427,6 +453,15 @@ export async function searchController(
creditsUsed: credits_billed,
});
} catch (error) {
+ if (error instanceof z.ZodError) {
+ logger.warn("Invalid request body", { error: error.errors });
+ return res.status(400).json({
+ success: false,
+ error: "Invalid request body",
+ details: error.errors,
+ });
+ }
+
if (error instanceof ScrapeJobTimeoutError) {
return res.status(408).json({
success: false,
diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.ts
index 2f5b673f1..5bff6abd1 100644
--- a/apps/api/src/controllers/v2/types.ts
+++ b/apps/api/src/controllers/v2/types.ts
@@ -1268,6 +1268,18 @@ export type WebSearchSourceOptions = z.infer<typeof webSearchSourceOptions>;
export type ImagesSearchSourceOptions = z.infer<typeof imagesSearchSourceOptions>;
export type NewsSearchSourceOptions = z.infer<typeof newsSearchSourceOptions>;
+// Category source type definitions
+export const githubCategoryOptions = z.object({
+ type: z.literal("github"),
+}).strict();
+
+export const researchCategoryOptions = z.object({
+ type: z.literal("research"),
+}).strict();
+
+export type GithubCategoryOptions = z.infer<typeof githubCategoryOptions>;
+export type ResearchCategoryOptions = z.infer<typeof researchCategoryOptions>;
+
export const searchRequestSchema = z
.object({
query: z.string(),
@@ -1297,6 +1309,19 @@ export const searchRequestSchema = z
])
.optional()
.default(["web"]),
+ categories: z
+ .union([
+ // Array of strings (simple format)
+ z.array(z.enum(["github", "research"])),
+ // Array of objects (advanced format)
+ z.array(
+ z.union([
+ githubCategoryOptions,
+ researchCategoryOptions,
+ ])
+ ),
+ ])
+ .optional(),
lang: z.string().optional().default("en"),
country: z.string().optional().default("us"),
location: z.string().optional(),
@@ -1383,9 +1408,34 @@ export const searchRequestSchema = z
// Otherwise it's already an object array, keep as is
}
+ // Transform string array categories to object format
+ let categories = x.categories;
+ if (categories && Array.isArray(categories) && categories.length > 0) {
+ // Check if it's a string array by checking the first element
+ if (typeof categories[0] === 'string') {
+ // It's a string array, transform to object array
+ categories = (categories as string[]).map((c) => {
+ switch (c) {
+ case 'github':
+ return {
+ type: 'github' as const
+ };
+ case 'research':
+ return {
+ type: 'research' as const,
+ };
+ default:
+ return { type: c as any };
+ }
+ });
+ }
+ // Otherwise it's already an object array, keep as is
+ }
+
return {
...x,
sources,
+ categories,
scrapeOptions: extractTransform(x.scrapeOptions),
};
});
diff --git a/apps/api/src/lib/entities.ts b/apps/api/src/lib/entities.ts
index e1f15c1cb..2f17f159f 100644
--- a/apps/api/src/lib/entities.ts
+++ b/apps/api/src/lib/entities.ts
@@ -167,6 +167,7 @@ export interface NewsSearchResult {
date?: string;
imageUrl?: string;
position?: number;
+ category?: string;
// Scraped content fields
markdown?: string;
html?: string;
@@ -181,6 +182,7 @@ export interface WebSearchResult {
title: string;
description: string;
position?: number;
+ category?: string;
// Scraped content fields
markdown?: string;
html?: string;
diff --git a/apps/api/src/lib/search-query-builder.ts b/apps/api/src/lib/search-query-builder.ts
new file mode 100644
index 000000000..95b83fefd
--- /dev/null
+++ b/apps/api/src/lib/search-query-builder.ts
@@ -0,0 +1,135 @@
+/**
+ * Search Query Builder
+ * Builds search queries with category filters for the search API
+ */
+
+export interface CategoryInput {
+ type: 'github' | 'research';
+ sites?: string[];
+}
+
+export type CategoryOption = string | CategoryInput;
+
+export interface QueryBuilderResult {
+ query: string;
+ categoryMap: Map<string, string>;
+}
+
+// Default research sites
+const DEFAULT_RESEARCH_SITES = [
+ "arxiv.org",
+ "scholar.google.com",
+ "pubmed.ncbi.nlm.nih.gov",
+ "researchgate.net",
+ "nature.com",
+ "science.org",
+ "ieee.org",
+ "acm.org",
+ "springer.com",
+ "wiley.com",
+ "sciencedirect.com",
+ "plos.org",
+ "biorxiv.org",
+ "medrxiv.org"
+];
+
+/**
+ * Builds a search query with category filters
+ * @param baseQuery The base search query
+ * @param categories Optional array of categories to filter by
+ * @returns The final query string and a map of sites to categories
+ */
+export function buildSearchQuery(
+ baseQuery: string,
+ categories?: CategoryOption[]
+): QueryBuilderResult {
+ const categoryMap = new Map<string, string>();
+
+ if (!categories || categories.length === 0) {
+ return {
+ query: baseQuery,
+ categoryMap
+ };
+ }
+
+ const siteFilters: string[] = [];
+
+ for (const category of categories) {
+ if (typeof category === 'string') {
+ // Simple string format
+ if (category === 'github') {
+ siteFilters.push("site:github.com");
+ categoryMap.set("github.com", "github");
+ } else if (category === 'research') {
+ // Use default research sites
+ for (const site of DEFAULT_RESEARCH_SITES) {
+ siteFilters.push(`site:${site}`);
+ categoryMap.set(site, "research");
+ }
+ }
+ } else {
+ // Object format with options
+ if (category.type === 'github') {
+ siteFilters.push("site:github.com");
+ categoryMap.set("github.com", "github");
+ } else if (category.type === 'research') {
+ // Use custom sites if provided, otherwise defaults
+ const sites = category.sites || DEFAULT_RESEARCH_SITES;
+ for (const site of sites) {
+ siteFilters.push(`site:${site}`);
+ categoryMap.set(site, "research");
+ }
+ }
+ }
+ }
+
+ // Build the OR filter for sites
+ let categoryFilter = "";
+ if (siteFilters.length > 0) {
+ categoryFilter = " (" + siteFilters.join(" OR ") + ")";
+ }
+
+ return {
+ query: baseQuery + categoryFilter,
+ categoryMap
+ };
+}
+
+/**
+ * Determines the category for a given URL
+ * @param url The URL to categorize
+ * @param categoryMap Map of hostnames to categories
+ * @returns The category name or undefined
+ */
+export function getCategoryFromUrl(
+ url: string,
+ categoryMap: Map<string, string>
+): string | undefined {
+ try {
+ const urlObj = new URL(url);
+ const hostname = urlObj.hostname.toLowerCase();
+
+ // Direct match for GitHub
+ if (hostname === 'github.com' || hostname.endsWith('.github.com')) {
+ return 'github';
+ }
+
+ // Check against category map for other sites
+ for (const [site, category] of categoryMap.entries()) {
+ if (hostname === site.toLowerCase() || hostname.endsWith('.' + site.toLowerCase())) {
+ return category;
+ }
+ }
+ } catch (e) {
+ // Invalid URL, skip
+ }
+
+ return undefined;
+}
+
+/**
+ * Get default research sites
+ */
+export function getDefaultResearchSites(): string[] {
+ return [...DEFAULT_RESEARCH_SITES];
+}
diff --git a/apps/js-sdk/firecrawl/src/v2/methods/search.ts b/apps/js-sdk/firecrawl/src/v2/methods/search.ts
index 5653f3a5c..b94c8dbca 100644
--- a/apps/js-sdk/firecrawl/src/v2/methods/search.ts
+++ b/apps/js-sdk/firecrawl/src/v2/methods/search.ts
@@ -11,6 +11,7 @@ function prepareSearchPayload(req: SearchRequest): Record<string, unknown> {
query: req.query,
};
if (req.sources) payload.sources = req.sources;
+ if (req.categories) payload.categories = req.categories;
if (req.limit != null) payload.limit = req.limit;
if (req.tbs != null) payload.tbs = req.tbs;
if (req.location != null) payload.location = req.location;
diff --git a/apps/js-sdk/firecrawl/src/v2/types.ts b/apps/js-sdk/firecrawl/src/v2/types.ts
index b6193da10..a52ecc3b4 100644
--- a/apps/js-sdk/firecrawl/src/v2/types.ts
+++ b/apps/js-sdk/firecrawl/src/v2/types.ts
@@ -177,6 +177,7 @@ export interface SearchResultWeb {
url: string;
title?: string;
description?: string;
+ category?: string;
}
export interface SearchResultNews {
@@ -186,6 +187,7 @@ export interface SearchResultNews {
date?: string;
imageUrl?: string;
position?: number;
+ category?: string;
}
export interface SearchResultImages {
@@ -203,9 +205,14 @@ export interface SearchData {
images?: Array<SearchResultImages | Document>;
}
+export interface CategoryOption {
+ type: "github" | "research";
+}
+
export interface SearchRequest {
query: string;
sources?: Array<"web" | "news" | "images" | { type: "web" | "news" | "images" }>;
+ categories?: Array<"github" | "research" | CategoryOption>;
limit?: number;
tbs?: string;
location?: string;
diff --git a/apps/python-sdk/firecrawl/v2/methods/search.py b/apps/python-sdk/firecrawl/v2/methods/search.py
index 68d120092..aedd51c1c 100644
--- a/apps/python-sdk/firecrawl/v2/methods/search.py
+++ b/apps/python-sdk/firecrawl/v2/methods/search.py
@@ -121,6 +121,17 @@ def _validate_search_request(request: SearchRequest) -> SearchRequest:
if source.type not in valid_sources:
raise ValueError(f"Invalid source type: {source.type}. Valid types: {valid_sources}")
+ # Validate categories (if provided)
+ if request.categories is not None:
+ valid_categories = {"github", "research"}
+ for category in request.categories:
+ if isinstance(category, str):
+ if category not in valid_categories:
+ raise ValueError(f"Invalid category type: {category}. Valid types: {valid_categories}")
+ elif hasattr(category, 'type'):
+ if category.type not in valid_categories:
+ raise ValueError(f"Invalid category type: {category.type}. Valid types: {valid_categories}")
+
# Validate location (if provided)
if request.location is not None:
if not isinstance(request.location, str) or len(request.location.strip()) == 0:
diff --git a/apps/python-sdk/firecrawl/v2/types.py b/apps/python-sdk/firecrawl/v2/types.py
index 159fa9cc6..bff13327c 100644
--- a/apps/python-sdk/firecrawl/v2/types.py
+++ b/apps/python-sdk/firecrawl/v2/types.py
@@ -174,6 +174,12 @@ class Source(BaseModel):
SourceOption = Union[str, Source]
+class Category(BaseModel):
+ """Configuration for a search category."""
+ type: str
+
+CategoryOption = Union[str, Category]
+
FormatString = Literal[
# camelCase versions (API format)
"markdown", "html", "rawHtml", "links", "screenshot", "summary", "changeTracking", "json",
@@ -331,7 +337,8 @@ class SearchResultWeb(BaseModel):
"""A web search result with URL, title, and description."""
url: str
title: Optional[str] = None
- description: Optional[str] = None
+ description: Optional[str] = None
+ category: Optional[str] = None
class SearchResultNews(BaseModel):
"""A news search result with URL, title, snippet, date, image URL, and position."""
@@ -341,6 +348,7 @@ class SearchResultNews(BaseModel):
date: Optional[str] = None
image_url: Optional[str] = None
position: Optional[int] = None
+ category: Optional[str] = None
class SearchResultImages(BaseModel):
"""An image search result with URL, title, image URL, image width, image height, and position."""
@@ -521,6 +529,7 @@ class SearchRequest(BaseModel):
"""Request for search operations."""
query: str
sources: Optional[List[SourceOption]] = None
+ categories: Optional[List[CategoryOption]] = None
limit: Optional[int] = 5
tbs: Optional[str] = None
location: Optional[str] = None
@@ -547,6 +556,26 @@ class SearchRequest(BaseModel):
raise ValueError(f"Invalid source format: {source}")
return normalized_sources
+
+ @field_validator('categories')
+ @classmethod
+ def validate_categories(cls, v):
+ """Validate and normalize categories input."""
+ if v is None:
+ return v
+
+ normalized_categories = []
+ for category in v:
+ if isinstance(category, str):
+ normalized_categories.append(Category(type=category))
+ elif isinstance(category, dict):
+ normalized_categories.append(Category(**category))
+ elif isinstance(category, Category):
+ normalized_categories.append(category)
+ else:
+ raise ValueError(f"Invalid category format: {category}")
+
+ return normalized_categories
class LinkResult(BaseModel):
"""A generic link result with optional metadata (used by search and map)."""