tavily

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 5, 2026 License: MIT Imports: 8 Imported by: 0

README

Go Tavily Client

Go Version Go Report Card GoDoc CodeRabbit Pull Request Reviews

English | 中文

A thin, type-safe Go client for the Tavily API. Built for Go 1.26+.

Installation

go get github.com/solarhell/go-tavily

Quick Start

client := tavily.New("tvly-your-api-key")

resp, err := client.Search(ctx, &tavily.SearchParams{
    Query: "Go programming language",
})
answerMode := tavily.IncludeAnswerAdvanced

resp, err := client.Search(ctx, &tavily.SearchParams{
    Query:         "AI news",
    SearchDepth:   tavily.SearchDepthAdvanced,
    Topic:         tavily.TopicNews,
    TimeRange:     tavily.TimeRangeWeek,
    MaxResults:    10,
    IncludeAnswer: &answerMode,
})

Zero-value fields are omitted from the request — the API uses its own server-side defaults.

Country Filter

Use an ISO 3166-1 alpha-2 country code to boost search results from a specific country. The country filter is only available when topic is general (or unset). Country codes are case-insensitive.

resp, err := client.Search(ctx, &tavily.SearchParams{
    Query:   "latest tech news",
    Country: "US",
})

Note: Tavily supports ~160 countries. Unsupported country codes will be rejected at call time.
Supported country code mapping file: country.go.
Example codes: US/us, CN/cn, JP/jp.
The SDK handles country codes case-insensitively.
Current SDK mapping is implemented as of 2026-03-05.

Extract

resp, err := client.Extract(ctx, &tavily.ExtractParams{
    URLs:   []string{"https://example.com"},
    Format: tavily.FormatMarkdown,
})

Client Options

client := tavily.New("tvly-your-api-key",
    tavily.WithBaseURL("https://custom.api.com"),
    tavily.WithHTTPClient(&http.Client{Timeout: 45 * time.Second}),
)

If the API key is empty, it reads from the TAVILY_API_KEY environment variable.

Error Handling

resp, err := client.Search(ctx, &tavily.SearchParams{Query: "test"})
if err != nil {
    var apiErr *tavily.APIError
    if errors.As(err, &apiErr) {
        switch {
        case apiErr.IsUnauthorized():
            // invalid API key (401)
        case apiErr.IsRateLimit():
            // rate limited (429)
        case apiErr.IsPlanLimitExceeded():
            // plan usage limit (432)
        case apiErr.IsPayGoLimitExceeded():
            // pay-as-you-go limit (433)
        case apiErr.IsBadRequest():
            // invalid parameters (400)
        }
    }
}

Testing

go test -v -race ./...

Documentation

Overview

Package tavily provides a Go client for the Tavily AI-powered search and web content extraction API.

Usage:

client := tavily.New("tvly-your-api-key")
resp, err := client.Search(ctx, &tavily.SearchParams{
    Query: "Go programming language",
})

Index

Constants

View Source
const DefaultBaseURL = "https://api.tavily.com"

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
}

APIError represents an error response from the Tavily API.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) IsBadRequest

func (e *APIError) IsBadRequest() bool

IsBadRequest returns true if the error is due to invalid parameters (400).

func (*APIError) IsPayGoLimitExceeded

func (e *APIError) IsPayGoLimitExceeded() bool

IsPayGoLimitExceeded returns true if the pay-as-you-go limit is exceeded (433).

func (*APIError) IsPlanLimitExceeded

func (e *APIError) IsPlanLimitExceeded() bool

IsPlanLimitExceeded returns true if the plan usage limit is exceeded (432).

func (*APIError) IsRateLimit

func (e *APIError) IsRateLimit() bool

IsRateLimit returns true if the error is due to rate limiting (429).

func (*APIError) IsUnauthorized

func (e *APIError) IsUnauthorized() bool

IsUnauthorized returns true if the error is due to an invalid API key (401).

type Client

type Client struct {
	// contains filtered or unexported fields
}

func New

func New(apiKey string, opts ...Option) *Client

New creates a new Tavily API client. If apiKey is empty, it reads from TAVILY_API_KEY environment variable.

func (*Client) Extract

func (c *Client) Extract(ctx context.Context, params *ExtractParams) (*ExtractResponse, error)

Extract extracts content from one or more URLs via the Tavily API.

func (*Client) Search

func (c *Client) Search(ctx context.Context, params *SearchParams) (*SearchResponse, error)

Search performs a web search via the Tavily API.

type ExtractDepth

type ExtractDepth string

ExtractDepth controls the depth of content extraction.

const (
	ExtractDepthBasic    ExtractDepth = "basic"
	ExtractDepthAdvanced ExtractDepth = "advanced"
)

type ExtractFailedResult

type ExtractFailedResult struct {
	URL   string `json:"url"`
	Error string `json:"error"`
}

ExtractFailedResult represents a failed content extraction.

type ExtractParams

