@unsearch/sdk
v0.2.0
Published
UnSearch SDK - Tavily-compatible AI search API with RAG capabilities
Maintainers
Readme
UnSearch JavaScript SDK
The official JavaScript/TypeScript SDK for UnSearch - comprehensive AI search API with full backend capabilities.
Features
- 🔄 Tavily-compatible - Drop-in replacement for Tavily API
- 🧠 Exa-compatible - Neural/semantic search endpoints
- 🤖 AI-powered search - Get intelligent answers, not just links
- 📚 RAG optimized - Built for retrieval augmented generation
- 🌐 70+ search engines - Aggregated results from multiple sources
- 🔒 Type-safe - Full TypeScript support
- ⚡ Fast & reliable - Automatic retries and timeout handling
- 🎯 Zero-retention mode - Privacy-first architecture
- 📡 Topic monitoring - Real-time web monitoring
- ✅ Fact verification - AI-powered fact-checking
Installation
npm install unsearch
# or
yarn add unsearch
# or
pnpm add unsearchQuick Start
import { UnSearchClient } from 'unsearch';
const client = new UnSearchClient({
apiKey: 'uns_...' // or set UNSEARCH_API_KEY env var
});
// Simple search with AI answer
const results = await client.search({
query: 'What is retrieval augmented generation?',
includeAnswer: true,
maxResults: 5
});
console.log(results.answer);
console.log(results.results);Usage Examples
Basic Search
// Basic web search
const results = await client.search({
query: 'latest AI developments 2026',
maxResults: 10,
searchDepth: 'advanced'
});
results.results.forEach(result => {
console.log(result.title, result.url);
});Search with AI Answer
// Get direct answers to questions
const response = await client.search({
query: 'How does vector search work?',
includeAnswer: true,
model: 'quality', // Use high-quality LLM
maxResults: 5
});
console.log('Answer:', response.answer);
console.log('Sources:', response.results.length);Quick Q&A
// Shortcut for simple questions
const answer = await client.qna('What is the capital of France?');
console.log(answer); // "Paris is the capital of France..."Content Extraction
// Extract and parse content from URLs
const extracted = await client.extract({
urls: [
'https://example.com/article1',
'https://example.com/article2'
],
extractDepth: 'advanced',
includeImages: true
});
extracted.results.forEach(content => {
console.log(content.title);
console.log(content.markdown); // Markdown formatted
console.log(content.images);
});Deep Research (UnSearch Exclusive)
// Multi-step research with AI synthesis
const research = await client.research({
topic: 'Impact of AI on healthcare',
depth: 'deep', // quick | standard | deep | comprehensive
maxSources: 20,
includeAnalysis: true,
focusAreas: ['diagnostics', 'drug discovery', 'patient care']
});
console.log(research.executiveSummary);
console.log(research.keyFindings);
console.log(research.sources.length); // 20+ sourcesRAG Search (Optimized for AI Apps)
// Get search results formatted for RAG
const ragResults = await client.ragSearch({
query: 'machine learning best practices',
maxSources: 5,
scrapeContent: true,
includeContext: true
});
// Use context directly in your LLM prompt
const context = ragResults.context;
const prompt = `Based on this context: ${context}\n\nAnswer: ${query}`;Get Search Context for RAG
// Tavily-compatible method for RAG context
const context = await client.getSearchContext(
'What are the latest developments in quantum computing?',
5 // max results
);
// Feed context to your LLM
const answer = await yourLLM.generate({
prompt: `Context: ${context}\n\nQuestion: ...`,
});Neural Search (Exa-compatible)
// Semantic search with auto-prompting
const neural = await client.neuralSearch({
query: 'innovations in renewable energy',
numResults: 10,
useAutoprompt: true, // AI expands query for better recall
includeHighlights: true,
category: 'tech'
});
console.log('Expanded queries:', neural.expandedQueries);
neural.results.forEach(r => {
console.log(r.title, r.highlights);
});Find Similar Content
// Find content similar to a URL
const similar = await client.findSimilar({
url: 'https://example.com/article',
numResults: 10,
excludeSource: true
});
// Or find similar to text
const similarText = await client.findSimilar({
text: 'Your article content here...',
numResults: 5
});Topic Monitoring
// Create a monitor for real-time updates
const monitor = await client.createMonitor({
topic: 'artificial intelligence regulations',
keywords: ['AI', 'regulation', 'EU', 'policy'],
checkIntervalMinutes: 60,
webhookUrl: 'https://your-app.com/webhook',
deepAnalysis: true
});
// List monitors
const monitors = await client.listMonitors();
// Get results
const results = await client.getMonitorResults(monitor.id, 50);Fact Verification
// Verify a claim
const verification = await client.verifyClaim({
claim: 'The Earth is approximately 4.5 billion years old',
depth: 'thorough'
});
console.log('Verdict:', verification.verdict); // true, false, partially_true, etc.
console.log('Confidence:', verification.confidence);
console.log('Summary:', verification.summary);
console.log('Supporting evidence:', verification.supportingEvidence);
// Check source credibility
const credibility = await client.checkSourceCredibility({
url: 'https://example-news.com'
});
console.log('Credibility score:', credibility.credibilityScore);
console.log('Bias rating:', credibility.biasRating);Advanced Options
Search Options
const results = await client.search({
query: 'artificial intelligence',
maxResults: 10,
searchDepth: 'advanced', // basic | advanced | fast | ultra-fast
includeAnswer: true,
includeRawContent: true,
includeImages: true,
includeDomains: ['arxiv.org', 'nature.com'], // Filter sources
excludeDomains: ['example.com'],
model: 'quality', // auto | speed | quality | reasoning | production
rerank: true, // Use AI reranking
topic: 'news', // general | news
});Model Selection
UnSearch supports intelligent model selection based on query complexity:
auto- Automatically choose best model (default)speed- Fast responses, simple queries (llama-3.1-8b)quality- Best quality answers (gpt-oss-120b)reasoning- Complex analysis (qwq-32b)production- Enterprise-grade (gpt-oss-120b)
Error Handling
import {
UnSearchClient,
UnSearchAuthError,
UnSearchRateLimitError,
UnSearchNetworkError
} from 'unsearch';
try {
const results = await client.search({ query: 'test' });
} catch (error) {
if (error instanceof UnSearchAuthError) {
console.error('Invalid API key');
} else if (error instanceof UnSearchRateLimitError) {
console.error('Rate limit exceeded, please retry later');
} else if (error instanceof UnSearchNetworkError) {
console.error('Network error:', error.message);
} else {
console.error('Unknown error:', error);
}
}Configuration
Client Options
const client = new UnSearchClient({
apiKey: 'uns_...', // Required (or set UNSEARCH_API_KEY env var)
baseUrl: 'https://api.unsearch.dev', // Optional
timeout: 30000, // Request timeout in ms (default: 30000)
maxRetries: 3, // Max retry attempts (default: 3)
});Environment Variables
UNSEARCH_API_KEY=uns_...
UNSEARCH_BASE_URL=https://api.unsearch.dev # OptionalMigration from Tavily
UnSearch is 100% compatible with Tavily's API. Simply replace the client:
// Before (Tavily)
import { TavilyClient } from '@tavily/core';
const client = new TavilyClient({ apiKey: '...' });
// After (UnSearch)
import { UnSearchClient } from 'unsearch';
const client = new UnSearchClient({ apiKey: '...' });
// All methods work the same!
const results = await client.search({ query: '...' });
const extracted = await client.extract({ urls: ['...'] });
const context = await client.getSearchContext('...', 5);Why Migrate to UnSearch?
| Feature | Tavily | UnSearch | |---------|--------|----------| | Cost at scale | ~$0.0075/query | $0.0003/query (96% less) | | Free tier | 1,000 queries | 5,000 queries (5x more) | | Search engines | Single | 70+ aggregated | | Self-hosted | ❌ | ✅ Open source | | Zero retention | ❌ | ✅ Privacy mode | | Deep research | ❌ | ✅ Multi-step synthesis | | Model choice | Single | 20+ AI models |
API Reference
Agent API (Tavily-compatible)
| Method | Description |
|--------|-------------|
| search(options) | AI-optimized web search with optional answer generation |
| extract(options) | Extract and parse content from URLs |
| research(options) | Multi-step deep research with AI synthesis |
| qna(query) | Quick Q&A shortcut - get direct answers |
| listModels() | List available AI models |
| agentHealth() | Agent API health check |
Core Search API
| Method | Description |
|--------|-------------|
| coreSearch(options) | Full-featured search with scraping, caching, etc. |
| batchSearch(options) | Search multiple queries in parallel |
| listEngines() | List available search engines |
| searchHealth() | Search API health check |
RAG API
| Method | Description |
|--------|-------------|
| ragResearch(options) | Deep RAG research on a topic |
| ragSearch(options) | Quick RAG-optimized search |
| getSearchContext(query, maxResults) | Get context string for RAG |
| semanticSearch(options) | Semantic search over a corpus |
| imageSearch(options) | Image search |
| generateQueries(topic, numQueries) | Generate research queries |
| listCorpora() | List all research corpora |
| getCorpusInfo(corpusId) | Get corpus info |
| deleteCorpus(corpusId) | Delete a corpus |
Neural API (Exa-compatible)
| Method | Description |
|--------|-------------|
| neuralSearch(options) | Neural/semantic search with auto-prompting |
| findSimilar(options) | Find content similar to URL or text |
| extractHighlights(options) | Extract key highlights from content |
| predictiveSearch(options) | Predict what user might search next |
| listNeuralCategories() | List neural search categories |
Topic Monitoring API
| Method | Description |
|--------|-------------|
| createMonitor(options) | Create a new topic monitor |
| listMonitors() | List all monitors |
| getMonitor(monitorId) | Get a specific monitor |
| pauseMonitor(monitorId) | Pause a monitor |
| resumeMonitor(monitorId) | Resume a monitor |
| deleteMonitor(monitorId) | Delete a monitor |
| triggerMonitorCheck(monitorId) | Manually trigger a check |
| getMonitorResults(monitorId, limit) | Get monitor results |
Enhanced API (Advanced scraping)
| Method | Description |
|--------|-------------|
| enhancedSearch(options) | Advanced search with extraction strategies |
| enhancedScrape(options) | Direct URL scraping with advanced features |
| enhancedFeatures() | List available enhanced features |
| extractTables(options) | Extract tables from HTML content |
| chunkContent(options) | Chunk text for RAG pipelines |
| discoverUrls(options) | Discover URLs from sitemaps/crawling |
| enhancedPerformance() | Get performance metrics |
Knowledge Graph API
| Method | Description |
|--------|-------------|
| knowledgeExtract(options) | Extract entities & relationships from text |
| knowledgeSearch(options) | Search the knowledge graph |
| knowledgePeople(options) | Search for people |
| knowledgeGetEntity(entityId) | Get a specific entity |
| knowledgeGraph(entityTypes?, limit?) | Get graph structure |
| knowledgeDeleteEntity(entityId) | Delete an entity |
Agent Registration API
| Method | Description |
|--------|-------------|
| registerAgent(options) | Register new AI agent (sandbox) |
| agentStatus() | Get current agent status |
| resendClaim() | Resend agent claim link |
Verification API (Fact-checking)
| Method | Description |
|--------|-------------|
| verifyClaim(options) | Verify a claim with multi-source fact-checking |
| checkSourceCredibility(options) | Check source/domain credibility |
| batchVerify(options) | Batch verify multiple claims |
| getBatchVerificationStatus(jobId) | Get batch verification status |
Examples
Check out the examples directory for complete examples:
TypeScript Support
This SDK is written in TypeScript and includes full type definitions. All methods are fully typed for the best developer experience.
import type {
SearchOptions,
SearchResponse,
ResearchOptions
} from 'unsearch';Contributing
We welcome contributions! Please see our Contributing Guide.
Support
- 📧 Email: [email protected]
- 💬 Discord: Join our community
- 📖 Docs: docs.unsearch.dev
- 🐛 Issues: GitHub Issues
License
MIT License - see LICENSE for details.
Links
Built with ❤️ by the UnSearch team
