Community MaintainedSDK • Go • v1.0.4

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

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, and enhanced image results (v1.0.1+).

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. Enable AI to execute actions.

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

Clean, extensible API design following Go best practices. Flexible configuration with option functions.

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 including temperature, top_p, max_tokens, presence/frequency penalties, and more.

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 (v1.0.1+)

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

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"),
)

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

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) (Current)

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

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.