Inject custom HTTP sessions for enterprise environments
masterIn enterprise environments using API gateways, you can pass a pre-configured requests.Session (sync) or httpx.AsyncClient (async) to TavilyClient or AsyncTavilyClient instead of an api_key.
Key Behaviors:
- If a custom session/client is provided,
api_keyis optional. - Custom session headers take precedence over SDK defaults.
- Custom session proxies take precedence over SDK proxy settings.
- Lifecycle: The SDK will not close externally-provided sessions; you are responsible for managing their lifecycle.
Sync Example:
import requests
from tavily import TavilyClient
session = requests.Session()
session.headers["Authorization"] = "Bearer your-gateway-token"
client = TavilyClient(session=session, api_base_url="https://your-gateway.com/tavily")
response = client.search("latest AI research")Async Example:
import httpx
from tavily import AsyncTavilyClient
custom_client = httpx.AsyncClient(headers={"Authorization": "Bearer token"}, base_url="https://your-gateway.com/tavily")
client = AsyncTavilyClient(client=custom_client)
response = await client.search("latest AI research")import requests
from tavily import TavilyClient
# Pre-configure a session with your gateway's auth
session = requests.Session()
session.headers["Authorization"] = "Bearer your-gateway-token"
session.headers["X-Subscription-Key"] = "your-subscription-key"
# No Tavily API key needed — auth is handled by the session
client = TavilyClient(
session=session,
api_base_url="https://your-gateway.com/tavily",
)
response = client.search("latest AI research")