Community MaintainedSDK • Go • v1.2.0

Perplexity Go SDK

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.2.0 Released (2026-05-02): Added reusable per-request options, raw response helpers across public resources, Python SDK-style client cloning with option overrides, default query/header options, streaming request options, and missing search last-updated filters.

⚠️ 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.

Why Perplexity Go SDK?

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.

Features

Chat Completions

Full support for Perplexity's chat API with 60+ parameters. Synchronous and streaming responses with all Sonar models.

Web Search

Advanced search with filtering, multiple queries, specialized modes, enhanced image results, and last-updated filters.

Streaming Responses

Real-time streaming with Server-Sent Events (SSE) for better user experience. Handle chunks as they arrive.

Tool Calling

Function calling and tool integration for external system interactions plus async chat completion workflows.

Reasoning Traces

Access to model reasoning steps to understand AI conclusions.

Automatic Retries

Exponential backoff for transient errors with configurable retry logic.

Error Handling

Detailed error types for all API responses with clear debugging messages.

Type Safety

Comprehensive type definitions with generics for compile-time safety.

Context-Aware

All methods accept context.Context for cancellation and timeouts.

Functional Options

Functional options pattern for client setup, client cloning, default headers/query parameters, and per-request overrides.

Secure Authentication

API key support with TLS. Environment variable integration for safe credential management.

Enhanced Image Search

Control image result relevance with ImageResultsEnhancedRelevance. Get more accurate visual results (v1.0.1+).

Configurable Search Context

Adjust search context size (low/medium/high) for optimal results. Balance speed and comprehensiveness (v1.0.1+).

Flexible Search Types

Choose between fast, pro, or auto search modes. Optimize for speed or quality based on your needs (v1.0.1+).

Well Documented

Comprehensive examples and documentation. Clear API reference with usage patterns and best practices.

Complete Parameters

60+ chat parameters plus per-request headers, query parameters, extra JSON body fields, and timeouts.

Quick Start

Prerequisites

Installation

go get github.com/ZaguanLabs/perplexity-go/perplexity

Basic Usage

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() {
    // 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)
}

Streaming Usage

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)
        }
    }
}

Web Search Example

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)
    }
}

Advanced Web Search Options

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)
}

Enhanced web search options include image results relevance, configurable search context size (low/medium/high), search type selection (fast/pro/auto), and v1.2.0 last-updated filters.

Environment Setup

Set your Perplexity API key as an environment variable:

export PERPLEXITY_API_KEY=your-api-key-here

Then create a client without passing the API key:

client, err := perplexity.NewClient("") // Reads from PERPLEXITY_API_KEY

Configuration

The SDK supports flexible configuration through functional options:

Client 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"),
    perplexity.WithDefaultQuery("source", "docs"),
)

Available Options

  • WithBaseURL(url string) - Set a custom API base URL
  • WithHTTPClient(client *http.Client) - Use a custom HTTP client
  • WithTimeout(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
  • WithDefaultHeaders(headers map[string]string) - Add default headers to all requests
  • WithDefaultQuery(key, value string) - Add a default query parameter to all requests
  • WithDefaultQueryParams(params map[string]string) - Add default query parameters to all requests

Project Structure

perplexity-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

Roadmap

v0.1.0 - Initial Development (2025-01-18)

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.

v1.0.0 - Production Ready (2025-11-18)

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.

v1.0.1 - Enhanced Web Search (2025-11-19)

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.

v1.0.2 - Async Chat Completions (2025-12-15)

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.

v1.0.3 - Packaging Fix (2025-12-15)

Re-tagged release to fix packaging issues.

v1.0.4 - Fix Missing Files (2025-12-18)

Fixed broken .gitignore pattern that was excluding necessary files from the repository.

v1.2.0 - Request Options & Raw Responses (2026-05-02) (Current)

Added the perplexity/api package, raw response helper methods across chat, search, responses, embeddings, contextualized embeddings, async chat, and browser sessions, Client.Copy(), Client.WithOptions(), default query and header options, per-request options across public resources, streaming request option support, and missing search last-updated filter fields.

Future Plans

Community feedback and improvements, additional API features as Perplexity releases them, performance optimizations, enhanced documentation and examples, bug fixes and stability improvements.

Development

Prerequisites

  • Go 1.21 or later
  • Perplexity API key

Building

# Clone the repository
git clone https://github.com/ZaguanLabs/perplexity-go.git
cd perplexity-go

# Build
go build ./...

# Run tests
go test ./...

Running Examples

# 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.go

Contributing

Contributions 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.

Ready to Try Perplexity Go SDK?

Check out the repository for full documentation and examples.