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.
Current parity target: official Perplexity Python SDK 0.43.5 (Go SDK 1.6.0).
β οΈ 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.
- π Production Ready: Comprehensive error handling, retries, and timeouts
- π¦ Zero Dependencies: Uses only the Go standard library
- π Type Safe: Full type definitions with compile-time safety
- β‘ Streaming Support: Real-time responses with Server-Sent Events
- π Complete API Coverage: Chat, streaming, and search endpoints
- π Well Documented: Extensive examples and GoDoc comments
- β Thoroughly Tested: 76%+ test coverage with 130+ test cases
- π― Fully Audited: Comprehensive security, performance, and compliance audits passed
- Chat Completions: Full support for Perplexity's chat API with 60+ parameters
- Async Chat Completions: Submit, list, and retrieve asynchronous chat completion requests
- Streaming Responses: Real-time streaming with Server-Sent Events (SSE)
- Web Search: Advanced search with filtering, multiple queries, and specialized modes
- Tool Calling: Function calling and tool integration
- Reasoning Traces: Access to model reasoning steps
- Context-Aware: All methods accept
context.Contextfor cancellation and timeouts - Automatic Retries: Exponential backoff for transient errors
- Type Safety: Comprehensive type definitions with generics
- Error Handling: Detailed error types for all API responses
- Flexible Configuration: Functional options pattern for client setup
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/search"
"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)
// 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)
}
}Submit long-running chat completion requests and retrieve results later:
import (
"github.com/ZaguanLabs/perplexity-go/perplexity/asyncchat"
)
// Submit an async chat completion request
asyncResult, err := client.AsyncChat.Create(ctx, &asyncchat.CompletionCreateParams{
Request: &chat.CompletionParams{
Model: "sonar",
Messages: []types.ChatMessage{
types.UserMessage("Explain quantum computing in detail"),
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Request ID: %s, Status: %s\n", asyncResult.ID, asyncResult.Status)
// List all async requests
listResult, err := client.AsyncChat.List(ctx)
if err != nil {
log.Fatal(err)
}
for _, req := range listResult.Requests {
fmt.Printf("ID: %s, Status: %s\n", req.ID, req.Status)
}
// Get a specific async request result
getResult, err := client.AsyncChat.Get(ctx, asyncResult.ID, nil)
if err != nil {
log.Fatal(err)
}
if getResult.Status == asyncchat.CompletionStatusCompleted && getResult.Response != nil {
fmt.Println(getResult.Response.Choices[0].Message.Content)
}The API key can be provided in two ways:
- Direct parameter:
client, err := perplexity.NewClient("your-api-key")- Environment variable:
export PERPLEXITY_API_KEY="your-api-key"client, err := perplexity.NewClient("") // Reads from PERPLEXITY_API_KEYCustomize the client with 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"),
)Available options:
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 requests
The SDK provides typed errors for different HTTP status codes:
resp, err := client.Chat.Completions.Create(ctx, params)
if err != nil {
switch e := err.(type) {
case *perplexity.AuthenticationError:
log.Fatal("Invalid API key:", e)
case *perplexity.RateLimitError:
log.Println("Rate limited, retrying...")
case *perplexity.InternalServerError:
log.Println("Server error, will retry automatically")
default:
log.Fatal("Unexpected error:", err)
}
}Error types:
BadRequestError(400)AuthenticationError(401)PermissionDeniedError(403)NotFoundError(404)ConflictError(409)UnprocessableEntityError(422)RateLimitError(429)InternalServerError(5xx)ConnectionError(network errors)TimeoutError(request timeout)
Helper functions:
IsRetryable(err error) bool- Check if error is retryableIsRateLimitError(err error) bool- Check for rate limit errorsIsAuthenticationError(err error) bool- Check for auth errorsIsTimeoutError(err error) bool- Check for timeout errors
- Go 1.21 or higher
- A Perplexity API key (get one here)
- π CHANGELOG.md - Version history and release notes
- π οΈ DEVELOPMENT.md - Development status and roadmap
- π€ CONTRIBUTING.md - Contribution guidelines
- π LICENSE - Apache 2.0 License
This is an unofficial, community-maintained project. For issues with this SDK:
- π Report bugs
- π‘ Request features
- π€ Contribute
For Perplexity API support, please contact Perplexity AI directly.
Apache 2.0 - See LICENSE for details.
This SDK was built with reference to the official Python SDK to ensure API compatibility and feature parity.