type ExtractParams struct {
	URLs            []string     `json:"urls"`
	Query           string       `json:"query,omitzero"`
	ChunksPerSource uint64       `json:"chunks_per_source,omitzero"`
	ExtractDepth    ExtractDepth `json:"extract_depth,omitzero"`
	IncludeImages   *bool        `json:"include_images,omitzero"`
	IncludeFavicon  *bool        `json:"include_favicon,omitzero"`
	Format          Format       `json:"format,omitzero"`
	Timeout         float64      `json:"timeout,omitzero"`
	IncludeUsage    *bool        `json:"include_usage,omitzero"`
}

ExtractParams is the request body for POST /extract. Zero-value fields are omitted; the API uses server-side defaults.

type ExtractResponse

type ExtractResponse struct {
	ResponseTime  float64               `json:"response_time"`
	Results       []ExtractResult       `json:"results"`
	FailedResults []ExtractFailedResult `json:"failed_results"`
	Usage         *Usage                `json:"usage,omitzero"`
	RequestID     string                `json:"request_id,omitzero"`
}

ExtractResponse is the response from POST /extract.

type ExtractResult

type ExtractResult struct {
	URL        string   `json:"url"`
	RawContent string   `json:"raw_content"`
	Images     []string `json:"images,omitzero"`
	Favicon    string   `json:"favicon,omitzero"`
}

ExtractResult represents a successful content extraction.

type Format

type Format string

Format represents the output format for extracted content.

const (
	FormatMarkdown Format = "markdown"
	FormatText     Format = "text"
)

type IncludeAnswer

type IncludeAnswer string

IncludeAnswer controls the LLM-generated answer in search results.

const (
	IncludeAnswerBasic    IncludeAnswer = "basic"
	IncludeAnswerAdvanced IncludeAnswer = "advanced"
)

type IncludeRawContent

type IncludeRawContent string

IncludeRawContent controls cleaned content format in search results.

const (
	IncludeRawContentText     IncludeRawContent = "text"
	IncludeRawContentMarkdown IncludeRawContent = "markdown"
)

type Option

type Option func(*Client)

Option configures the Client.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets a custom API base URL.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom HTTP client.

type SearchDepth

type SearchDepth string

SearchDepth controls the depth of the search.

const (
	SearchDepthBasic     SearchDepth = "basic"
	SearchDepthAdvanced  SearchDepth = "advanced"
	SearchDepthFast      SearchDepth = "fast"
	SearchDepthUltraFast SearchDepth = "ultra-fast"
)

type SearchParams

type SearchParams struct {
	Query             string             `json:"query"`
	SearchDepth       SearchDepth        `json:"search_depth,omitzero"`
	Topic             Topic              `json:"topic,omitzero"`
	TimeRange         TimeRange          `json:"time_range,omitzero"`
	StartDate         string             `json:"start_date,omitzero"`
	EndDate           string             `json:"end_date,omitzero"`
	MaxResults        uint64             `json:"max_results,omitzero"`
	ChunksPerSource   uint64             `json:"chunks_per_source,omitzero"`
	IncludeDomains    []string           `json:"include_domains,omitzero"`
	ExcludeDomains    []string           `json:"exclude_domains,omitzero"`
	IncludeAnswer     *IncludeAnswer     `json:"include_answer,omitzero"`
	IncludeRawContent *IncludeRawContent `json:"include_raw_content,omitzero"`
	IncludeFavicon    *bool              `json:"include_favicon,omitzero"`
	Country           string             `json:"country,omitzero"`
	AutoParameters    *bool              `json:"auto_parameters,omitzero"`
	ExactMatch        *bool              `json:"exact_match,omitzero"`
	IncludeUsage      *bool              `json:"include_usage,omitzero"`
}

SearchParams is the request body for POST /search. Zero-value fields are omitted; the API uses server-side defaults.

type SearchResponse

type SearchResponse struct {
	Query        string         `json:"query"`
	Answer       string         `json:"answer,omitzero"`
	ResponseTime float64        `json:"response_time"`
	Results      []SearchResult `json:"results"`
	Usage        *Usage         `json:"usage,omitzero"`
	RequestID    string         `json:"request_id,omitzero"`
}

SearchResponse is the response from POST /search.

type SearchResult

type SearchResult struct {
	Title         string  `json:"title"`
	URL           string  `json:"url"`
	Content       string  `json:"content"`
	RawContent    string  `json:"raw_content,omitzero"`
	Score         float64 `json:"score"`
	PublishedDate string  `json:"published_date,omitzero"`
	Favicon       string  `json:"favicon,omitzero"`
}

SearchResult represents a single search result.

type TimeRange

type TimeRange string

TimeRange represents the time range filter for search results.

const (
	TimeRangeDay   TimeRange = "day"
	TimeRangeWeek  TimeRange = "week"
	TimeRangeMonth TimeRange = "month"
	TimeRangeYear  TimeRange = "year"
)

type Topic

type Topic string

Topic represents the topic category for search.

const (
	TopicGeneral Topic = "general"
	TopicNews    Topic = "news"
	TopicFinance Topic = "finance"
)

type Usage

type Usage struct {
	Credits uint64 `json:"credits"`
}

Usage represents credit usage information.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL