Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Production-ready Tavily API integration patterns for search, extract, crawl, map, and research in Python and JavaScript.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/sdk.md
1# SDK Reference23## Table of Contents45- [Python SDK](#python-sdk)6- [JavaScript SDK](#javascript-sdk)7- [Async Patterns](#async-patterns)8- [Hybrid RAG](#hybrid-rag)910---1112## Python SDK1314### Installation1516```bash17pip install tavily-python18```1920### Client Initialization2122```python23from tavily import TavilyClient2425# Uses TAVILY_API_KEY env var (recommended)26client = TavilyClient()2728# Explicit API key29client = TavilyClient(api_key="tvly-YOUR_API_KEY")3031# With project tracking32client = TavilyClient(api_key="tvly-YOUR_API_KEY", project_id="your-project-id")3334# With proxies35proxies = {"http": "<proxy>", "https": "<proxy>"}36client = TavilyClient(api_key="tvly-YOUR_API_KEY", proxies=proxies)37```3839### Async Client4041```python42from tavily import AsyncTavilyClient4344async_client = AsyncTavilyClient()4546# Parallel queries47import asyncio48responses = await asyncio.gather(49async_client.search("query 1"),50async_client.search("query 2"),51async_client.search("query 3")52)53```5455### Methods5657#### search()5859```python60response = client.search(61query="quantum computing breakthroughs",62search_depth="advanced", # "basic" | "advanced"63topic="general", # "general" | "news" | "finance"64max_results=10, # 0-2065include_answer=False, # bool | "basic" | "advanced"66include_raw_content=False, # bool | "markdown" | "text"67include_images=False,68time_range="week", # "day" | "week" | "month" | "year"69include_domains=["arxiv.org"],70exclude_domains=["reddit.com"],71country="united states"72)73```7475#### extract()7677```python78response = client.extract(79urls=["https://example.com/page1", "https://example.com/page2"],80extract_depth="basic", # "basic" | "advanced"81format="markdown", # "markdown" | "text"82include_images=False,83query="focus query", # Reranks chunks by relevance84chunks_per_source=3 # 1-5, requires query85)86```8788#### crawl()8990```python91response = client.crawl(92url="https://docs.example.com",93max_depth=2, # 1-594max_breadth=20,95limit=50,96instructions="Find API documentation",97chunks_per_source=3, # 1-5, requires instructions98select_paths=["/docs/.*"],99exclude_paths=["/blog/.*"],100extract_depth="basic",101format="markdown",102allow_external=True103)104```105106#### map()107108```python109response = client.map(110url="https://docs.example.com",111max_depth=2,112max_breadth=20,113limit=50,114instructions="Find all API pages",115select_paths=["/api/.*"],116allow_external=False117)118```119120#### research()121122```python123# Start research task124result = client.research(125input="Analyze competitive landscape for X",126model="pro", # "mini" | "pro" | "auto"127stream=False,128output_schema=None, # JSON schema for structured output129citation_format="numbered" # "numbered" | "mla" | "apa" | "chicago"130)131132# Poll for results133import time134response = client.get_research(result["request_id"])135while response["status"] not in ["completed", "failed"]:136time.sleep(10)137response = client.get_research(result["request_id"])138```139140---141142## JavaScript SDK143144### Installation145146```bash147npm install @tavily/core148```149150### Client Initialization151152```javascript153const { tavily } = require("@tavily/core");154155// Basic initialization156const client = tavily({ apiKey: "tvly-YOUR_API_KEY" });157158// With project tracking159const client = tavily({160apiKey: "tvly-YOUR_API_KEY",161projectId: "your-project-id"162});163164// With proxies165const client = tavily({166apiKey: "tvly-YOUR_API_KEY",167proxies: {168http: "<proxy>",169https: "<proxy>"170}171});172```173174### Methods175176#### search()177178```javascript179const response = await client.search("quantum computing", {180searchDepth: "advanced", // "basic" | "advanced"181topic: "general", // "general" | "news" | "finance"182maxResults: 10, // 0-20183includeAnswer: false, // boolean | "basic" | "advanced"184includeRawContent: false, // boolean | "markdown" | "text"185includeImages: false,186timeRange: "week", // "day" | "week" | "month" | "year"187includeDomains: ["arxiv.org"],188excludeDomains: ["reddit.com"],189country: "united states"190});191```192193#### extract()194195```javascript196const response = await client.extract([197"https://example.com/page1",198"https://example.com/page2"199], {200extractDepth: "basic", // "basic" | "advanced"201format: "markdown", // "markdown" | "text"202includeImages: false,203query: "focus query" // Reranks chunks204});205```206207#### crawl()208209```javascript210const response = await client.crawl("https://docs.example.com", {211maxDepth: 2,212maxBreadth: 20,213limit: 50,214instructions: "Find API documentation",215selectPaths: ["/docs/.*"],216excludePaths: ["/blog/.*"],217extractDepth: "basic",218format: "markdown"219});220```221222#### map()223224```javascript225const response = await client.map("https://docs.example.com", {226maxDepth: 2,227maxBreadth: 20,228limit: 50,229instructions: "Find all API pages"230});231```232233---234235## Async Patterns236237### Python Parallel Queries238239```python240import asyncio241from tavily import AsyncTavilyClient242243client = AsyncTavilyClient()244245async def parallel_search():246queries = [247"AI trends 2025",248"machine learning best practices",249"LLM deployment strategies"250]251252responses = await asyncio.gather(253*(client.search(q, search_depth="advanced") for q in queries),254return_exceptions=True255)256257for query, response in zip(queries, responses):258if isinstance(response, Exception):259print(f"Failed: {query}")260else:261print(f"{query}: {len(response['results'])} results")262263asyncio.run(parallel_search())264```265266### JavaScript Parallel Queries267268```javascript269const queries = ["AI trends", "ML practices", "LLM strategies"];270271const responses = await Promise.all(272queries.map(q => client.search(q, { searchDepth: "advanced" }))273);274275responses.forEach((response, i) => {276console.log(`${queries[i]}: ${response.results.length} results`);277});278```279280---281282## Hybrid RAG283284Combine web search with local database retrieval.285286### Python287288```python289from tavily import TavilyHybridClient290from pymongo import MongoClient291292# Connect to MongoDB293db = MongoClient("mongodb+srv://URI")["DB_NAME"]294295# Initialize hybrid client296hybrid_client = TavilyHybridClient(297api_key="tvly-YOUR_API_KEY",298db_provider="mongodb",299collection=db.get_collection("documents"),300embeddings_field="embeddings",301content_field="content"302)303304# Search across web + local DB305results = hybrid_client.search(306query="quantum computing advances",307max_results=10,308max_local=5, # Results from local DB309max_foreign=5, # Results from web310save_foreign=True # Store web results in DB311)312```313314**Environment Variables:**315- `TAVILY_PROJECT`: Default project ID316- `TAVILY_HTTP_PROXY` / `TAVILY_HTTPS_PROXY`: Proxy configuration317- `CO_API_KEY`: Cohere API key for embeddings318319---320321## Response Structures322323### Search Response324325```python326{327"query": str,328"results": [329{330"title": str,331"url": str,332"content": str,333"score": float,334"favicon": str335}336],337"response_time": float,338"request_id": str,339"answer": str, # if include_answer340"images": list # if include_images341}342```343344### Extract Response345346```python347{348"results": [349{350"url": str,351"raw_content": str,352"images": list,353"favicon": str354}355],356"failed_results": [357{"url": str, "error": str}358],359"response_time": float,360"request_id": str361}362```363364### Crawl Response365366```python367{368"base_url": str,369"results": [370{371"url": str,372"raw_content": str,373"images": list,374"favicon": str375}376],377"response_time": float,378"request_id": str379}380```381382### Map Response383384```python385{386"base_url": str,387"results": [str], # List of URLs388"response_time": float,389"request_id": str390}391```392393---394395For full API documentation, see:396- [Python SDK Reference](https://docs.tavily.com/sdk/python/reference)397- [JavaScript SDK Reference](https://docs.tavily.com/sdk/javascript/reference)398