Documentation
¶
Overview ¶
Package perplexity provides a Go client for interacting with the Perplexity AI API. It supports both synchronous and streaming (SSE) completion requests.
Index ¶
- Constants
- Variables
- func EstimateRemainingTime(job *AsyncJobResponse) time.Duration
- func IsAsyncJobComplete(status AsyncJobStatus) bool
- func IsAsyncJobError(err error) bool
- func IsAsyncJobValidationError(err error) bool
- func IsRetryableAsyncError(err error) bool
- func ParseAsyncJobErrorResponse(statusCode int, data []byte, jobID string) error
- func ParseErrorMessage(data []byte) error
- func ValidateAsyncJobRequest(req *AsyncJobRequest) error
- type AsyncJobAPIError
- type AsyncJobError
- type AsyncJobListResponse
- type AsyncJobMonitor
- func (m *AsyncJobMonitor) GetElapsedTime() time.Duration
- func (m *AsyncJobMonitor) GetJobID() string
- func (m *AsyncJobMonitor) GetLastPollTime() time.Time
- func (m *AsyncJobMonitor) Poll(ctx context.Context) (*AsyncJobResponse, error)
- func (m *AsyncJobMonitor) Wait(ctx context.Context) (*AsyncJobResponse, error)
- func (m *AsyncJobMonitor) WaitWithProgress(ctx context.Context, progressChan chan<- *AsyncJobResponse) (*AsyncJobResponse, error)
- type AsyncJobProgress
- type AsyncJobRequest
- type AsyncJobRequestOption
- func WithAsyncFrequencyPenalty(penalty float64) AsyncJobRequestOption
- func WithAsyncImageDomainFilter(domains []string) AsyncJobRequestOption
- func WithAsyncImageFormatFilter(formats []string) AsyncJobRequestOption
- func WithAsyncLastUpdatedAfter(date string) AsyncJobRequestOption
- func WithAsyncLastUpdatedBefore(date string) AsyncJobRequestOption
- func WithAsyncMaxTokens(maxTokens int) AsyncJobRequestOption
- func WithAsyncMessages(messages []Message) AsyncJobRequestOption
- func WithAsyncMessagesObject(messages Messages) AsyncJobRequestOption
- func WithAsyncMultimodalMessages(messages []MultimodalMessage) AsyncJobRequestOption
- func WithAsyncPresencePenalty(penalty float64) AsyncJobRequestOption
- func WithAsyncPublishedAfter(date string) AsyncJobRequestOption
- func WithAsyncPublishedBefore(date string) AsyncJobRequestOption
- func WithAsyncReasoningEffort(effort string) AsyncJobRequestOption
- func WithAsyncSearchDomain(domain string) AsyncJobRequestOption
- func WithAsyncSearchDomainFilter(domains []string) AsyncJobRequestOption
- func WithAsyncSearchMode(mode string) AsyncJobRequestOption
- func WithAsyncTemperature(temperature float64) AsyncJobRequestOption
- func WithAsyncTopK(topK int) AsyncJobRequestOption
- func WithAsyncTopP(topP float64) AsyncJobRequestOption
- func WithAsyncWebSearchOptions(options *WebSearchOptions) AsyncJobRequestOption
- type AsyncJobRequestValidator
- type AsyncJobResponse
- type AsyncJobStatus
- type AsyncJobTimeoutError
- type AsyncJobValidationError
- type AsyncPollingOptions
- type Choice
- type Client
- func (s *Client) CreateAsyncJob(req *AsyncJobRequest) (*AsyncJobResponse, error)
- func (s *Client) CreateAsyncJobWithContext(ctx context.Context, req *AsyncJobRequest) (*AsyncJobResponse, error)
- func (s *Client) GetAsyncJob(jobID string) (*AsyncJobResponse, error)
- func (s *Client) GetAsyncJobWithContext(ctx context.Context, jobID string) (*AsyncJobResponse, error)
- func (s *Client) GetHTTPTimeout() time.Duration
- func (s *Client) ListAsyncJobs(limit, offset int) (*AsyncJobListResponse, error)
- func (s *Client) ListAsyncJobsWithContext(ctx context.Context, limit, offset int) (*AsyncJobListResponse, error)
- func (s *Client) NewAsyncJobMonitor(jobID string, opts *AsyncPollingOptions) *AsyncJobMonitor
- func (s *Client) SendCompletionRequest(req *CompletionRequest) (*CompletionResponse, error)
- func (s *Client) SendCompletionRequestWithContext(ctx context.Context, req *CompletionRequest) (*CompletionResponse, error)
- func (s *Client) SendSSEHTTPRequest(wg *sync.WaitGroup, req *CompletionRequest, ...) errordeprecated
- func (s *Client) SendSSEHTTPRequestWithContext(ctx context.Context, wg *sync.WaitGroup, req *CompletionRequest, ...) errordeprecated
- func (s *Client) SendSearchRequest(req *SearchRequest) (*SearchResponse, error)
- func (s *Client) SendSearchRequestWithContext(ctx context.Context, req *SearchRequest) (*SearchResponse, error)
- func (s *Client) SetAsyncEndpoint(endpoint string)
- func (s *Client) SetEndpoint(endpoint string)
- func (s *Client) SetHTTPClient(httpClient *http.Client)
- func (s *Client) SetHTTPTimeout(timeout time.Duration)
- func (s *Client) SetSearchEndpoint(endpoint string)
- func (s *Client) StreamCompletion(req *CompletionRequest, responseChannel chan<- CompletionResponse) error
- func (s *Client) StreamCompletionWithContext(ctx context.Context, req *CompletionRequest, ...) error
- func (s *Client) WaitForAsyncJob(jobID string, opts *AsyncPollingOptions) (*AsyncJobResponse, error)
- func (s *Client) WaitForAsyncJobWithContext(ctx context.Context, jobID string, opts *AsyncPollingOptions) (*AsyncJobResponse, error)
- func (s *Client) WaitForAsyncJobWithProgress(ctx context.Context, jobID string, opts *AsyncPollingOptions, ...) (*AsyncJobResponse, error)
- type CompletionRequest
- func (r *CompletionRequest) HasImages() bool
- func (r *CompletionRequest) IsMultimodal() bool
- func (r *CompletionRequest) MarshalJSON() ([]byte, error)
- func (r *CompletionRequest) Validate() error
- func (r *CompletionRequest) ValidateSearchDomain() error
- func (r *CompletionRequest) ValidateSearchDomainFilter() error
- func (r *CompletionRequest) ValidateSearchRecencyFilter() error
- func (r *CompletionRequest) ValidateStructuredOutput() error
- type CompletionRequestOption
- func WithDefaultModel() CompletionRequestOption
- func WithFrequencyPenalty(frequencyPenalty float64) CompletionRequestOption
- func WithImageDomainFilter(domains []string) CompletionRequestOption
- func WithImageFormatFilter(formats []string) CompletionRequestOption
- func WithImageFromFile(_ string) CompletionRequestOption
- func WithImageFromURL(_ string) CompletionRequestOption
- func WithJSONSchemaResponseFormat(schema any) CompletionRequestOption
- func WithLanguagePreference(lang string) CompletionRequestOption
- func WithLastUpdatedAfterFilter(date time.Time) CompletionRequestOption
- func WithLastUpdatedBeforeFilter(date time.Time) CompletionRequestOption
- func WithLatestUpdated(date time.Time) CompletionRequestOption
- func WithMaxTokens(maxTokens int) CompletionRequestOption
- func WithMessages(msg []Message) CompletionRequestOption
- func WithMessagesFromMessages(messages *Messages) CompletionRequestOption
- func WithModel(model string) CompletionRequestOption
- func WithMultimodalMessages(messages []MultimodalMessage) CompletionRequestOption
- func WithPresencePenalty(presencePenalty float64) CompletionRequestOption
- func WithPublishedAfter(date time.Time) CompletionRequestOption
- func WithPublishedBefore(date time.Time) CompletionRequestOption
- func WithReasoningEffort(effort string) CompletionRequestOption
- func WithRegexResponseFormat(regex string) CompletionRequestOption
- func WithResponseFormat(format *ResponseFormat) CompletionRequestOption
- func WithReturnImages(returnImages bool) CompletionRequestOption
- func WithReturnRelatedQuestions(returnRelatedQuestions bool) CompletionRequestOption
- func WithSearchAfterDateFilter(date time.Time) CompletionRequestOptiondeprecated
- func WithSearchBeforeDateFilter(date time.Time) CompletionRequestOptiondeprecated
- func WithSearchContextSize(size string) CompletionRequestOption
- func WithSearchDomain(searchDomain string) CompletionRequestOption
- func WithSearchDomainFilter(searchDomainFilter []string) CompletionRequestOption
- func WithSearchMode(searchMode string) CompletionRequestOption
- func WithSearchRecencyFilter(searchRecencyFilter string) CompletionRequestOption
- func WithStream(stream bool) CompletionRequestOption
- func WithTemperature(temperature float64) CompletionRequestOption
- func WithTopK(topK int) CompletionRequestOption
- func WithTopP(topP float64) CompletionRequestOption
- func WithUserLocation(latitude, longitude float64, country string) CompletionRequestOption
- func WithWebSearchOptions(opts *WebSearchOptions) CompletionRequestOption
- type CompletionResponse
- func (r *CompletionResponse) GetCitations() []stringdeprecated
- func (r *CompletionResponse) GetImages() []Image
- func (r *CompletionResponse) GetLastContent() string
- func (r *CompletionResponse) GetPostThinkingContent() string
- func (r *CompletionResponse) GetRelatedQuestions() []string
- func (r *CompletionResponse) GetSearchResults() []SearchResult
- func (r *CompletionResponse) String() string
- type Content
- type ContentType
- type Cost
- type FileProcessor
- func (p *FileProcessor) CheckFileURLAccessibility(ctx context.Context, fileURL string) error
- func (p *FileProcessor) EncodeFileFromPath(filePath string) (string, string, error)
- func (p *FileProcessor) ValidateFileFormat(format string) error
- func (p *FileProcessor) ValidateFileSize(size int64) error
- func (p *FileProcessor) ValidateFileURL(fileURL string) error
- type FileURL
- type Image
- type ImageProcessor
- func (p *ImageProcessor) CheckImageURLAccessibility(ctx context.Context, imageURL string) error
- func (p *ImageProcessor) EncodeImageFromFile(filepath string) (string, error)
- func (p *ImageProcessor) EstimateTokenUsage(width, height int) int
- func (p *ImageProcessor) ValidateImageFormat(format string) error
- func (p *ImageProcessor) ValidateImageSize(size int64) error
- func (p *ImageProcessor) ValidateImageURL(imageURL string) error
- type ImageURL
- type JSONSchemaConfig
- type Message
- type Messages
- func (m *Messages) AddAgentMessage(content string) error
- func (m *Messages) AddMultimodalAgentMessage(contents []Content) error
- func (m *Messages) AddMultimodalUserMessage(contents []Content) error
- func (m *Messages) AddUserMessage(content string) error
- func (m *Messages) AddUserMessageWithFile(text, fileURL, fileName string) error
- func (m *Messages) AddUserMessageWithFileFromPath(text, filepath string) error
- func (m *Messages) AddUserMessageWithImage(text, imageURL string) error
- func (m *Messages) AddUserMessageWithImageFile(text, filepath string) error
- func (m *Messages) GetMessages() []Message
- func (m *Messages) GetMultimodalMessages() []MultimodalMessage
- func (m *Messages) GetSystemMessage() string
- func (m *Messages) HasFiles() bool
- func (m *Messages) HasImages() bool
- func (m *Messages) IsMultimodal() bool
- type MessagesOption
- type MultimodalMessage
- type RegexConfig
- type RequestValidator
- type ResponseError
- type ResponseFormat
- type SearchImageItem
- type SearchRequest
- type SearchRequestOption
- func WithSearchCountry(country string) SearchRequestOption
- func WithSearchDomains(domains []string) SearchRequestOption
- func WithSearchLanguagePreference(lang string) SearchRequestOption
- func WithSearchMaxResults(maxResults int) SearchRequestOption
- func WithSearchMaxTokens(maxTokens int) SearchRequestOption
- func WithSearchReturnImages(include bool) SearchRequestOption
- func WithSearchReturnSnippets(include bool) SearchRequestOption
- type SearchRequestValidator
- type SearchResponse
- type SearchResult
- type SearchResultItem
- type Usage
- type UserLocation
- type WebSearchOptions
Constants ¶
const ( // AsyncEndpoint is the base endpoint for async operations. AsyncEndpoint = "https://api.perplexity.ai/async/chat/completions" // AsyncJobTTL is the time-to-live for async jobs (7 days). AsyncJobTTL = 7 * 24 * time.Hour )
Async API constants and types.
const ( // MaxDomainFilterCount is the maximum number of domains allowed in filters. MaxDomainFilterCount = 10 // MaxImageFormatFilterCount is the maximum number of image formats allowed. MaxImageFormatFilterCount = 10 )
Constants for async request validation.
const ( // DefaultInitialPollingInterval is the default initial polling interval. DefaultInitialPollingInterval = 2 * time.Second // DefaultMaxPollingInterval is the default maximum polling interval. DefaultMaxPollingInterval = 30 * time.Second // DefaultBackoffMultiplier is the default exponential backoff multiplier. DefaultBackoffMultiplier = 1.5 // DefaultMaxWaitTime is the default maximum wait time for job completion. DefaultMaxWaitTime = 30 * time.Minute // JitterPercentage is the percentage of jitter to apply to polling intervals. JitterPercentage = 0.1 // JitterOffset centers the jitter around zero. JitterOffset = 0.5 )
Constants for async polling configuration.
const ( // MaxFileSizeBytes is the maximum allowed file size (50MB) according to Perplexity API. MaxFileSizeBytes = 50 * 1024 * 1024 // HTTPFileTimeoutSeconds is the timeout for HTTP requests to check file URL accessibility. HTTPFileTimeoutSeconds = 10 )
File processing constants and errors.
const ( // MaxImageSizeBytes is the maximum allowed image size (50MB) according to Perplexity API. MaxImageSizeBytes = 50 * 1024 * 1024 // TokenEstimationDivisor is used to estimate token usage from image pixels // Based on empirical measurements of Perplexity API token consumption. TokenEstimationDivisor = 750 // HTTPTimeoutSeconds is the timeout for HTTP requests to check image URL accessibility. HTTPTimeoutSeconds = 10 )
Image processing constants and errors.
const ( // DefaultTemperature is the default temperature value for text generation (0.0 to 1.0). DefaultTemperature = 0.2 // DefaultTopP is the default top-p sampling parameter (0.0 to 1.0). DefaultTopP = 0.9 // DefaultTopK is the default top-k sampling parameter (0 to 2048). DefaultTopK = 0 // DefaultMaxTokens is the default maximum number of tokens to generate. DefaultMaxTokens = 4000 // DefaultPresencePenalty is the default presence penalty value (-2.0 to 2.0). DefaultPresencePenalty = 0.0 // DefaultFrequencyPenalty is the default frequency penalty value (0.0 to 1.0). DefaultFrequencyPenalty = 1.0 // DefaultSearchRecencyFilter is the default search recency filter value (empty = omitted from the request). DefaultSearchRecencyFilter = "" // DefaultSearchMode is the default search mode value. DefaultSearchMode = "web" // ReasoningEffortLow provides faster, simpler answers with reduced computational effort for sonar-deep-research model. ReasoningEffortLow = "low" // ReasoningEffortMedium provides balanced approach for sonar-deep-research model. ReasoningEffortMedium = "medium" // ReasoningEffortHigh provides deeper, more thorough responses with increased computational effort for sonar-deep-research model. ReasoningEffortHigh = "high" // DefaultReasoningEffort is the default reasoning effort value for sonar-deep-research model. DefaultReasoningEffort = ReasoningEffortMedium )
const AsyncJobEndpoint = "https://api.perplexity.ai/async/chat/completions"
AsyncJobEndpoint is the base endpoint for async operations.
const DefaultEndpoint = "https://api.perplexity.ai/chat/completions"
DefaultEndpoint is the default endpoint for the Perplexity API.
const DefaultModel = "sonar"
DefaultModel is the default model for the Perplexity API.
const DefaultTimeout = 30 * time.Second
DefaultTimeout is the default timeout for the HTTP client.
const (
// MaxLengthOfDomainFilter is the maximum number of domains allowed in the search domain filter.
MaxLengthOfDomainFilter = 10
)
const ModelSonarDeepResearch = "sonar-deep-research"
ModelSonarDeepResearch is the sonar-deep-research model that supports reasoning_effort parameter.
const SearchEndpoint = "https://api.perplexity.ai/search"
SearchEndpoint is the endpoint for the Perplexity Search API.
Variables ¶
var ( // ErrNilRequest is returned when a nil request is provided. ErrNilRequest = errors.New("request must not be nil") ErrUnauthorized = errors.New("unauthorized: check your API key") // ErrNilResponseChannel is returned when a nil response channel is provided. ErrNilResponseChannel = errors.New("response channel must not be nil") // ErrNilWaitGroup is returned when a nil wait group is provided. ErrNilWaitGroup = errors.New("wait group must not be nil") )
Error definitions.
var ( // ErrAsyncModelRequired is returned when a non-sonar-deep-research model is used for async. ErrAsyncModelRequired = errors.New("async jobs require sonar-deep-research model") // ErrAsyncJobExpired is returned when an async job has expired. ErrAsyncJobExpired = errors.New("async job has expired") // ErrAsyncJobFailed is returned when an async job has failed. ErrAsyncJobFailed = errors.New("async job failed") // ErrAsyncJobNotFound is returned when an async job ID is not found. ErrAsyncJobNotFound = errors.New("async job not found") // ErrAsyncJobInvalidStatus is returned when an async job has an unexpected status. ErrAsyncJobInvalidStatus = errors.New("async job has invalid status") // ErrAsyncPollingTimeout is returned when polling times out. ErrAsyncPollingTimeout = errors.New("async job polling timeout") // ErrJobCompletedNoResult is returned when job is completed but no result is available. ErrJobCompletedNoResult = errors.New("job completed but no result available") // ErrJobStillProcessing is returned when job is still processing. ErrJobStillProcessing = errors.New("job is still processing") // ErrUnsupportedTimestampFormat is returned when timestamp format is unsupported. ErrUnsupportedTimestampFormat = errors.New("unsupported timestamp format") // ErrJobIDEmpty is returned when job ID is empty. ErrJobIDEmpty = errors.New("job ID cannot be empty") // ErrJobNotComplete is a sentinel error for when job is not yet complete. ErrJobNotComplete = errors.New("job not complete") )
Error definitions for async operations.
var ( // ErrRequestNil is returned when request is nil. ErrRequestNil = errors.New("request cannot be nil") // ErrMessagesRequired is returned when no messages are provided. ErrMessagesRequired = errors.New("at least one message is required") // ErrBothMessageTypes is returned when both regular and multimodal messages are provided. ErrBothMessageTypes = errors.New("cannot specify both messages and multimodal messages") // ErrInvalidReasoningEffort is returned when reasoning effort is invalid. ErrInvalidReasoningEffort = errors.New("reasoning effort must be 'low', 'medium', or 'high'") // ErrInvalidTemperature is returned when temperature is out of range. ErrInvalidTemperature = errors.New("temperature must be between 0 and 2") // ErrInvalidTopP is returned when top_p is out of range. ErrInvalidTopP = errors.New("top_p must be between 0 and 1") // ErrInvalidTopK is returned when top_k is out of range. ErrInvalidTopK = errors.New("top_k must be between 0 and 2048") // ErrInvalidPresencePenalty is returned when presence penalty is out of range. ErrInvalidPresencePenalty = errors.New("presence penalty must be between -2.0 and 2.0") // ErrInvalidFrequencyPenalty is returned when frequency penalty is out of range. ErrInvalidFrequencyPenalty = errors.New("frequency penalty must be between -2.0 and 2.0") // ErrTooManySearchDomains is returned when too many search domains are provided. ErrTooManySearchDomains = errors.New("search domain filter cannot exceed 10 domains") // ErrInvalidSearchMode is returned when search mode is invalid. ErrInvalidSearchMode = errors.New("search mode must be 'academic' or 'web'") // ErrInvalidSearchDomain is returned when search domain is invalid. ErrInvalidSearchDomain = errors.New("search domain must be 'sec'") // ErrTooManyImageDomains is returned when too many image domains are provided. ErrTooManyImageDomains = errors.New("image domain filter cannot exceed 10 domains") // ErrTooManyImageFormats is returned when too many image formats are provided. ErrTooManyImageFormats = errors.New("image format filter cannot exceed 10 formats") // ErrInvalidPublishedAfter is returned when published_after date is invalid. ErrInvalidPublishedAfter = errors.New("invalid published_after date format") // ErrInvalidPublishedBefore is returned when published_before date is invalid. ErrInvalidPublishedBefore = errors.New("invalid published_before date format") // ErrInvalidLastUpdatedAfter is returned when last_updated_after_filter date is invalid. ErrInvalidLastUpdatedAfter = errors.New("invalid last_updated_after_filter date format") // ErrInvalidLastUpdatedBefore is returned when last_updated_before_filter date is invalid. ErrInvalidLastUpdatedBefore = errors.New("invalid last_updated_before_filter date format") // ErrUnsupportedDateFormat is returned when date format is unsupported. ErrUnsupportedDateFormat = errors.New("unsupported date format") )
Static validation errors.
var ( // ErrFileTooLarge is returned when a file exceeds the 50MB size limit. ErrFileTooLarge = errors.New("file size exceeds 50MB limit") // ErrFileFormatNotSupported is returned when a file format is not supported. ErrFileFormatNotSupported = errors.New("file format not supported (use PDF, DOC, DOCX, TXT, or RTF)") // ErrFileURLNotHTTPS is returned when a file URL does not use HTTPS protocol. ErrFileURLNotHTTPS = errors.New("file URL must use HTTPS protocol") // ErrFileNotFound is returned when a file cannot be found. ErrFileNotFound = errors.New("file not found") // ErrFileReadFailed is returned when a file cannot be read. ErrFileReadFailed = errors.New("failed to read file") // ErrFileURLInvalid is returned when a file URL is malformed. ErrFileURLInvalid = errors.New("invalid file URL format") // ErrFileDataURIMalformed is returned when a file data URI is malformed. ErrFileDataURIMalformed = errors.New("invalid file data URI") // ErrFileURLBadStatus is returned when file URL returns a non-2xx status. ErrFileURLBadStatus = errors.New("file URL returned bad status") // ErrInvalidFileContentType is returned when file content type is invalid. ErrInvalidFileContentType = errors.New("invalid file content type") )
Error definitions for file processing.
var ( // ErrImageTooLarge is returned when an image exceeds the 50MB size limit. ErrImageTooLarge = errors.New("image size exceeds 50MB limit") // ErrImageFormatNotSupported is returned when an image format is not supported. ErrImageFormatNotSupported = errors.New("image format not supported (use PNG, JPEG, WEBP, or GIF)") // ErrImageURLNotHTTPS is returned when an image URL does not use HTTPS protocol. ErrImageURLNotHTTPS = errors.New("image URL must use HTTPS protocol") // ErrImageFileNotFound is returned when an image file cannot be found. ErrImageFileNotFound = errors.New("image file not found") // ErrImageReadFailed is returned when an image file cannot be read. ErrImageReadFailed = errors.New("failed to read image file") // ErrImageURLInvalid is returned when an image URL is malformed. ErrImageURLInvalid = errors.New("invalid image URL format") // ErrImageDataURIMalformed is returned when an image data URI is malformed. ErrImageDataURIMalformed = errors.New("invalid image data URI") // ErrImageURLBadStatus is returned when image URL returns a non-2xx status. ErrImageURLBadStatus = errors.New("image URL returned bad status") // ErrInvalidContentType is returned when image content type is invalid. ErrInvalidContentType = errors.New("invalid content type") )
Error definitions for image processing.
var ( // ErrPrevMessageShouldBeAssistant is returned when the previous message is not from the assistant. ErrPrevMessageShouldBeAssistant = errors.New("previous message should be an assistant message") // ErrFirstMessageShouldBeUser is returned when the first message is not from the user. ErrFirstMessageShouldBeUser = errors.New("first message should be a user message") // ErrPrevMessageShouldBeUser is returned when the previous message is not from the user. ErrPrevMessageShouldBeUser = errors.New("previous message should be a user message") // ErrMultimodalContentEmpty is returned when multimodal message content is empty. ErrMultimodalContentEmpty = errors.New("multimodal message content cannot be empty") // ErrMultimodalInvalidContentType is returned when multimodal content has invalid type. ErrMultimodalInvalidContentType = errors.New("invalid content type in multimodal message") )
Error definitions.
var ( // ErrSearchRecencyFilter is returned when the search recency filter is invalid or incompatible. ErrSearchRecencyFilter = errors.New("search recency filter must be one of month, week, day, hour and is incompatible with images") // ErrRegexAndImages is returned when both regex response format and images are requested, which are incompatible. ErrRegexAndImages = errors.New("regex and images are not compatible") // ErrRegexAndStream is returned when both regex response format and streaming are requested, which are incompatible. ErrRegexAndStream = errors.New("regex and stream are not compatible") // ErrValidationFailed is returned when struct validation fails. ErrValidationFailed = errors.New("validation failed") // ErrStructuredOutputFormatMismatch is returned when the response format configuration doesn't match the type. ErrStructuredOutputFormatMismatch = errors.New("response format type must match the provided configuration (json_schema or regex)") // ErrStructuredOutputRegexAndImages is returned when regex and images are used together. ErrStructuredOutputRegexAndImages = errors.New("regex and images are not compatible") // ErrDomainFilterTooLong is returned when the domain filter exceeds the maximum allowed number of domains. ErrDomainFilterTooLong = errors.New("domain filter must be less than or equal to 10") // ErrDomainFilterEmpty is returned when a domain filter entry is empty. ErrDomainFilterEmpty = errors.New("domain filter entry cannot be empty") // ErrDomainFilterProtocolNotAllowed is returned when a domain filter entry includes a protocol prefix (http:// or https://). ErrDomainFilterProtocolNotAllowed = errors.New("domain filter entry cannot include http:// or https://") // ErrDomainFilterWWWNotAllowed is returned when a domain filter entry includes a www. prefix. ErrDomainFilterWWWNotAllowed = errors.New("domain filter entry cannot include www. prefix") // ErrDomainFilterSubdomainNotAllowed is returned when a domain filter entry includes subdomains. ErrDomainFilterSubdomainNotAllowed = errors.New("domain filter entry cannot include subdomains") // ErrDomainFilterInvalidFormat is returned when a domain filter entry has an invalid format. ErrDomainFilterInvalidFormat = errors.New("domain filter entry must be a valid domain name (e.g., example.com or -gettyimages.com)") // ErrImageFormatFilterTooLong is returned when the image format filter exceeds the maximum allowed number of formats. ErrImageFormatFilterTooLong = errors.New("image format filter must be less than or equal to 10") // ErrImageFormatFilterEmpty is returned when an image format filter entry is empty. ErrImageFormatFilterEmpty = errors.New("image format filter entry cannot be empty") // ErrImageFormatFilterDotPrefixNotAllowed is returned when an image format filter entry starts with a dot. ErrImageFormatFilterDotPrefixNotAllowed = errors.New("image format filter entry cannot start with a dot (e.g., .gif)") // ErrImageFormatFilterMustBeLowercase is returned when an image format filter entry is not in lowercase. ErrImageFormatFilterMustBeLowercase = errors.New("image format filter entry must be in lowercase") // ErrImageFormatFilterInvalidFormat is returned when an image format filter entry has an invalid format. ErrImageFormatFilterInvalidFormat = errors.New("image format filter entry must be a valid format (e.g., jpg, png, webp)") // ErrDateFilterInvalidFormat is returned when a date filter has an invalid format. ErrDateFilterInvalidFormat = errors.New("date filter must be in format %m/%d/%Y (e.g., 3/1/2025, 12/31/2024)") // ErrReasoningEffortModelRequirement is returned when reasoning_effort is used with an unsupported model. ErrReasoningEffortModelRequirement = errors.New("reasoning_effort is only available for the '" + ModelSonarDeepResearch + "' model") // ErrSearchDomainInvalid is returned when search_domain is set to an invalid value. ErrSearchDomainInvalid = errors.New("search_domain must be 'sec' or empty") // ErrImageAndRegexIncompatible is returned when images are used with regex response format. ErrImageAndRegexIncompatible = errors.New("images cannot be used with regex response format") // ErrImageAndDeepResearchIncompatible is returned when images are used with sonar-deep-research model. ErrImageAndDeepResearchIncompatible = errors.New("images cannot be used with sonar-deep-research model") // ErrMultimodalAndRegularMessages is returned when both multimodal and regular messages are present. ErrMultimodalAndRegularMessages = errors.New("cannot use both multimodal messages and regular messages") // ErrMultimodalContentValidation is returned when multimodal content validation fails. ErrMultimodalContentValidation = errors.New("multimodal content validation failed") // ErrTextContentEmpty is returned when text content is empty. ErrTextContentEmpty = errors.New("text content cannot be empty") // ErrImageURLContentNil is returned when image URL content is nil. ErrImageURLContentNil = errors.New("image URL content cannot be nil") // ErrFileURLContentNil is returned when file URL content is nil. ErrFileURLContentNil = errors.New("file URL content cannot be nil") // ErrLanguagePreferenceInvalid is returned when language preference format is invalid. ErrLanguagePreferenceInvalid = errors.New("language_preference must be valid ISO 639 format (e.g., 'en', 'en-US')") )
Error definitions for CompletionRequest validation.
var ( ErrSearchQueryRequired = errors.New("query is required") ErrSearchQueryStringEmpty = errors.New("query string cannot be empty") ErrSearchQueryArrayEmpty = errors.New("query array cannot be empty") ErrSearchQueryInvalidType = errors.New("query must be a string or array of strings") ErrSearchMaxResultsInvalid = errors.New("max_results must be a positive integer") ErrSearchMaxTokensInvalid = errors.New("max_tokens must be a positive integer") ErrSearchCountryInvalid = errors.New("country must be a valid ISO 3166-1 alpha-2 code (2 uppercase letters)") ErrSearchLanguagePreferenceInvalid = errors.New("language_preference must be valid ISO 639 format (e.g., 'en', 'en-US')") ErrSearchDomainFilterEntryEmpty = errors.New("domain filter entry cannot be empty") ErrSearchDomainFilterEntryInvalid = errors.New("domain filter entry is not a valid domain or pattern") ErrSearchQueryArrayElementEmpty = errors.New("query array element cannot be empty") )
Search API validation errors.
var SupportedFileFormats = []string{"pdf", "doc", "docx", "txt", "rtf"}
SupportedFileFormats contains the file formats supported by the Perplexity API.
var SupportedImageFormats = []string{"png", "jpeg", "jpg", "webp", "gif"}
SupportedImageFormats contains the image formats supported by the Perplexity API.
Functions ¶
func EstimateRemainingTime ¶ added in v2.13.0
func EstimateRemainingTime(job *AsyncJobResponse) time.Duration
EstimateRemainingTime estimates remaining time based on job progress. Returns zero if progress information is unavailable.
func IsAsyncJobComplete ¶ added in v2.13.0
func IsAsyncJobComplete(status AsyncJobStatus) bool
IsAsyncJobComplete checks if an async job is in a terminal state.
func IsAsyncJobError ¶ added in v2.13.0
IsAsyncJobError checks if an error is an AsyncJobAPIError.
func IsAsyncJobValidationError ¶ added in v2.13.0
IsAsyncJobValidationError checks if an error is an AsyncJobValidationError.
func IsRetryableAsyncError ¶ added in v2.13.0
IsRetryableAsyncError determines if an async job error is retryable.
func ParseAsyncJobErrorResponse ¶ added in v2.13.0
ParseAsyncJobErrorResponse parses async job specific error responses.
func ParseErrorMessage ¶ added in v2.6.0
ParseErrorMessage unmarshals a []byte representing an API error response and returns the error message.
func ValidateAsyncJobRequest ¶ added in v2.13.0
func ValidateAsyncJobRequest(req *AsyncJobRequest) error
ValidateAsyncJobRequest is a convenience function for validating async job requests.
Types ¶
type AsyncJobAPIError ¶ added in v2.13.0
AsyncJobAPIError represents errors specific to async job operations.
func GetAsyncJobError ¶ added in v2.13.0
func GetAsyncJobError(err error) (*AsyncJobAPIError, bool)
GetAsyncJobError extracts AsyncJobAPIError from an error.
func NewAsyncJobAPIError ¶ added in v2.13.0
func NewAsyncJobAPIError(statusCode int, message, jobID, requestID string) *AsyncJobAPIError
NewAsyncJobAPIError creates a new AsyncJobAPIError.
func (*AsyncJobAPIError) Error ¶ added in v2.13.0
func (e *AsyncJobAPIError) Error() string
Error implements the error interface for AsyncJobAPIError.
type AsyncJobError ¶ added in v2.13.0
type AsyncJobError struct {
JobID string
Status AsyncJobStatus
Message string
}
AsyncJobError represents an error related to async job operations.
func (*AsyncJobError) Error ¶ added in v2.13.0
func (e *AsyncJobError) Error() string
Error implements the error interface.
func (*AsyncJobError) Is ¶ added in v2.13.0
func (e *AsyncJobError) Is(target error) bool
Is checks if the error matches a target error.
type AsyncJobListResponse ¶ added in v2.13.0
type AsyncJobListResponse struct {
// Jobs: List of async jobs.
Jobs []AsyncJobResponse `json:"jobs"`
// Total: Total number of jobs available.
Total int `json:"total"`
// Limit: Maximum number of jobs returned in this response.
Limit int `json:"limit"`
// Offset: Offset used for pagination.
Offset int `json:"offset"`
// HasMore: Whether there are more jobs available.
HasMore bool `json:"has_more"`
}
AsyncJobListResponse represents a list of async jobs.
type AsyncJobMonitor ¶ added in v2.13.0
type AsyncJobMonitor struct {
// contains filtered or unexported fields
}
AsyncJobMonitor provides advanced monitoring capabilities for async jobs.
func (*AsyncJobMonitor) GetElapsedTime ¶ added in v2.13.0
func (m *AsyncJobMonitor) GetElapsedTime() time.Duration
GetElapsedTime returns the time elapsed since monitoring started.
func (*AsyncJobMonitor) GetJobID ¶ added in v2.13.0
func (m *AsyncJobMonitor) GetJobID() string
GetJobID returns the job ID being monitored.
func (*AsyncJobMonitor) GetLastPollTime ¶ added in v2.13.0
func (m *AsyncJobMonitor) GetLastPollTime() time.Time
GetLastPollTime returns the time of the last poll attempt.
func (*AsyncJobMonitor) Poll ¶ added in v2.13.0
func (m *AsyncJobMonitor) Poll(ctx context.Context) (*AsyncJobResponse, error)
Poll performs a single poll operation and returns the current job status.
func (*AsyncJobMonitor) Wait ¶ added in v2.13.0
func (m *AsyncJobMonitor) Wait(ctx context.Context) (*AsyncJobResponse, error)
Wait waits for job completion using the configured polling options.
func (*AsyncJobMonitor) WaitWithProgress ¶ added in v2.13.0
func (m *AsyncJobMonitor) WaitWithProgress(ctx context.Context, progressChan chan<- *AsyncJobResponse) (*AsyncJobResponse, error)
WaitWithProgress waits for job completion and sends progress updates.
type AsyncJobProgress ¶ added in v2.13.0
type AsyncJobProgress struct {
// Stage: Current processing stage.
Stage string `json:"stage,omitempty"`
// Percentage: Completion percentage (0-100).
Percentage *int `json:"percentage,omitempty"`
// EstimatedTimeRemaining: Estimated time until completion.
EstimatedTimeRemaining *time.Duration `json:"estimated_time_remaining,omitempty"`
}
AsyncJobProgress represents progress information for a running async job.
type AsyncJobRequest ¶ added in v2.13.0
type AsyncJobRequest struct {
// Messages: The chat conversation messages.
Messages []Message `json:"messages" validate:"omitempty,dive"`
// MultimodalMessages: For requests containing images or mixed content.
MultimodalMessages []MultimodalMessage `json:"-" validate:"omitempty,dive"`
// Model: Must be "sonar-deep-research" for async operations.
Model string `json:"model" validate:"required,eq=sonar-deep-research"`
// ReasoningEffort: Controls computational effort for sonar-deep-research.
// Options: "low", "medium", "high"
ReasoningEffort string `json:"reasoning_effort,omitempty" validate:"omitempty,oneof=low medium high"`
// MaxTokens: Maximum number of completion tokens.
MaxTokens int `json:"max_tokens" validate:"omitempty,gt=0"`
// Temperature: Randomness in response (0-2).
Temperature float64 `json:"temperature" validate:"omitempty,gte=0,lt=2"`
// TopP: Nucleus sampling threshold (0-1).
TopP float64 `json:"top_p" validate:"omitempty,gt=0,lt=1"`
// TopK: Top-k filtering (0-2048).
TopK int `json:"top_k" validate:"omitempty,gte=0,lte=2048"`
// PresencePenalty: Penalty for new tokens (-2.0 to 2.0).
PresencePenalty float64 `json:"presence_penalty" validate:"omitempty,gte=-2,lte=2"`
// FrequencyPenalty: Penalty for frequent tokens (-2.0 to 2.0).
FrequencyPenalty float64 `json:"frequency_penalty" validate:"omitempty,gte=-2,lte=2"`
// SearchDomainFilter: Domains to include or exclude from search.
SearchDomainFilter []string `json:"search_domain_filter" validate:"omitempty,max=10,dive,required"`
// SearchMode: Search mode ("academic" or "web").
SearchMode string `json:"search_mode,omitempty" validate:"omitempty,oneof=academic web"`
// SearchDomain: Specific domain type ("sec" for SEC documents).
SearchDomain string `json:"search_domain,omitempty" validate:"omitempty,oneof=sec"`
// ImageDomainFilter: Domains to include/exclude for image search.
ImageDomainFilter []string `json:"image_domain_filter,omitempty" validate:"omitempty,max=10,dive,required"`
// ImageFormatFilter: Image formats to include.
ImageFormatFilter []string `json:"image_format_filter,omitempty" validate:"omitempty,max=10,dive,required"`
// PublishedAfter: Filter content published after this date.
PublishedAfter string `json:"published_after,omitempty" validate:"omitempty"`
// PublishedBefore: Filter content published before this date.
PublishedBefore string `json:"published_before,omitempty" validate:"omitempty"`
// LastUpdatedAfterFilter: Filter content last updated after this date.
LastUpdatedAfterFilter string `json:"last_updated_after_filter,omitempty" validate:"omitempty"`
// LastUpdatedBeforeFilter: Filter content last updated before this date.
LastUpdatedBeforeFilter string `json:"last_updated_before_filter,omitempty" validate:"omitempty"`
// WebSearchOptions: Web search context and user location.
WebSearchOptions *WebSearchOptions `json:"web_search_options,omitempty" validate:"omitempty"`
// Stream: Always false for async requests (async doesn't support streaming).
Stream bool `json:"stream"`
}
AsyncJobRequest represents a request to create an async job. This is essentially a CompletionRequest but specifically for async operations.
func DefaultAsyncJobRequest ¶ added in v2.13.0
func DefaultAsyncJobRequest() *AsyncJobRequest
DefaultAsyncJobRequest creates a new AsyncJobRequest with default values.
func NewAsyncJobRequest ¶ added in v2.13.0
func NewAsyncJobRequest(opts ...AsyncJobRequestOption) *AsyncJobRequest
NewAsyncJobRequest creates a new AsyncJobRequest with functional options.
func (*AsyncJobRequest) HasImages ¶ added in v2.13.0
func (r *AsyncJobRequest) HasImages() bool
HasImages returns true if any of the messages contain images.
func (*AsyncJobRequest) IsMultimodal ¶ added in v2.13.0
func (r *AsyncJobRequest) IsMultimodal() bool
IsMultimodal returns true if the request contains multimodal messages.
func (*AsyncJobRequest) MarshalJSON ¶ added in v2.13.0
func (r *AsyncJobRequest) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for AsyncJobRequest. The async API requires the request to be wrapped in a "request" field.
type AsyncJobRequestOption ¶ added in v2.13.0
type AsyncJobRequestOption func(*AsyncJobRequest)
AsyncJobRequestOption is a functional option for configuring AsyncJobRequest.
func WithAsyncFrequencyPenalty ¶ added in v2.13.0
func WithAsyncFrequencyPenalty(penalty float64) AsyncJobRequestOption
WithAsyncFrequencyPenalty sets the frequency penalty.
func WithAsyncImageDomainFilter ¶ added in v2.13.0
func WithAsyncImageDomainFilter(domains []string) AsyncJobRequestOption
WithAsyncImageDomainFilter sets the image domain filter.
func WithAsyncImageFormatFilter ¶ added in v2.13.0
func WithAsyncImageFormatFilter(formats []string) AsyncJobRequestOption
WithAsyncImageFormatFilter sets the image format filter.
func WithAsyncLastUpdatedAfter ¶ added in v2.13.0
func WithAsyncLastUpdatedAfter(date string) AsyncJobRequestOption
WithAsyncLastUpdatedAfter sets the last updated after filter.
func WithAsyncLastUpdatedBefore ¶ added in v2.13.0
func WithAsyncLastUpdatedBefore(date string) AsyncJobRequestOption
WithAsyncLastUpdatedBefore sets the last updated before filter.
func WithAsyncMaxTokens ¶ added in v2.13.0
func WithAsyncMaxTokens(maxTokens int) AsyncJobRequestOption
WithAsyncMaxTokens sets the maximum number of tokens.
func WithAsyncMessages ¶ added in v2.13.0
func WithAsyncMessages(messages []Message) AsyncJobRequestOption
WithAsyncMessages sets the messages for the async request.
func WithAsyncMessagesObject ¶ added in v2.13.0
func WithAsyncMessagesObject(messages Messages) AsyncJobRequestOption
WithAsyncMessagesObject sets messages from a Messages object.
func WithAsyncMultimodalMessages ¶ added in v2.13.0
func WithAsyncMultimodalMessages(messages []MultimodalMessage) AsyncJobRequestOption
WithAsyncMultimodalMessages sets the multimodal messages for the async request.
func WithAsyncPresencePenalty ¶ added in v2.13.0
func WithAsyncPresencePenalty(penalty float64) AsyncJobRequestOption
WithAsyncPresencePenalty sets the presence penalty.
func WithAsyncPublishedAfter ¶ added in v2.13.0
func WithAsyncPublishedAfter(date string) AsyncJobRequestOption
WithAsyncPublishedAfter sets the published after filter.
func WithAsyncPublishedBefore ¶ added in v2.13.0
func WithAsyncPublishedBefore(date string) AsyncJobRequestOption
WithAsyncPublishedBefore sets the published before filter.
func WithAsyncReasoningEffort ¶ added in v2.13.0
func WithAsyncReasoningEffort(effort string) AsyncJobRequestOption
WithAsyncReasoningEffort sets the reasoning effort level.
func WithAsyncSearchDomain ¶ added in v2.13.0
func WithAsyncSearchDomain(domain string) AsyncJobRequestOption
WithAsyncSearchDomain sets the search domain.
func WithAsyncSearchDomainFilter ¶ added in v2.13.0
func WithAsyncSearchDomainFilter(domains []string) AsyncJobRequestOption
WithAsyncSearchDomainFilter sets the search domain filter.
func WithAsyncSearchMode ¶ added in v2.13.0
func WithAsyncSearchMode(mode string) AsyncJobRequestOption
WithAsyncSearchMode sets the search mode.
func WithAsyncTemperature ¶ added in v2.13.0
func WithAsyncTemperature(temperature float64) AsyncJobRequestOption
WithAsyncTemperature sets the temperature parameter.
func WithAsyncTopK ¶ added in v2.13.0
func WithAsyncTopK(topK int) AsyncJobRequestOption
WithAsyncTopK sets the top-k parameter.
func WithAsyncTopP ¶ added in v2.13.0
func WithAsyncTopP(topP float64) AsyncJobRequestOption
WithAsyncTopP sets the top-p parameter.
func WithAsyncWebSearchOptions ¶ added in v2.13.0
func WithAsyncWebSearchOptions(options *WebSearchOptions) AsyncJobRequestOption
WithAsyncWebSearchOptions sets the web search options.
type AsyncJobRequestValidator ¶ added in v2.13.0
type AsyncJobRequestValidator struct{}
AsyncJobRequestValidator provides validation for AsyncJobRequest.
func NewAsyncJobRequestValidator ¶ added in v2.13.0
func NewAsyncJobRequestValidator() *AsyncJobRequestValidator
NewAsyncJobRequestValidator creates a new request validator.
func (*AsyncJobRequestValidator) Validate ¶ added in v2.13.0
func (v *AsyncJobRequestValidator) Validate(req *AsyncJobRequest) error
Validate validates an AsyncJobRequest.
type AsyncJobResponse ¶ added in v2.13.0
type AsyncJobResponse struct {
// ID: Unique identifier for the async job.
ID string `json:"id"`
// Status: Current status of the job.
Status AsyncJobStatus `json:"status"`
// CreatedAt: When the job was created.
CreatedAt time.Time `json:"created_at"`
// CompletedAt: When the job completed (if applicable).
CompletedAt *time.Time `json:"completed_at,omitempty"`
// ExpiresAt: When the job and its results will expire.
ExpiresAt time.Time `json:"expires_at"`
// Result: The completion response (only present when status is "completed").
Result *CompletionResponse `json:"result,omitempty"`
// Error: Error message (only present when status is "failed").
Error *string `json:"error,omitempty"`
// Progress: Optional progress information during processing.
Progress *AsyncJobProgress `json:"progress,omitempty"`
}
AsyncJobResponse represents the response from an async job operation.
func (*AsyncJobResponse) GetResult ¶ added in v2.13.0
func (r *AsyncJobResponse) GetResult() (*CompletionResponse, error)
GetResult returns the completion result if available, or an error.
func (*AsyncJobResponse) IsCompleted ¶ added in v2.13.0
func (r *AsyncJobResponse) IsCompleted() bool
IsCompleted returns true if the job has completed (successfully or with failure).
func (*AsyncJobResponse) IsExpired ¶ added in v2.13.0
func (r *AsyncJobResponse) IsExpired() bool
IsExpired returns true if the job has expired.
func (*AsyncJobResponse) UnmarshalJSON ¶ added in v2.13.0
func (r *AsyncJobResponse) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for AsyncJobResponse. The Perplexity async API returns Unix timestamps as integers, but tests may use RFC3339 strings.
type AsyncJobStatus ¶ added in v2.13.0
type AsyncJobStatus string
AsyncJobStatus represents the status of an async job.
const ( // StatusPending indicates the job is queued but not yet processing. StatusPending AsyncJobStatus = "pending" // StatusProcessing indicates the job is currently being processed. StatusProcessing AsyncJobStatus = "processing" // StatusCompleted indicates the job has completed successfully. StatusCompleted AsyncJobStatus = "completed" // StatusFailed indicates the job has failed. StatusFailed AsyncJobStatus = "failed" // StatusExpired indicates the job has expired (TTL exceeded). StatusExpired AsyncJobStatus = "expired" )
type AsyncJobTimeoutError ¶ added in v2.13.0
AsyncJobTimeoutError represents timeout errors for async operations.
func (*AsyncJobTimeoutError) Error ¶ added in v2.13.0
func (e *AsyncJobTimeoutError) Error() string
Error implements the error interface for AsyncJobTimeoutError.
func (*AsyncJobTimeoutError) Is ¶ added in v2.13.0
func (e *AsyncJobTimeoutError) Is(target error) bool
Is checks if the error matches ErrAsyncPollingTimeout.
type AsyncJobValidationError ¶ added in v2.13.0
AsyncJobValidationError represents validation errors for async job requests.
func NewAsyncJobValidationError ¶ added in v2.13.0
func NewAsyncJobValidationError(field string, value any, message string) *AsyncJobValidationError
NewAsyncJobValidationError creates a new validation error.
func (*AsyncJobValidationError) Error ¶ added in v2.13.0
func (e *AsyncJobValidationError) Error() string
Error implements the error interface for AsyncJobValidationError.
type AsyncPollingOptions ¶ added in v2.13.0
type AsyncPollingOptions struct {
// InitialInterval is the initial polling interval.
InitialInterval time.Duration
// MaxInterval is the maximum polling interval.
MaxInterval time.Duration
// BackoffMultiplier is the multiplier for exponential backoff.
BackoffMultiplier float64
// MaxWaitTime is the maximum time to wait for job completion.
MaxWaitTime time.Duration
// JitterEnabled adds random jitter to polling intervals.
JitterEnabled bool
}
AsyncPollingOptions configures the polling behavior for async jobs.
func DefaultAsyncPollingOptions ¶ added in v2.13.0
func DefaultAsyncPollingOptions() *AsyncPollingOptions
DefaultAsyncPollingOptions returns default polling options with exponential backoff.
type Choice ¶
type Choice struct {
Index int `json:"index"`
FinishReason string `json:"finish_reason"`
Message Message `json:"message"`
Delta Message `json:"delta"`
}
Choice is a choice object for the Perplexity API.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a client for the Perplexity API.
func NewClient ¶
NewClient creates a new Perplexity API client. The apiKey is the API key to use for authentication. The default model is llama-3-sonar-small-32k-online.
func (*Client) CreateAsyncJob ¶ added in v2.13.0
func (s *Client) CreateAsyncJob(req *AsyncJobRequest) (*AsyncJobResponse, error)
CreateAsyncJob creates a new async job for long-running Sonar Deep Research tasks.
func (*Client) CreateAsyncJobWithContext ¶ added in v2.13.0
func (s *Client) CreateAsyncJobWithContext(ctx context.Context, req *AsyncJobRequest) (*AsyncJobResponse, error)
CreateAsyncJobWithContext creates a new async job with the given context.
func (*Client) GetAsyncJob ¶ added in v2.13.0
func (s *Client) GetAsyncJob(jobID string) (*AsyncJobResponse, error)
GetAsyncJob retrieves the status and result of an async job by ID.
func (*Client) GetAsyncJobWithContext ¶ added in v2.13.0
func (s *Client) GetAsyncJobWithContext(ctx context.Context, jobID string) (*AsyncJobResponse, error)
GetAsyncJobWithContext retrieves the status and result of an async job by ID with the given context.
func (*Client) GetHTTPTimeout ¶
GetHTTPTimeout sets the HTTP timeout.
func (*Client) ListAsyncJobs ¶ added in v2.13.0
func (s *Client) ListAsyncJobs(limit, offset int) (*AsyncJobListResponse, error)
ListAsyncJobs retrieves a list of async jobs with optional pagination.
func (*Client) ListAsyncJobsWithContext ¶ added in v2.13.0
func (s *Client) ListAsyncJobsWithContext(ctx context.Context, limit, offset int) (*AsyncJobListResponse, error)
ListAsyncJobsWithContext retrieves a list of async jobs with the given context and optional pagination.
func (*Client) NewAsyncJobMonitor ¶ added in v2.13.0
func (s *Client) NewAsyncJobMonitor(jobID string, opts *AsyncPollingOptions) *AsyncJobMonitor
NewAsyncJobMonitor creates a new job monitor.
func (*Client) SendCompletionRequest ¶
func (s *Client) SendCompletionRequest(req *CompletionRequest) (*CompletionResponse, error)
SendCompletionRequest sends a completion request to the Perplexity API.
func (*Client) SendCompletionRequestWithContext ¶ added in v2.9.0
func (s *Client) SendCompletionRequestWithContext(ctx context.Context, req *CompletionRequest) (*CompletionResponse, error)
SendCompletionRequestWithContext sends a completion request to the Perplexity API with the given context.
func (*Client) SendSSEHTTPRequest
deprecated
added in
v2.4.0
func (s *Client) SendSSEHTTPRequest(wg *sync.WaitGroup, req *CompletionRequest, responseChannel chan<- CompletionResponse) error
SendSSEHTTPRequest sends a completion request to the Perplexity API using Server-Sent Events. The caller must call wg.Add(1) before invoking; this function calls wg.Done() on return and closes responseChannel when the request is done.
Deprecated: Use StreamCompletion, which does not require a WaitGroup and applies backpressure instead of silently dropping events when the consumer is not ready.
func (*Client) SendSSEHTTPRequestWithContext
deprecated
added in
v2.9.0
func (s *Client) SendSSEHTTPRequestWithContext(ctx context.Context, wg *sync.WaitGroup, req *CompletionRequest, responseChannel chan<- CompletionResponse) error
SendSSEHTTPRequestWithContext is like SendSSEHTTPRequest but accepts a context for cancellation.
Deprecated: Use StreamCompletionWithContext, which does not require a WaitGroup and applies backpressure instead of silently dropping events when the consumer is not ready.
func (*Client) SendSearchRequest ¶ added in v2.14.0
func (s *Client) SendSearchRequest(req *SearchRequest) (*SearchResponse, error)
SendSearchRequest sends a search request to the Perplexity Search API. The Search API provides direct access to Perplexity's real-time web index without the generative LLM layer, returning raw ranked search results.
func (*Client) SendSearchRequestWithContext ¶ added in v2.14.0
func (s *Client) SendSearchRequestWithContext(ctx context.Context, req *SearchRequest) (*SearchResponse, error)
SendSearchRequestWithContext sends a search request to the Perplexity Search API with the given context.
func (*Client) SetAsyncEndpoint ¶ added in v2.13.0
SetAsyncEndpoint sets the async API endpoint.
func (*Client) SetEndpoint ¶
SetEndpoint sets the API endpoint.
func (*Client) SetHTTPClient ¶
SetHTTPClient sets the HTTP client.
func (*Client) SetHTTPTimeout ¶
SetHTTPTimeout sets the HTTP timeout.
func (*Client) SetSearchEndpoint ¶ added in v2.14.0
SetSearchEndpoint sets the Search API endpoint.
func (*Client) StreamCompletion ¶ added in v2.16.1
func (s *Client) StreamCompletion(req *CompletionRequest, responseChannel chan<- CompletionResponse) error
StreamCompletion sends a completion request to the Perplexity API using Server-Sent Events. It blocks until the stream ends or an error occurs, writing each event to responseChannel, and closes responseChannel before returning.
Typical usage: run this in its own goroutine and consume the channel from the caller:
ch := make(chan perplexity.CompletionResponse)
errCh := make(chan error, 1)
go func() { errCh <- client.StreamCompletion(req, ch) }()
for event := range ch { ... }
if err := <-errCh; err != nil { ... }
func (*Client) StreamCompletionWithContext ¶ added in v2.16.1
func (s *Client) StreamCompletionWithContext( ctx context.Context, req *CompletionRequest, responseChannel chan<- CompletionResponse, ) error
StreamCompletionWithContext is like StreamCompletion but accepts a context for cancellation. Cancelling ctx stops the stream and returns ctx.Err().
func (*Client) WaitForAsyncJob ¶ added in v2.13.0
func (s *Client) WaitForAsyncJob(jobID string, opts *AsyncPollingOptions) (*AsyncJobResponse, error)
WaitForAsyncJob polls an async job until completion or timeout. Returns the final job response when completed successfully.
func (*Client) WaitForAsyncJobWithContext ¶ added in v2.13.0
func (s *Client) WaitForAsyncJobWithContext(ctx context.Context, jobID string, opts *AsyncPollingOptions) (*AsyncJobResponse, error)
WaitForAsyncJobWithContext polls an async job with context until completion or timeout.
func (*Client) WaitForAsyncJobWithProgress ¶ added in v2.13.0
func (s *Client) WaitForAsyncJobWithProgress(ctx context.Context, jobID string, opts *AsyncPollingOptions, progressChan chan<- *AsyncJobResponse) (*AsyncJobResponse, error)
WaitForAsyncJobWithProgress polls an async job and sends progress updates via channel. The progress channel will receive job responses on each poll until completion.
type CompletionRequest ¶
type CompletionRequest struct {
Messages []Message `json:"messages" validate:"required_without=MultimodalMessages,dive"`
// MultimodalMessages: Optional. Used when request contains images or mixed content.
// When this field is set, the regular Messages field is ignored.
MultimodalMessages []MultimodalMessage `json:"-" validate:"omitempty,dive"`
// Model: name of the model that will complete your prompt
// supported model: https://docs.perplexity.ai/guides/model-cards
Model string `json:"model" validate:"required"`
// MaxTokens: The maximum number of completion tokens returned by the API.
// The total number of tokens requested in max_tokens plus the number of
// prompt tokens sent in messages must not exceed the context window token limit of model requested.
// If left unspecified, then the model will generate tokens until
// either it reaches its stop token or the end of its context window.
MaxTokens int `json:"max_tokens" validate:"gt=0"`
// Temperatur: The amount of randomness in the response, valued between 0 inclusive and 2 exclusive.
// Higher values are more random, and lower values are more deterministic.
// Required range: 0 < x < 2
Temperature float64 `json:"temperature" validate:"gte=0,lt=2"`
// TopP: The nucleus sampling threshold, valued between 0 and 1 inclusive.
// For each subsequent token, the model considers the results of the tokens with top_p probability mass.
// We recommend either altering top_k or top_p, but not both.
// Required range: 0 < x < 1
TopP float64 `json:"top_p" validate:"gt=0,lt=1"`
// SearchDomainFilter: Given a list of domains, limit the citations used by the online model
// to URLs from the specified domains. Not to exceed 10 domains for allowlisting and denylisting.
// For denylisting add a - to the beginning of the domain string. This filter is in closed beta
SearchDomainFilter []string `json:"search_domain_filter"`
// ReturnImages: Determines whether or not a request to an online model
// should return images. Images are in closed beta
ReturnImages bool `json:"return_images"`
// ReturnRelatedQuestions: Determines whether or not a request to an online model
// should return related questions. Related questions are in closed beta
ReturnRelatedQuestions bool `json:"return_related_questions"`
// SearchRecencyFilter: Returns search results within the specified time interval - does not apply to images.
// Values include year, month, week, day, hour
SearchRecencyFilter string `json:"search_recency_filter,omitempty" validate:"omitempty,oneof=year month week day hour"`
// SearchMode: Controls the search mode used for the request.
// Options: "academic" (prioritizes scholarly sources like peer-reviewed papers and academic journals), "web" (default)
SearchMode string `json:"search_mode,omitempty" validate:"omitempty,oneof=academic web"`
// SearchDomain: Restricts search to a specific domain type.
// Options: "sec" (search within SEC regulatory documents like 10-K, 10-Q, 8-K reports)
SearchDomain string `json:"search_domain,omitempty" validate:"omitempty,oneof=sec"`
// TopK: The number of tokens to keep for highest top-k filtering,
// specified as an integer between 0 and 2048 inclusive.
// If set to 0, top-k filtering is disabled.
// We recommend either altering top_k or top_p, but not both.
// Required range: 0 < x < 2048
TopK int `json:"top_k" validate:"gte=0,lte=2048"`
// Stream: Determines whether or not to incrementally stream the response
// with server-sent events with content-type: text/event-stream
// The client of this does not handle the stream, it is up to the user to handle the stream.
Stream bool `json:"stream"`
// PresencePenalty: A value between -2.0 and 2.0.
// Positive values penalize new tokens based on whether they appear in the text so far,
// increasing the model's likelihood to talk about new topics.
// Incompatible with frequency_penalty
PresencePenalty float64 `json:"presence_penalty" validate:"gte=-2,lte=2"`
// FrequencyPenalty: A multiplicative penalty greater than 0.
// Values greater than 1.0 penalize new tokens based on their existing frequency in the text so far,
// decreasing the model's likelihood to repeat the same line verbatim. A value of 1.0 means no penalty.
// Incompatible with presence_penalty
FrequencyPenalty float64 `json:"frequency_penalty" validate:"gt=0"`
// WebSearchOptions: Optional. Controls web search context and user location for search refinement.
WebSearchOptions *WebSearchOptions `json:"web_search_options,omitempty" validate:"omitempty"`
// ResponseFormat: Optional. Controls the format of the response output.
// Supports JSON Schema and Regex formats for structured outputs.
ResponseFormat *ResponseFormat `json:"response_format,omitempty" validate:"omitempty"`
// ImageDomainFilter: Optional. Controls the domain filter for images.
// Domain Filtering:
// - prepending the url with - will exclude the domain
// - Use simple domain names like example.com or -gettyimages.com
// - Do not include http://, https://, or subdomains
// Filter Strategy:
// - You can mix inclusion and exclusion in domain filters
// - Keep lists short (≤10 entries) for performance and relevance
// Performance Notes:
// - Filters may slightly increase response time
// - Overly restrictive filters may reduce result quality or quantity
ImageDomainFilter []string `json:"image_domain_filter,omitempty" validate:"omitempty"`
// ImageFormatFilter: Optional. Controls the format filter for images.
ImageFormatFilter []string `json:"image_format_filter,omitempty" validate:"omitempty"`
// SearchAfterDateFilter: Optional. Filters search results to include content published after a specific date.
// Date format: "%m/%d/%Y" (e.g., "3/1/2025")
//
// Deprecated: Use PublishedAfter instead for API compliance.
//go:deprecated
SearchAfterDateFilter string `json:"search_after_date_filter,omitempty" validate:"omitempty"`
// SearchBeforeDateFilter: Optional. Filters search results to include content published before a specific date.
// Date format: "%m/%d/%Y" (e.g., "3/1/2025")
//
// Deprecated: Use PublishedBefore instead for API compliance.
//go:deprecated
SearchBeforeDateFilter string `json:"search_before_date_filter,omitempty" validate:"omitempty"`
// LastUpdatedAfterFilter: Optional. Filters search results to include content last updated after a specific date.
// Date format: "%m/%d/%Y" (e.g., "3/1/2025")
LastUpdatedAfterFilter string `json:"last_updated_after_filter,omitempty" validate:"omitempty"`
// LastUpdatedBeforeFilter: Optional. Filters search results to include content last updated before a specific date.
// Date format: "%m/%d/%Y" (e.g., "3/1/2025")
LastUpdatedBeforeFilter string `json:"last_updated_before_filter,omitempty" validate:"omitempty"`
// PublishedAfter: Filters search results to include content published after a specific date.
// Date format: "%m/%d/%Y" (e.g., "3/1/2025")
PublishedAfter string `json:"published_after,omitempty" validate:"omitempty"`
// PublishedBefore: Filters search results to include content published before a specific date.
// Date format: "%m/%d/%Y" (e.g., "3/1/2025")
PublishedBefore string `json:"published_before,omitempty" validate:"omitempty"`
// ReasoningEffort: Optional. Controls the computational effort dedicated to each query for sonar-deep-research model.
// Options: ReasoningEffortLow (faster, simpler answers), ReasoningEffortMedium (balanced approach), ReasoningEffortHigh (deeper, more thorough responses)
// Only applicable for sonar-deep-research model.
ReasoningEffort string `json:"reasoning_effort,omitempty" validate:"omitempty,oneof=low medium high"`
// LanguagePreference: Optional. Specify preferred language for search results and responses.
// Accepts ISO 639-1 language codes (e.g., "en", "fr", "es") or extended format with country (e.g., "en-US", "fr-CA").
LanguagePreference string `json:"language_preference,omitempty" validate:"omitempty,min=2,max=5"`
}
CompletionRequest is a request object for the Perplexity API. https://docs.perplexity.ai/api-reference/chat-completions
func DefaultCompletionRequest ¶
func DefaultCompletionRequest() *CompletionRequest
DefaultCompletionRequest returns a default completion request.
func NewCompletionRequest ¶
func NewCompletionRequest(opts ...CompletionRequestOption) *CompletionRequest
NewCompletionRequest creates a new completion request.
func (*CompletionRequest) HasImages ¶ added in v2.13.0
func (r *CompletionRequest) HasImages() bool
HasImages returns true if any of the messages contain images.
func (*CompletionRequest) IsMultimodal ¶ added in v2.13.0
func (r *CompletionRequest) IsMultimodal() bool
IsMultimodal returns true if the request contains multimodal messages.
func (*CompletionRequest) MarshalJSON ¶ added in v2.13.0
func (r *CompletionRequest) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for CompletionRequest. When MultimodalMessages are present, they are used instead of the regular Messages field.
func (*CompletionRequest) Validate ¶
func (r *CompletionRequest) Validate() error
Validate validates the completion request using the default validator.
func (*CompletionRequest) ValidateSearchDomain ¶ added in v2.13.0
func (r *CompletionRequest) ValidateSearchDomain() error
ValidateSearchDomain validates the search domain parameter.
func (*CompletionRequest) ValidateSearchDomainFilter ¶
func (r *CompletionRequest) ValidateSearchDomainFilter() error
ValidateSearchDomainFilter validates the search domain filter.
func (*CompletionRequest) ValidateSearchRecencyFilter ¶
func (r *CompletionRequest) ValidateSearchRecencyFilter() error
ValidateSearchRecencyFilter validates the search recency filter.
func (*CompletionRequest) ValidateStructuredOutput ¶ added in v2.9.0
func (r *CompletionRequest) ValidateStructuredOutput() error
ValidateStructuredOutput validates the structured output configuration.
type CompletionRequestOption ¶
type CompletionRequestOption func(*CompletionRequest)
CompletionRequestOption is a functional option for the CompletionRequest.
func WithDefaultModel ¶ added in v2.2.0
func WithDefaultModel() CompletionRequestOption
WithDefaultModel sets the model to the default sonar model.
func WithFrequencyPenalty ¶
func WithFrequencyPenalty(frequencyPenalty float64) CompletionRequestOption
WithFrequencyPenalty sets the frequency penalty option.
func WithImageDomainFilter ¶ added in v2.10.0
func WithImageDomainFilter(domains []string) CompletionRequestOption
WithImageDomainFilter sets the image domain filter option. Controls which domains to include or exclude for image generation. Domain Filtering:
- prepending the url with - will exclude the domain
- Use simple domain names like example.com or -gettyimages.com
- Do not include http://, https://, or subdomains
Filter Strategy:
- You can mix inclusion and exclusion in domain filters
- Keep lists short (≤10 entries) for performance and relevance
Performance Notes:
- Filters may slightly increase response time
- Overly restrictive filters may reduce result quality or quantity
func WithImageFormatFilter ¶ added in v2.10.0
func WithImageFormatFilter(formats []string) CompletionRequestOption
WithImageFormatFilter sets the image format filter option. Controls which image formats to include in the response.
func WithImageFromFile ¶ added in v2.13.0
func WithImageFromFile(_ string) CompletionRequestOption
WithImageFromFile adds an image from file path to the current message content. This option should be used in combination with WithMultimodalMessages or when building multimodal content programmatically.
func WithImageFromURL ¶ added in v2.13.0
func WithImageFromURL(_ string) CompletionRequestOption
WithImageFromURL adds an image from URL to the current message content. The URL must be HTTPS and publicly accessible.
func WithJSONSchemaResponseFormat ¶ added in v2.9.0
func WithJSONSchemaResponseFormat(schema any) CompletionRequestOption
WithJSONSchemaResponseFormat sets the response format to JSON Schema. The schema parameter can be a Go struct, map, or any valid JSON schema.
func WithLanguagePreference ¶ added in v2.15.0
func WithLanguagePreference(lang string) CompletionRequestOption
WithLanguagePreference sets the preferred language for search results and responses. Accepts ISO 639-1 language codes (e.g., "en", "fr", "es") or extended format with country (e.g., "en-US", "fr-CA").
func WithLastUpdatedAfterFilter ¶ added in v2.11.0
func WithLastUpdatedAfterFilter(date time.Time) CompletionRequestOption
WithLastUpdatedAfterFilter sets the last updated after filter option. Filters search results to include content last updated after the specified date. The date is automatically formatted to "%m/%d/%Y" format (e.g., "3/1/2025").
func WithLastUpdatedBeforeFilter ¶ added in v2.11.0
func WithLastUpdatedBeforeFilter(date time.Time) CompletionRequestOption
WithLastUpdatedBeforeFilter sets the last updated before filter option. Filters search results to include content last updated before the specified date. The date is automatically formatted to "%m/%d/%Y" format (e.g., "3/1/2025").
func WithLatestUpdated ¶ added in v2.13.0
func WithLatestUpdated(date time.Time) CompletionRequestOption
WithLatestUpdated sets the latest updated filter for web search results. Only pages last updated after the specified date will be included in search results. The date is automatically formatted to MM/DD/YYYY format required by the API.
func WithMaxTokens ¶
func WithMaxTokens(maxTokens int) CompletionRequestOption
WithMaxTokens sets the max tokens option.
func WithMessages ¶
func WithMessages(msg []Message) CompletionRequestOption
WithMessages sets the messages option.
func WithMessagesFromMessages ¶ added in v2.13.0
func WithMessagesFromMessages(messages *Messages) CompletionRequestOption
WithMessagesFromMessages converts a Messages object to appropriate request format. If the Messages object contains multimodal content, it sets MultimodalMessages. Otherwise, it sets the regular Messages field.
func WithModel ¶
func WithModel(model string) CompletionRequestOption
WithModel sets the model option (overrides the default model). Prefer the use of WithModelDefaultModel, WithModelProModel, or WithModelHugeModel.
func WithMultimodalMessages ¶ added in v2.13.0
func WithMultimodalMessages(messages []MultimodalMessage) CompletionRequestOption
WithMultimodalMessages sets multimodal messages for the request. This option enables support for messages containing both text and images.
func WithPresencePenalty ¶
func WithPresencePenalty(presencePenalty float64) CompletionRequestOption
WithPresencePenalty sets the presence penalty option.
func WithPublishedAfter ¶ added in v2.13.0
func WithPublishedAfter(date time.Time) CompletionRequestOption
WithPublishedAfter sets the published after filter option. Filters search results to include content published after the specified date. The date is automatically formatted to "%m/%d/%Y" format (e.g., "3/1/2025").
func WithPublishedBefore ¶ added in v2.13.0
func WithPublishedBefore(date time.Time) CompletionRequestOption
WithPublishedBefore sets the published before filter option. Filters search results to include content published before the specified date. The date is automatically formatted to "%m/%d/%Y" format (e.g., "3/1/2025").
func WithReasoningEffort ¶ added in v2.11.0
func WithReasoningEffort(effort string) CompletionRequestOption
WithReasoningEffort sets the reasoning effort option for sonar-deep-research model. Controls the computational effort dedicated to each query. Options: ReasoningEffortLow (faster, simpler answers), ReasoningEffortMedium (balanced approach), ReasoningEffortHigh (deeper, more thorough responses). Only applicable for sonar-deep-research model.
func WithRegexResponseFormat ¶ added in v2.9.0
func WithRegexResponseFormat(regex string) CompletionRequestOption
WithRegexResponseFormat sets the response format to Regex. The regex parameter should be a valid regular expression pattern.
func WithResponseFormat ¶ added in v2.9.0
func WithResponseFormat(format *ResponseFormat) CompletionRequestOption
WithResponseFormat sets the response format option. Supports both JSON Schema and Regex formats for structured outputs.
func WithReturnImages ¶
func WithReturnImages(returnImages bool) CompletionRequestOption
WithReturnImages sets the return images option.
func WithReturnRelatedQuestions ¶
func WithReturnRelatedQuestions(returnRelatedQuestions bool) CompletionRequestOption
WithReturnRelatedQuestions sets the return related questions option.
func WithSearchAfterDateFilter
deprecated
added in
v2.11.0
func WithSearchAfterDateFilter(date time.Time) CompletionRequestOption
WithSearchAfterDateFilter sets the search after date filter option. Filters search results to include content published after the specified date. The date is automatically formatted to "%m/%d/%Y" format (e.g., "3/1/2025").
Deprecated: Use WithPublishedAfter instead for API compliance.
func WithSearchBeforeDateFilter
deprecated
added in
v2.11.0
func WithSearchBeforeDateFilter(date time.Time) CompletionRequestOption
WithSearchBeforeDateFilter sets the search before date filter option. Filters search results to include content published before the specified date. The date is automatically formatted to "%m/%d/%Y" format (e.g., "3/1/2025").
Deprecated: Use WithPublishedBefore instead for API compliance.
func WithSearchContextSize ¶ added in v2.8.0
func WithSearchContextSize(size string) CompletionRequestOption
WithSearchContextSize sets the search context size for web search. Valid values are "low", "medium", or "high".
func WithSearchDomain ¶ added in v2.13.0
func WithSearchDomain(searchDomain string) CompletionRequestOption
WithSearchDomain sets the search domain option. Options: "sec" (search within SEC regulatory documents like 10-K, 10-Q, 8-K reports).
func WithSearchDomainFilter ¶
func WithSearchDomainFilter(searchDomainFilter []string) CompletionRequestOption
WithSearchDomainFilter sets the search domain filter option.
func WithSearchMode ¶ added in v2.11.0
func WithSearchMode(searchMode string) CompletionRequestOption
WithSearchMode sets the search mode option. Options: "academic" (prioritizes scholarly sources like peer-reviewed papers and academic journals), "web" (default).
func WithSearchRecencyFilter ¶
func WithSearchRecencyFilter(searchRecencyFilter string) CompletionRequestOption
WithSearchRecencyFilter sets the search recency filter option.
func WithStream ¶ added in v2.4.0
func WithStream(stream bool) CompletionRequestOption
WithStream sets the stream option. Determines whether or not to incrementally stream the response. with server-sent events with content-type: text/event-stream.
func WithTemperature ¶
func WithTemperature(temperature float64) CompletionRequestOption
WithTemperature sets the temperature option.
func WithUserLocation ¶ added in v2.8.0
func WithUserLocation(latitude, longitude float64, country string) CompletionRequestOption
WithUserLocation sets the user location for web search. latitude and longitude are the geographic coordinates of the user's location. country is the two-letter ISO country code (e.g., "US", "FR").
func WithWebSearchOptions ¶ added in v2.8.0
func WithWebSearchOptions(opts *WebSearchOptions) CompletionRequestOption
WithWebSearchOptions sets the web search options for the CompletionRequest. It applies the provided WebSearchOptions to the request. If you only need to set specific options, consider using WithSearchContextSize or WithUserLocation directly.
type CompletionResponse ¶
type CompletionResponse struct {
ID string `json:"id"`
Model string `json:"model"`
Created int `json:"created"`
Usage Usage `json:"usage"`
Object string `json:"object"`
Choices []Choice `json:"choices"`
SearchResults *[]SearchResult `json:"search_results,omitempty"`
Images *[]Image `json:"images,omitempty"`
RelatedQuestions *[]string `json:"related_questions,omitempty"`
// Deprecated: Use SearchResults instead for better structured data with titles, URLs, and metadata.
//go:deprecated
Citations *[]string `json:"citations,omitempty"`
}
CompletionResponse is a response object for the Perplexity API.
func (*CompletionResponse) GetCitations
deprecated
added in
v2.3.0
func (r *CompletionResponse) GetCitations() []string
GetCitations returns the citations of the completion response.
Deprecated: Use GetSearchResults instead for better structured data with titles, URLs, and metadata.
func (*CompletionResponse) GetImages ¶ added in v2.10.0
func (r *CompletionResponse) GetImages() []Image
GetImages returns the images of the completion response.
func (*CompletionResponse) GetLastContent ¶
func (r *CompletionResponse) GetLastContent() string
GetLastContent returns the last content of the completion response.
func (*CompletionResponse) GetPostThinkingContent ¶ added in v2.12.0
func (r *CompletionResponse) GetPostThinkingContent() string
GetPostThinkingContent returns the content that comes after the thinking section in reasoning model responses. For reasoning models like sonar-reasoning or sonar-reasoning-pro, the response often contains a <think>...</think> section followed by the actual formatted response. This method extracts only the content after the thinking section. If no thinking section is found, it returns the original content unchanged.
func (*CompletionResponse) GetRelatedQuestions ¶ added in v2.11.0
func (r *CompletionResponse) GetRelatedQuestions() []string
GetRelatedQuestions returns the related questions of the completion response.
func (*CompletionResponse) GetSearchResults ¶ added in v2.10.0
func (r *CompletionResponse) GetSearchResults() []SearchResult
GetSearchResults returns the search results of the completion response.
func (*CompletionResponse) String ¶
func (r *CompletionResponse) String() string
String returns a string representation of the CompletionResponse.
type Content ¶ added in v2.13.0
type Content struct {
Type ContentType `json:"type" validate:"required,oneof=text image_url file_url"`
Text *string `json:"text,omitempty" validate:"required_if=Type text"`
ImageURL *ImageURL `json:"image_url,omitempty" validate:"required_if=Type image_url"`
FileURL *FileURL `json:"file_url,omitempty" validate:"required_if=Type file_url"`
FileName *string `json:"file_name,omitempty"` // Optional filename for base64 encoded files
}
Content represents text, image, or file content in a multimodal message.
func NewFileFileContent ¶ added in v2.15.0
NewFileFileContent creates file content from a file path by encoding it to a base64 data URI. The resulting URL field contains a "data:<mime>;base64,<payload>" URI accepted by the Perplexity API.
func NewFileURLContent ¶ added in v2.15.0
NewFileURLContent creates a file URL content object for multimodal messages. The fileName parameter is optional and only required for base64 encoded files.
func NewImageFileContent ¶ added in v2.13.0
NewImageFileContent creates image content from a file path by encoding it to base64 data URI.
func NewImageURLContent ¶ added in v2.13.0
NewImageURLContent creates an image URL content object for multimodal messages.
func NewTextContent ¶ added in v2.13.0
NewTextContent creates a text content object for multimodal messages.
type ContentType ¶ added in v2.13.0
type ContentType string
ContentType represents the type of content in a multimodal message.
const ( // ContentTypeText represents text content in a multimodal message. ContentTypeText ContentType = "text" // ContentTypeImageURL represents image URL content in a multimodal message. ContentTypeImageURL ContentType = "image_url" // ContentTypeFileURL represents file URL content in a multimodal message. ContentTypeFileURL ContentType = "file_url" )
type Cost ¶ added in v2.12.2
type Cost struct {
InputTokensCost *float64 `json:"input_tokens_cost,omitempty"`
OutputTokensCost *float64 `json:"output_tokens_cost,omitempty"`
RequestCost *float64 `json:"request_cost,omitempty"`
TotalCost *float64 `json:"total_cost,omitempty"`
}
Cost represents the cost breakdown for API usage.
type FileProcessor ¶ added in v2.15.0
type FileProcessor struct{}
FileProcessor handles file encoding and validation for the Perplexity API.
func NewFileProcessor ¶ added in v2.15.0
func NewFileProcessor() *FileProcessor
NewFileProcessor creates a new FileProcessor instance.
func (*FileProcessor) CheckFileURLAccessibility ¶ added in v2.15.0
func (p *FileProcessor) CheckFileURLAccessibility(ctx context.Context, fileURL string) error
CheckFileURLAccessibility performs a HEAD request to verify the file URL is accessible. This is an optional validation that can be used to verify URLs before sending to the API.
func (*FileProcessor) EncodeFileFromPath ¶ added in v2.15.0
func (p *FileProcessor) EncodeFileFromPath(filePath string) (string, string, error)
EncodeFileFromPath reads a file, validates it, and returns base64 encoded data and filename. The file path should point to a valid file in one of the supported formats. Returns (base64EncodedData, fileName, error). IMPORTANT: Returns raw base64 data WITHOUT data URI prefix (unlike image encoding).
func (*FileProcessor) ValidateFileFormat ¶ added in v2.15.0
func (p *FileProcessor) ValidateFileFormat(format string) error
ValidateFileFormat checks if the file format is supported by the Perplexity API.
func (*FileProcessor) ValidateFileSize ¶ added in v2.15.0
func (p *FileProcessor) ValidateFileSize(size int64) error
ValidateFileSize checks if the file size is within the 50MB limit.
func (*FileProcessor) ValidateFileURL ¶ added in v2.15.0
func (p *FileProcessor) ValidateFileURL(fileURL string) error
ValidateFileURL validates that a URL is HTTPS (or a base64 data URI) and has a valid format. Accepts either an https:// URL or a data:<mime>;base64,<payload> URI, matching what the Perplexity API accepts for embedded files.
type FileURL ¶ added in v2.15.0
type FileURL struct {
URL string `json:"url" validate:"required"`
}
FileURL represents file content with URL or base64 data.
type Image ¶ added in v2.10.0
type Image struct {
ImageURL string `json:"image_url"`
OriginURL string `json:"origin_url"`
Height int `json:"height"`
Width int `json:"width"`
}
Image represents a single image in the Perplexity API response.
type ImageProcessor ¶ added in v2.13.0
type ImageProcessor struct{}
ImageProcessor handles image encoding and validation for the Perplexity API.
func NewImageProcessor ¶ added in v2.13.0
func NewImageProcessor() *ImageProcessor
NewImageProcessor creates a new ImageProcessor instance.
func (*ImageProcessor) CheckImageURLAccessibility ¶ added in v2.13.0
func (p *ImageProcessor) CheckImageURLAccessibility(ctx context.Context, imageURL string) error
CheckImageURLAccessibility performs a HEAD request to verify the image URL is accessible. This is an optional validation that can be used to verify URLs before sending to the API.
func (*ImageProcessor) EncodeImageFromFile ¶ added in v2.13.0
func (p *ImageProcessor) EncodeImageFromFile(filepath string) (string, error)
EncodeImageFromFile reads an image file, validates it, and returns a base64 data URI. The file path should point to a valid image file in one of the supported formats. Returns a data URI in the format: "data:image/[format];base64,[encoded_data]".
func (*ImageProcessor) EstimateTokenUsage ¶ added in v2.13.0
func (p *ImageProcessor) EstimateTokenUsage(width, height int) int
EstimateTokenUsage estimates the token usage for an image based on its dimensions. According to Perplexity documentation: tokens = (width px × height px) / 750 This function requires image dimensions to be provided separately.
func (*ImageProcessor) ValidateImageFormat ¶ added in v2.13.0
func (p *ImageProcessor) ValidateImageFormat(format string) error
ValidateImageFormat checks if the image format is supported by the Perplexity API.
func (*ImageProcessor) ValidateImageSize ¶ added in v2.13.0
func (p *ImageProcessor) ValidateImageSize(size int64) error
ValidateImageSize checks if the image size is within the 50MB limit.
func (*ImageProcessor) ValidateImageURL ¶ added in v2.13.0
func (p *ImageProcessor) ValidateImageURL(imageURL string) error
ValidateImageURL validates that a URL is HTTPS (or a base64 data URI) and has a valid format. Accepts either an https:// URL or a data:image/<fmt>;base64,<payload> URI, matching what the Perplexity API accepts and what EncodeImageFromFile produces.
type ImageURL ¶ added in v2.13.0
type ImageURL struct {
URL string `json:"url" validate:"required"`
}
ImageURL represents image content with URL or base64 data URI.
type JSONSchemaConfig ¶ added in v2.9.0
type JSONSchemaConfig struct {
// Schema is the JSON schema object that defines the expected output structure.
// It can be a Go struct, map, or any valid JSON schema.
Schema any `json:"schema" validate:"required"`
}
JSONSchemaConfig contains the JSON schema for structured output.
type Message ¶
type Message struct {
Role string `json:"role" validate:"required,oneof=system user assistant"`
Content string `json:"content"`
}
Message is a message object for the Perplexity API.
type Messages ¶ added in v2.1.0
type Messages struct {
// contains filtered or unexported fields
}
Messages is an object that contains a list of messages for the Perplexity API.
func NewMessages ¶ added in v2.1.0
func NewMessages(opts ...MessagesOption) Messages
NewMessages returns a new Messages object.
func (*Messages) AddAgentMessage ¶ added in v2.1.0
AddAgentMessage adds an assistant message to the Messages object.
func (*Messages) AddMultimodalAgentMessage ¶ added in v2.13.0
AddMultimodalAgentMessage adds an assistant message with mixed content.
func (*Messages) AddMultimodalUserMessage ¶ added in v2.13.0
AddMultimodalUserMessage adds a user message with mixed content (text + images + files).
func (*Messages) AddUserMessage ¶ added in v2.1.0
AddUserMessage adds a user message to the Messages object.
func (*Messages) AddUserMessageWithFile ¶ added in v2.15.0
AddUserMessageWithFile adds a user message with text and a single file URL.
func (*Messages) AddUserMessageWithFileFromPath ¶ added in v2.15.0
AddUserMessageWithFileFromPath adds a user message with text and file from file path.
func (*Messages) AddUserMessageWithImage ¶ added in v2.13.0
AddUserMessageWithImage adds a user message with text and a single image URL.
func (*Messages) AddUserMessageWithImageFile ¶ added in v2.13.0
AddUserMessageWithImageFile adds a user message with text and image from file path.
func (*Messages) GetMessages ¶ added in v2.1.0
GetMessages returns all messages including the system message (if any) as a slice of Message. The system message is always included as the first message when present.
func (*Messages) GetMultimodalMessages ¶ added in v2.13.0
func (m *Messages) GetMultimodalMessages() []MultimodalMessage
GetMultimodalMessages returns all messages in multimodal format including the system message.
func (*Messages) GetSystemMessage ¶ added in v2.1.0
GetSystemMessage returns the system message.
func (*Messages) HasFiles ¶ added in v2.15.0
HasFiles returns true if any of the multimodal messages contain files.
func (*Messages) HasImages ¶ added in v2.13.0
HasImages returns true if any of the multimodal messages contain images.
func (*Messages) IsMultimodal ¶ added in v2.13.0
IsMultimodal returns true if the Messages object contains multimodal messages.
type MessagesOption ¶ added in v2.1.0
type MessagesOption func(*Messages)
MessagesOption is an option for the NewMessages function.
func WithSystemMessage ¶ added in v2.1.0
func WithSystemMessage(content string) MessagesOption
WithSystemMessage sets the system message for the Messages object.
type MultimodalMessage ¶ added in v2.13.0
type MultimodalMessage struct {
Role string `json:"role" validate:"required,oneof=system user assistant"`
Content []Content `json:"content" validate:"required,min=1,dive"`
}
MultimodalMessage supports both text and image content according to Perplexity API specification.
type RegexConfig ¶ added in v2.9.0
type RegexConfig struct {
// Regex is the regular expression pattern that the output must match.
// Supports basic regex features like character classes, quantifiers, alternation, and groups.
Regex string `json:"regex" validate:"required"`
}
RegexConfig contains the regex pattern for structured output.
type RequestValidator ¶ added in v2.10.0
type RequestValidator struct {
// contains filtered or unexported fields
}
RequestValidator provides validation functionality for CompletionRequest. This is a stateless validator that can be reused across multiple requests.
func NewRequestValidator ¶ added in v2.10.0
func NewRequestValidator() *RequestValidator
NewRequestValidator creates a new RequestValidator instance.
func (*RequestValidator) ValidateRequest ¶ added in v2.10.0
func (v *RequestValidator) ValidateRequest(req *CompletionRequest) error
ValidateRequest validates a CompletionRequest using the validator instance.
type ResponseError ¶ added in v2.9.0
type ResponseError struct {
ErrorData struct {
Message string `json:"message"`
Type string `json:"type"`
Code int `json:"code"`
} `json:"error"`
}
ResponseError is an error response object for the Perplexity API.
func (*ResponseError) Error ¶ added in v2.9.0
func (r *ResponseError) Error() string
Error returns the error message of the ResponseError.
type ResponseFormat ¶ added in v2.9.0
type ResponseFormat struct {
// Type specifies the format type: "json_schema" or "regex"
Type string `json:"type" validate:"required,oneof=json_schema regex"`
// JSONSchema contains the JSON schema configuration when Type is "json_schema"
JSONSchema *JSONSchemaConfig `json:"json_schema,omitempty" validate:"omitempty"`
// Regex contains the regex configuration when Type is "regex"
Regex *RegexConfig `json:"regex,omitempty" validate:"omitempty"`
}
ResponseFormat specifies the format of the response output.
type SearchImageItem ¶ added in v2.14.0
type SearchImageItem struct {
URL string `json:"url"`
Width *int `json:"width,omitempty"`
Height *int `json:"height,omitempty"`
}
SearchImageItem represents an image in a search result.
func (*SearchImageItem) String ¶ added in v2.14.0
func (img *SearchImageItem) String() string
String returns a string representation of the SearchImageItem.
type SearchRequest ¶ added in v2.14.0
type SearchRequest struct {
Query any `json:"query" validate:"required"` // string or []string
MaxResults *int `json:"max_results,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
ReturnImages *bool `json:"return_images,omitempty"`
ReturnSnippets *bool `json:"return_snippets,omitempty"`
Country *string `json:"country,omitempty"`
LanguagePreference *string `json:"language_preference,omitempty"`
SearchDomainFilter *[]string `json:"search_domain_filter,omitempty"`
}
SearchRequest represents a request to the Perplexity Search API. The Search API provides direct access to Perplexity's real-time web index without the generative LLM layer, returning raw ranked search results.
func NewSearchRequest ¶ added in v2.14.0
func NewSearchRequest(query any, opts ...SearchRequestOption) *SearchRequest
NewSearchRequest creates a new SearchRequest with the given query and options. The query can be either a single string or an array of strings for multi-query searches.
type SearchRequestOption ¶ added in v2.14.0
type SearchRequestOption func(*SearchRequest)
SearchRequestOption is a function that modifies a SearchRequest.
func WithSearchCountry ¶ added in v2.14.0
func WithSearchCountry(country string) SearchRequestOption
WithSearchCountry sets the ISO country code to bias or filter results by region.
func WithSearchDomains ¶ added in v2.14.0
func WithSearchDomains(domains []string) SearchRequestOption
WithSearchDomains sets the domain filters for the search.
func WithSearchLanguagePreference ¶ added in v2.15.0
func WithSearchLanguagePreference(lang string) SearchRequestOption
WithSearchLanguagePreference sets the preferred language for search results. Accepts ISO 639-1 language codes (e.g., "en", "fr", "es") or extended format with country (e.g., "en-US", "fr-CA").
func WithSearchMaxResults ¶ added in v2.14.0
func WithSearchMaxResults(maxResults int) SearchRequestOption
WithSearchMaxResults sets the maximum number of results to return per query.
func WithSearchMaxTokens ¶ added in v2.15.0
func WithSearchMaxTokens(maxTokens int) SearchRequestOption
WithSearchMaxTokens sets the maximum tokens extracted per page in search results.
func WithSearchReturnImages ¶ added in v2.14.0
func WithSearchReturnImages(include bool) SearchRequestOption
WithSearchReturnImages sets whether to include image URLs in the search results.
func WithSearchReturnSnippets ¶ added in v2.14.0
func WithSearchReturnSnippets(include bool) SearchRequestOption
WithSearchReturnSnippets sets whether to include text snippets in the search results.
type SearchRequestValidator ¶ added in v2.14.0
type SearchRequestValidator struct {
// contains filtered or unexported fields
}
SearchRequestValidator provides validation for SearchRequest objects.
func NewSearchRequestValidator ¶ added in v2.14.0
func NewSearchRequestValidator() *SearchRequestValidator
NewSearchRequestValidator creates a new SearchRequestValidator.
func (*SearchRequestValidator) ValidateSearchRequest ¶ added in v2.14.0
func (v *SearchRequestValidator) ValidateSearchRequest(req *SearchRequest) error
ValidateSearchRequest validates a SearchRequest.
type SearchResponse ¶ added in v2.14.0
type SearchResponse struct {
Results []SearchResultItem `json:"results"`
}
SearchResponse represents a response from the Perplexity Search API.
func (*SearchResponse) GetResultCount ¶ added in v2.14.0
func (r *SearchResponse) GetResultCount() int
GetResultCount returns the number of search results.
func (*SearchResponse) GetResults ¶ added in v2.14.0
func (r *SearchResponse) GetResults() []SearchResultItem
GetResults returns the search results.
func (*SearchResponse) String ¶ added in v2.14.0
func (r *SearchResponse) String() string
String returns a string representation of the SearchResponse.
type SearchResult ¶ added in v2.10.0
type SearchResult struct {
Title string `json:"title"`
URL string `json:"url"`
Date *string `json:"date,omitempty"`
LastUpdated *string `json:"last_updated,omitempty"`
}
SearchResult represents a single search result in the Perplexity API response.
func (*SearchResult) String ¶ added in v2.10.0
func (sr *SearchResult) String() string
String returns a string representation of the SearchResult.
type SearchResultItem ¶ added in v2.14.0
type SearchResultItem struct {
Title string `json:"title"`
URL string `json:"url"`
Snippet *string `json:"snippet,omitempty"`
Date *string `json:"date,omitempty"`
Score *float64 `json:"score,omitempty"`
Images *[]SearchImageItem `json:"images,omitempty"`
}
SearchResultItem represents a single search result from the Search API. This is distinct from SearchResult which is used in chat completion responses.
func (*SearchResultItem) String ¶ added in v2.14.0
func (item *SearchResultItem) String() string
String returns a string representation of the SearchResultItem.
type Usage ¶
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
Cost *Cost `json:"cost,omitempty"`
}
Usage is a usage object for the Perplexity API.
type UserLocation ¶ added in v2.8.0
type UserLocation struct {
// Latitude of the user's location.
Latitude float64 `json:"latitude,omitempty" validate:"omitempty"`
// Longitude of the user's location.
Longitude float64 `json:"longitude,omitempty" validate:"omitempty"`
// Country is the two-letter ISO country code of the user's location.
Country string `json:"country,omitempty" validate:"omitempty,len=2"`
}
UserLocation specifies an approximate user location for search refinement.
type WebSearchOptions ¶ added in v2.8.0
type WebSearchOptions struct {
// SearchContextSize determines how much search context is retrieved for the model.
// Options: low (default), medium, high.
// - low: minimizes context for cost savings but less comprehensive answers
// - medium: balanced approach suitable for most queries
// - high: maximizes context for comprehensive answers but at higher cost
SearchContextSize string `json:"search_context_size,omitempty" validate:"omitempty,oneof=low medium high"`
// UserLocation refines search results based on geography.
UserLocation *UserLocation `json:"user_location,omitempty" validate:"omitempty"`
// LatestUpdated filters search results to show only pages last updated after this date.
// Format: MM/DD/YYYY (e.g., "6/1/2025", "12/31/2024")
LatestUpdated string `json:"latest_updated,omitempty" validate:"omitempty"`
}
WebSearchOptions specifies web search context size and user location for the request.
Source Files
¶
- perplexity.go
- perplexity_async.go
- perplexity_async_request.go
- perplexity_async_utils.go
- perplexity_error.go
- perplexity_file.go
- perplexity_image.go
- perplexity_msg.go
- perplexity_request.go
- perplexity_request_validator.go
- perplexity_response.go
- perplexity_search_request.go
- perplexity_search_response.go
- perplexity_search_validator.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
async-completion
command
Package main demonstrates async completion requests with the Perplexity API.
|
Package main demonstrates async completion requests with the Perplexity API. |
|
basic-completion
command
Package main demonstrates basic completion requests with the Perplexity API.
|
Package main demonstrates basic completion requests with the Perplexity API. |
|
file-analysis
command
Package main demonstrates file attachment capabilities of the Perplexity API.
|
Package main demonstrates file attachment capabilities of the Perplexity API. |
|
image-search
command
Package main demonstrates image search capabilities of the Perplexity API.
|
Package main demonstrates image search capabilities of the Perplexity API. |
|
language-preference
command
Package main demonstrates the language_preference parameter for both Chat and Search APIs.
|
Package main demonstrates the language_preference parameter for both Chat and Search APIs. |
|
search-example
command
|
|
|
search-max-tokens
command
Package main demonstrates the max_tokens parameter for the Search API.
|
Package main demonstrates the max_tokens parameter for the Search API. |
|
shared
Package shared provides common utilities for the example programs.
|
Package shared provides common utilities for the example programs. |
|
streaming-sse
command
Package main demonstrates Server-Sent Events (SSE) streaming with the Perplexity API.
|
Package main demonstrates Server-Sent Events (SSE) streaming with the Perplexity API. |
|
structured-output
command
Package main demonstrates structured output capabilities of the Perplexity API.
|
Package main demonstrates structured output capabilities of the Perplexity API. |
|
test-issue119
command
Package main provides a comprehensive integration test for Issue 119 features.
|
Package main provides a comprehensive integration test for Issue 119 features. |