Skip to content

Repository files navigation

Perplexity Go SDK (Unofficial)

Go Reference Go Report Card License

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.

Why Use This SDK?

  • πŸš€ 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

Features

Core Capabilities

  • 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

Developer Experience

  • Context-Aware: All methods accept context.Context for 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

Installation

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

Quick Start

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

Async Chat Completions

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

Configuration

API Key

The API key can be provided in two ways:

  1. Direct parameter:
client, err := perplexity.NewClient("your-api-key")
  1. Environment variable:
export PERPLEXITY_API_KEY="your-api-key"
client, err := perplexity.NewClient("") // Reads from PERPLEXITY_API_KEY

Client Options

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

Error Handling

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 retryable
  • IsRateLimitError(err error) bool - Check for rate limit errors
  • IsAuthenticationError(err error) bool - Check for auth errors
  • IsTimeoutError(err error) bool - Check for timeout errors

Requirements

Project Resources

Related Links

Support

This is an unofficial, community-maintained project. For issues with this SDK:

For Perplexity API support, please contact Perplexity AI directly.

License

Apache 2.0 - See LICENSE for details.

Acknowledgments

This SDK was built with reference to the official Python SDK to ensure API compatibility and feature parity.

About

Unofficial Perplexity SDK in Go

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages