Documentation
¶
Overview ¶
Package perplexity provides a Go client for the Perplexity API. Since there is no official Perplexity Go SDK, this package implements the HTTP client from scratch following their API documentation.
Perplexity offers two main APIs:
- Search API: Delivers ranked web search results with advanced filtering
- Grounded LLM API: AI-powered chat completions with web-grounded knowledge
Reference: https://docs.perplexity.ai/getting-started/overview
Index ¶
Constants ¶
const BaseURL = "https://api.perplexity.ai"
BaseURL is the Perplexity API base URL
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type APIError ¶
APIError represents an API error
func (*APIError) IsRateLimitError ¶
IsRateLimitError returns true if this is a rate limit error
type ChatCompletionRequest ¶
type ChatCompletionRequest struct {
// Model is the name of the model to use (required)
// Available models: sonar, sonar-pro, sonar-reasoning, sonar-reasoning-pro
Model string `json:"model"`
// Messages is the list of messages in the conversation (required)
Messages []Message `json:"messages"`
// MaxTokens is the maximum number of tokens to generate
MaxTokens int `json:"max_tokens,omitempty"`
// Temperature controls randomness (0-2, default: 0.2)
Temperature *float64 `json:"temperature,omitempty"`
// TopP controls nucleus sampling (0-1, default: 0.9)
TopP *float64 `json:"top_p,omitempty"`
// TopK controls top-k sampling (default: 0, disabled)
TopK int `json:"top_k,omitempty"`
// Stream enables streaming responses
Stream bool `json:"stream,omitempty"`
// PresencePenalty penalizes new tokens based on presence in text (-2 to 2)
PresencePenalty float64 `json:"presence_penalty,omitempty"`
// FrequencyPenalty penalizes new tokens based on frequency in text (-2 to 2)
FrequencyPenalty float64 `json:"frequency_penalty,omitempty"`
// SearchDomainFilter limits search to specific domains
SearchDomainFilter []string `json:"search_domain_filter,omitempty"`
// ReturnImages enables image return in responses
ReturnImages bool `json:"return_images,omitempty"`
// ReturnRelatedQuestions returns related follow-up questions
ReturnRelatedQuestions bool `json:"return_related_questions,omitempty"`
// SearchRecencyFilter filters search by recency: "hour", "day", "week", "month"
SearchRecencyFilter string `json:"search_recency_filter,omitempty"`
// ResponseFormat enforces a structured output format (e.g. JSON Schema)
ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
}
ChatCompletionRequest represents a request to the chat completions endpoint
type ChatCompletionResponse ¶
type ChatCompletionResponse struct {
// ID is the unique identifier for the completion
ID string `json:"id"`
// Model is the model that was used
Model string `json:"model"`
// Object is always "chat.completion"
Object string `json:"object"`
// Created is the Unix timestamp of creation
Created int64 `json:"created"`
// Choices contains the completion choices
Choices []Choice `json:"choices"`
// Usage contains token usage information
Usage Usage `json:"usage"`
// Citations contains URLs used for the response (web-grounded responses)
Citations []string `json:"citations,omitempty"`
// Images contains images returned if return_images was true
Images []ImageResult `json:"images,omitempty"`
// RelatedQuestions contains follow-up questions if requested
RelatedQuestions []string `json:"related_questions,omitempty"`
}
ChatCompletionResponse represents the response from chat completions
type Choice ¶
type Choice struct {
// Index is the index of this choice
Index int `json:"index"`
// FinishReason indicates why the model stopped generating
FinishReason string `json:"finish_reason"`
// Message is the assistant's response message
Message Message `json:"message"`
// Delta is used for streaming responses
Delta *Message `json:"delta,omitempty"`
}
Choice represents a single completion choice
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a Perplexity API client
func NewClient ¶
func NewClient(config ClientConfig) (*Client, error)
NewClient creates a new Perplexity API client
func (*Client) ChatCompletions ¶
func (c *Client) ChatCompletions(ctx context.Context, req ChatCompletionRequest) (*ChatCompletionResponse, error)
ChatCompletions sends a chat completion request to the Perplexity API
func (*Client) Search ¶
func (c *Client) Search(ctx context.Context, req SearchRequest) (*SearchResponse, error)
Search performs a web search using Perplexity's Search API
type ClientConfig ¶
type ClientConfig struct {
// APIKey is the Perplexity API key (required)
APIKey string
// BaseURL is the API base URL (defaults to https://api.perplexity.ai)
BaseURL string
// Timeout is the HTTP client timeout (default: 30s)
Timeout time.Duration
}
ClientConfig contains configuration for the Perplexity client
type ErrorDetail ¶
type ErrorDetail struct {
Message string `json:"message"`
Type string `json:"type"`
Code string `json:"code,omitempty"`
}
ErrorDetail contains error details
type ErrorResponse ¶
type ErrorResponse struct {
Error ErrorDetail `json:"error"`
}
ErrorResponse represents an API error response
type ImageResult ¶
type ImageResult struct {
// URL is the image URL
URL string `json:"url"`
// SourceURL is the page where the image was found
SourceURL string `json:"source_url,omitempty"`
// Alt is the image alt text
Alt string `json:"alt,omitempty"`
// Width is the image width
Width int `json:"width,omitempty"`
// Height is the image height
Height int `json:"height,omitempty"`
}
ImageResult represents an image search result
type JSONSchemaSpec ¶ added in v1.1.0
type JSONSchemaSpec struct {
// Schema is a valid JSON Schema object describing the expected response shape
Schema map[string]any `json:"schema"`
}
JSONSchemaSpec wraps the JSON Schema object for structured outputs
type Message ¶
type Message struct {
Role string `json:"role"` // "system", "user", or "assistant"
Content string `json:"content"` // The message content
}
Message represents a chat message
type ResponseFormat ¶ added in v1.1.0
type ResponseFormat struct {
// Type is the format type; currently only "json_schema" is supported
Type string `json:"type"`
// JSONSchema holds the schema when Type is "json_schema"
JSONSchema *JSONSchemaSpec `json:"json_schema,omitempty"`
}
ResponseFormat specifies the desired output format for a chat completion
type SearchRequest ¶
type SearchRequest struct {
// Query is the search query string (required)
Query string `json:"query"`
// RecencyFilter filters results by time: "hour", "day", "week", "month", "year"
RecencyFilter string `json:"recency_filter,omitempty"`
// DomainFilter limits search to specific domains
DomainFilter []string `json:"domain_filter,omitempty"`
// CountryCode filters results by country (e.g., "us", "gb")
CountryCode string `json:"country_code,omitempty"`
// LanguageCode filters results by language (e.g., "en", "fr")
LanguageCode string `json:"language_code,omitempty"`
// ReturnImages includes image results
ReturnImages bool `json:"return_images,omitempty"`
// SafeSearch enables safe search mode
SafeSearch bool `json:"safe_search,omitempty"`
}
SearchRequest represents a request to the Search API
type SearchResponse ¶
type SearchResponse struct {
// Results contains the search results
Results []SearchResult `json:"results"`
// Images contains image results if requested
Images []ImageResult `json:"images,omitempty"`
}
SearchResponse represents the response from the Search API
type SearchResult ¶
type SearchResult struct {
// Title is the page title
Title string `json:"title"`
// URL is the result URL
URL string `json:"url"`
// Snippet is the text snippet from the page
Snippet string `json:"snippet,omitempty"`
// DatePublished is when the content was published
DatePublished string `json:"date_published,omitempty"`
// Author is the content author if available
Author string `json:"author,omitempty"`
}
SearchResult represents a single search result
type Usage ¶
type Usage struct {
// PromptTokens is the number of tokens in the prompt
PromptTokens int `json:"prompt_tokens"`
// CompletionTokens is the number of tokens in the completion
CompletionTokens int `json:"completion_tokens"`
// TotalTokens is the total number of tokens used
TotalTokens int `json:"total_tokens"`
}
Usage contains token usage information