Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added search1api for a search and retrieve tool #428

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
4 changes: 3 additions & 1 deletion .env.local.example
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ TAVILY_API_KEY=[YOUR_TAVILY_API_KEY] # Get your API key at: https://app.tavily.
# Alternative Search Providers
# Configure different search backends (default: Tavily)
#------------------------------------------------------------------------------
# SEARCH_API=searxng # Available options: tavily, searxng, exa
# SEARCH_API=searxng # Available options: tavily, searxng, exa, search1api

# SearXNG Configuration (Required if SEARCH_API=searxng)
# SEARXNG_API_URL=http://localhost:8080 # Replace with your local SearXNG API URL or docker http://searxng:8080
Expand All @@ -84,6 +84,8 @@ TAVILY_API_KEY=[YOUR_TAVILY_API_KEY] # Get your API key at: https://app.tavily.
# SEARXNG_TIME_RANGE=None
# SEARXNG_SAFESEARCH=0

# SEARCH1API_API_KEY=[YOUR_SEARCH1API_API_KEY](Required if SEARCH_API=search1api, it supports retrieve tool too)

#------------------------------------------------------------------------------
# Additional Features
# Enable extra functionality as needed
Expand Down
Binary file modified bun.lockb
Binary file not shown.
15 changes: 15 additions & 0 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,21 @@ LOCAL_REDIS_URL=redis://localhost:6379

## Search Providers

### Search1API Configuration

[Search1API](https://www.search1api.com) is a unified search API optimized for AI applications:

- **Image Search**: Built-in support for image search results
- **Advanced Search**: Advanced search mode with full content crawling when you need
- **Retrieval Tool**: Specialized tool for extracting content from specific URLs

Configure Search1API as your search and Retrieve tool:

```bash
SEARCH_API=search1api
SEARCH1API_API_KEY=[YOUR_SEARCH1API_API_KEY]
```

### SearXNG Configuration

SearXNG can be used as an alternative search backend with advanced search capabilities.
Expand Down
50 changes: 47 additions & 3 deletions lib/tools/retrieve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,59 @@ async function fetchTavilyExtractData(
}
}

async function fetchSearch1APIData(
url: string
): Promise<SearchResultsType | null> {
try {
const apiKey = process.env.SEARCH1API_API_KEY
if (!apiKey) {
console.error('Search1API API key is not set')
return null
}

const response = await fetch('https://api.search1api.com/crawl', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ url })
})

const json = await response.json()
if (!json.results) {
return null
}

const content = json.results.content.slice(0, CONTENT_CHARACTER_LIMIT)

return {
results: [
{
title: json.results.title,
content,
url: json.results.link || url
}
],
query: '',
images: []
}
} catch (error) {
console.error('Search1API Crawl error:', error)
return null
}
}

export const retrieveTool = tool({
description: 'Retrieve content from the web',
parameters: retrieveSchema,
execute: async ({ url }) => {
let results: SearchResultsType | null

// Use Jina if the API key is set, otherwise use Tavily
const useJina = process.env.JINA_API_KEY
if (useJina) {
// Use Search1API if SEARCH_API is set to search1api
if (process.env.SEARCH_API === 'search1api') {
results = await fetchSearch1APIData(url)
} else if (process.env.JINA_API_KEY) {
results = await fetchJinaReaderData(url)
} else {
results = await fetchTavilyExtractData(url)
Expand Down
60 changes: 54 additions & 6 deletions lib/tools/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const searchTool = tool({
query.length < 5 ? query + ' '.repeat(5 - query.length) : query
let searchResult: SearchResults
const searchAPI =
(process.env.SEARCH_API as 'tavily' | 'exa' | 'searxng') || 'tavily'
(process.env.SEARCH_API as 'tavily' | 'exa' | 'searxng' | 'search1api') || 'tavily'

const effectiveSearchDepth =
searchAPI === 'searxng' &&
Expand Down Expand Up @@ -64,12 +64,14 @@ export const searchTool = tool({
? tavilySearch
: searchAPI === 'exa'
? exaSearch
: searchAPI === 'search1api'
? search1apiSearch
: searxngSearch)(
filledQuery,
max_results,
effectiveSearchDepth === 'advanced' ? 'advanced' : 'basic',
include_domains,
exclude_domains
filledQuery,
max_results,
effectiveSearchDepth === 'advanced' ? 'advanced' : 'basic',
include_domains,
exclude_domains
)
}
} catch (error) {
Expand Down Expand Up @@ -279,3 +281,49 @@ async function searxngSearch(
throw error
}
}

async function search1apiSearch(
query: string,
maxResults: number = 10,
searchDepth: 'basic' | 'advanced' = 'basic',
includeDomains: string[] = [],
excludeDomains: string[] = []
): Promise<SearchResults> {
const apiKey = process.env.SEARCH1API_API_KEY
if (!apiKey) {
throw new Error('SEARCH1API_API_KEY is not set in the environment variables')
}

const response = await fetch('https://api.search1api.com/search', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
query,
search_service: 'google',
image: true,
max_results: maxResults,
crawl_results: searchDepth === 'advanced' ? maxResults : 0
})
})

if (!response.ok) {
throw new Error(
`Search1API error: ${response.status} ${response.statusText}`
)
}

const data = await response.json()
return {
results: data.results.map((result: any) => ({
title: result.title,
url: result.link,
content: result.content || result.snippet
})),
query,
images: data.images?.map((url: string) => sanitizeUrl(url)) || [],
number_of_results: data.results.length
}
}
21 changes: 21 additions & 0 deletions lib/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,24 @@ export type SearXNGSearchResults = {
number_of_results?: number
query: string
}

export interface Search1APIResult {
title: string
link: string
snippet: string
content: string
}

export interface Search1APIResponse {
searchParameters: {
query: string
search_service: string
max_results: number
crawl_results: number
gl: string
hl: string
image: boolean
}
results: Search1APIResult[]
images: string[]
}