An unofficial, community-maintained Go client library for the Perplexity API. This SDK provides idiomatic Go interfaces for chat completions, streaming responses, and web search with 60+ parameters, making it easy to integrate Perplexity's powerful AI capabilities into your Go applications.
v1.0.1 Released (2025-11-19): Added missing WebSearchOptions fields including ImageResultsEnhancedRelevance (bool), SearchContextSize (enum: low, medium, high), and SearchType (enum: fast, pro, auto). Enhanced web search capabilities with granular control over search behavior and image result relevance.
⚠️ Disclaimer: This is an unofficial SDK and is not affiliated with, endorsed by, or supported by Perplexity AI. For official support, please refer to the Perplexity API documentation.
Perplexity's Sonar language models offer powerful AI capabilities with real-time web search integration, but integrating them into Go applications requires careful handling of HTTP requests, streaming responses, and error management.
Perplexity Go SDK provides a clean, idiomatic Go interface that handles all the complexity for you. Focus on building your application while the SDK manages authentication, retries, streaming, and error handling.
Full support for Perplexity's chat API with 60+ parameters. Synchronous and streaming responses with all Sonar models.
Advanced search with filtering, multiple queries, specialized modes, and enhanced image results (v1.0.1+).
Real-time streaming with Server-Sent Events (SSE) for better user experience. Handle chunks as they arrive.
Function calling and tool integration for external system interactions. Enable AI to execute actions.
Access to model reasoning steps to understand AI conclusions.
Exponential backoff for transient errors with configurable retry logic.
Detailed error types for all API responses with clear debugging messages.
Comprehensive type definitions with generics for compile-time safety.
All methods accept context.Context for cancellation and timeouts.
Clean, extensible API design following Go best practices. Flexible configuration with option functions.
API key support with TLS. Environment variable integration for safe credential management.
Control image result relevance with ImageResultsEnhancedRelevance. Get more accurate visual results (v1.0.1+).
Adjust search context size (low/medium/high) for optimal results. Balance speed and comprehensiveness (v1.0.1+).
Choose between fast, pro, or auto search modes. Optimize for speed or quality based on your needs (v1.0.1+).
Comprehensive examples and documentation. Clear API reference with usage patterns and best practices.
60+ chat parameters including temperature, top_p, max_tokens, presence/frequency penalties, and more.
go get github.com/ZaguanLabs/perplexity-go/perplexitypackage main
import (
"context"
"fmt"
"log"
"github.com/ZaguanLabs/perplexity-go/perplexity"
"github.com/ZaguanLabs/perplexity-go/perplexity/chat"
"github.com/ZaguanLabs/perplexity-go/perplexity/types"
)
func main() {
// Create a new client
client, err := perplexity.NewClient("your-api-key")
if err != nil {
log.Fatal(err)
}
// Create a chat completion
result, err := client.Chat.Create(context.Background(), &chat.CompletionParams{
Model: "sonar",
Messages: []types.ChatMessage{
types.UserMessage("What is the capital of France?"),
},
MaxTokens: types.Int(100),
})
if err != nil {
log.Fatal(err)
}
// Print the response
fmt.Println(result.Choices[0].Message.Content)
}package main
import (
"context"
"fmt"
"log"
"github.com/ZaguanLabs/perplexity-go/perplexity"
"github.com/ZaguanLabs/perplexity-go/perplexity/chat"
"github.com/ZaguanLabs/perplexity-go/perplexity/types"
)
func main() {
client, err := perplexity.NewClient("your-api-key")
if err != nil {
log.Fatal(err)
}
// Create a streaming chat completion
stream, err := client.Chat.CreateStream(context.Background(), &chat.CompletionParams{
Model: "sonar",
Messages: []types.ChatMessage{
types.UserMessage("Tell me a story"),
},
Stream: types.Bool(true),
})
if err != nil {
log.Fatal(err)
}
defer stream.Close()
// Process streaming chunks
for {
chunk, err := stream.Recv()
if err != nil {
break
}
if len(chunk.Choices) > 0 {
fmt.Print(chunk.Choices[0].Delta.Content)
}
}
}package main
import (
"context"
"fmt"
"log"
"github.com/ZaguanLabs/perplexity-go/perplexity"
"github.com/ZaguanLabs/perplexity-go/perplexity/search"
"github.com/ZaguanLabs/perplexity-go/perplexity/types"
)
func main() {
client, err := perplexity.NewClient("your-api-key")
if err != nil {
log.Fatal(err)
}
// Perform a web search
searchResult, err := client.Search.Create(context.Background(), &search.SearchParams{
Query: "latest AI developments",
MaxResults: types.Int(5),
})
if err != nil {
log.Fatal(err)
}
// Print search results
for _, item := range searchResult.Results {
fmt.Printf("%s: %s\n", item.Title, item.URL)
}
}package main
import (
"context"
"fmt"
"log"
"github.com/ZaguanLabs/perplexity-go/perplexity"
"github.com/ZaguanLabs/perplexity-go/perplexity/chat"
"github.com/ZaguanLabs/perplexity-go/perplexity/types"
)
func main() {
client, err := perplexity.NewClient("your-api-key")
if err != nil {
log.Fatal(err)
}
// Chat with enhanced web search options
result, err := client.Chat.Create(context.Background(), &chat.CompletionParams{
Model: "sonar-pro",
Messages: []types.ChatMessage{
types.UserMessage("What are the latest developments in quantum computing?"),
},
WebSearchOptions: &chat.WebSearchOptions{
ImageResultsEnhancedRelevance: types.Bool(true),
SearchContextSize: types.String("high"),
SearchType: types.String("pro"),
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Choices[0].Message.Content)
}New in v1.0.1: Enhanced web search options including image results relevance, configurable search context size (low/medium/high), and search type selection (fast/pro/auto).
Set your Perplexity API key as an environment variable:
export PERPLEXITY_API_KEY=your-api-key-hereThen create a client without passing the API key:
client, err := perplexity.NewClient("") // Reads from PERPLEXITY_API_KEYThe SDK supports flexible configuration through functional options:
client, err := perplexity.NewClient(
"your-api-key",
perplexity.WithBaseURL("https://custom.api.com"),
perplexity.WithTimeout(30*time.Second),
perplexity.WithMaxRetries(5),
perplexity.WithDefaultHeader("X-Custom-Header", "value"),
)WithBaseURL(url string) - Set a custom API base URLWithHTTPClient(client *http.Client) - Use a custom HTTP clientWithTimeout(timeout time.Duration) - Set request timeout (default: 15 minutes)WithMaxRetries(retries int) - Set maximum retry attempts (default: 2)WithDefaultHeader(key, value string) - Add a default header to all requestsperplexity-go/ ├── perplexity/ │ ├── client.go # Main client implementation │ ├── chat/ │ │ ├── chat.go # Chat completions API │ │ ├── stream.go # Streaming support │ │ └── types.go # Chat-specific types │ ├── search/ │ │ ├── search.go # Web search API │ │ └── types.go # Search-specific types │ ├── types/ │ │ └── types.go # Shared types and utilities │ ├── config.go # Configuration management │ └── errors.go # Error types and handling ├── examples/ │ ├── basic/ # Basic usage examples │ ├── streaming/ # Streaming examples │ ├── search/ # Web search examples │ └── advanced/ # Advanced features ├── go.mod └── README.md
Initial release with complete Perplexity API implementation. Zero external dependencies, chat completions, streaming support, search API, 60+ parameters, comprehensive error handling, and type-safe interfaces. ~70% test coverage with 50+ test cases.
First official production-ready release after comprehensive 8-phase audit. 76.1% test coverage (+24.1%), 133 tests, 33 benchmarks. Zero security vulnerabilities, 16x faster than Python SDK, 25K+ req/sec throughput. Overall grade: A - Production Ready.
Added missing WebSearchOptions fields: ImageResultsEnhancedRelevance for controlling image result relevance, SearchContextSize (low/medium/high) for adjusting search depth, and SearchType (fast/pro/auto) for optimizing search mode.
New asyncchat package implementing /async/chat/completions endpoints. AsyncChat.Create(), List(), and Get() methods. Status tracking (CREATED, IN_PROGRESS, COMPLETED, FAILED), idempotency_key support, ForceNewAgent and UserOriginalQuery fields.
Re-tagged release to fix packaging issues.
Fixed broken .gitignore pattern that was excluding necessary files from the repository.
Community feedback and improvements, additional API features as Perplexity releases them, performance optimizations, enhanced documentation and examples, bug fixes and stability improvements.
# Clone the repository
git clone https://github.com/ZaguanLabs/perplexity-go.git
cd perplexity-go
# Build
go build ./...
# Run tests
go test ./...# Set your API key
export PERPLEXITY_API_KEY=your-api-key-here
# Run basic example
go run examples/basic/main.go
# Run streaming example
go run examples/streaming/main.go
# Run web search example
go run examples/search/main.goContributions are welcome! Whether it's bug reports, feature requests, or pull requests, we appreciate all forms of contribution.
Apache 2.0 Licensed - The Perplexity Go SDK is free and open source software. You're welcome to use, modify, and distribute it for any purpose.