A lightweight Go library for interacting with the Perplexity AI API, focusing on the chat completion endpoint.
Find a file
dependabot[bot] afaccf1a2d
Some checks failed
Generate coverage badges / generate-badges (push) Has been cancelled
linter / linter (push) Has been cancelled
Tests / test (push) Has been cancelled
Vulnerability Scan / Run govulncheck (push) Has been cancelled
chore(deps): bump actions/checkout from 5 to 6 (#116)
Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-01 23:02:00 +01:00
.github chore(deps): bump actions/checkout from 5 to 6 (#116) 2025-12-01 23:02:00 +01:00
.vscode feat: add support for image filters to CompletionRequest and Images to CompleteResponse (#73) 2025-07-15 22:06:33 +02:00
cmd docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
.gitignore ci: refactor (#96) 2025-09-06 21:56:53 +02:00
.golangci.yml chore: update golangci-lint to version 2.2.2 and adjust linting configurations (#87) 2025-07-31 21:19:42 +02:00
.goreleaser.yml chore: remove LinkedIn announcement configuration from goreleaser (#100) 2025-09-21 10:42:09 +02:00
CODE_OF_CONDUCT.md feat: add CODEOWNERS, SECURITY, SUPPORT, and CODE_OF_CONDUCT documents (#23) 2025-02-06 20:54:03 +01:00
CODEOWNERS feat: add CODEOWNERS, SECURITY, SUPPORT, and CODE_OF_CONDUCT documents (#23) 2025-02-06 20:54:03 +01:00
CONTRIBUTING.md feat: add CODEOWNERS, SECURITY, SUPPORT, and CODE_OF_CONDUCT documents (#23) 2025-02-06 20:54:03 +01:00
go.mod chore(deps): bump github.com/go-playground/validator/v10 (#113) 2025-11-02 08:01:34 +01:00
go.sum chore(deps): bump github.com/go-playground/validator/v10 (#113) 2025-11-02 08:01:34 +01:00
LICENSE Initial commit 2024-06-28 11:45:40 +02:00
perplexity.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_async.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_async_request.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_async_test.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_async_utils.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_async_utils_test.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_error.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_error_test.go 50 add golangci lint (#58) 2025-06-01 22:10:11 +02:00
perplexity_image.go 79 add async api support for sonar deep research (#107) 2025-09-21 21:58:20 +02:00
perplexity_image_test.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_msg.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_msg_test.go feat: implement multimodal message support with image processing and validation (#106) 2025-09-21 14:25:11 +02:00
perplexity_request.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_request_test.go feat: update date filter fields for API compliance and deprecate old filters (#105) 2025-09-21 13:14:18 +02:00
perplexity_request_validator.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_request_validator_test.go feat: update date filter fields for API compliance and deprecate old filters (#105) 2025-09-21 13:14:18 +02:00
perplexity_response.go feat: add cost structure to usage and corresponding tests (#99) 2025-09-21 10:37:07 +02:00
perplexity_response_test.go feat: add cost structure to usage and corresponding tests (#99) 2025-09-21 10:37:07 +02:00
perplexity_search_benchmark_test.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_search_compliance_test.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_search_integration_test.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_search_request.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_search_request_test.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_search_response.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_search_response_test.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_search_validator.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_search_validator_test.go docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
perplexity_test.go feat: add search mode option to CompletionRequest and update related tests (#83) 2025-07-17 22:14:10 +02:00
README.md docs(search): add comprehensive Search API documentation (#112) 2025-10-30 01:14:54 +01:00
SECURITY.md feat: add CODEOWNERS, SECURITY, SUPPORT, and CODE_OF_CONDUCT documents (#23) 2025-02-06 20:54:03 +01:00
SUPPORT.md feat: add CODEOWNERS, SECURITY, SUPPORT, and CODE_OF_CONDUCT documents (#23) 2025-02-06 20:54:03 +01:00
Taskfile.yml chore: rename linter task to lint in workflow and Taskfile 2025-11-26 21:12:40 +01:00

Perplexity API Go Client

Go Report Card coverage GoDoc CI Release golangci-lint

A lightweight Go library for interacting with the Perplexity AI API, supporting both chat completions and the Search API.

Features

  • Simple and easy-to-use interface for chat completion requests
  • Search API support for direct access to Perplexity's real-time web index
  • Supports all Perplexity models, including online LLMs
  • Handles authentication and API key management
  • Comprehensive request validation
  • Concurrent request support with thread-safe operations
  • Context-aware request handling with cancellation support

If you need a CLI tool to interact with the API, check out the pplx project.

Due to AI models that change regulary, only the default model will be handled for version >=2.5.0. Using the WithModel, you're able to specify the model you want to use. The default model will always be maintained up to date. Now the library should be stable.

If you have access to the beta version of the API I'm interesred to get some informations to hanle image generation. Please contact me.

Installation

To install the library, use go get:

go get github.com/sgaunet/perplexity-go/v2

Usage

Here's a quick example of how to use the library:

package main

import (
  "fmt"
  "os"

  "github.com/sgaunet/perplexity-go/v2"
)

func main() {
client := perplexity.NewClient(os.Getenv("PPLX_API_KEY"))
  msg := []perplexity.Message{
    {
      Role:    "user",
      Content: "Wat's the capital of France?",
    },
  }
  req := perplexity.NewCompletionRequest(perplexity.WithMessages(msg), perplexity.WithReturnImages(true))
  err := req.Validate()
  if err != nil {
    fmt.Printf("Error: %v\n", err)
    os.Exit(1)
  }

  res, err := client.SendCompletionRequest(req)
  if err != nil {
    fmt.Printf("Error: %v\n", err)
    os.Exit(1)
  }

  fmt.Println(res.GetLastContent())
}

Search API

The Perplexity Search API provides direct access to Perplexity's real-time web index without the generative LLM layer, returning raw ranked search results with structured snippets.

Features

  • Direct web search without AI generation layer
  • Single query or multi-query search support
  • Structured results with titles, URLs, snippets, and scores
  • Optional image results
  • Domain filtering
  • Country-specific results

Pricing

The Search API is priced at $5 per 1,000 requests (as of 2024), separate from chat completion pricing.

Basic Search Usage

package main

import (
    "fmt"
    "os"

    "github.com/sgaunet/perplexity-go/v2"
)

func main() {
    client := perplexity.NewClient(os.Getenv("PPLX_API_KEY"))

    // Simple search
    req := perplexity.NewSearchRequest("golang best practices")

    resp, err := client.SendSearchRequest(req)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        os.Exit(1)
    }

    // Print results
    for i, result := range resp.Results {
        fmt.Printf("%d. %s\n", i+1, result.Title)
        fmt.Printf("   URL: %s\n", result.URL)
        if result.Snippet != nil {
            fmt.Printf("   Snippet: %s\n", *result.Snippet)
        }
    }
}

Advanced Search Options

// Search with all options
req := perplexity.NewSearchRequest(
    "machine learning papers",
    perplexity.WithSearchMaxResults(10),
    perplexity.WithSearchReturnImages(true),
    perplexity.WithSearchReturnSnippets(true),
    perplexity.WithSearchCountry("US"),
    perplexity.WithSearchDomains([]string{"arxiv.org", "github.com"}),
)

resp, err := client.SendSearchRequest(req)
// Search multiple queries at once
queries := []string{
    "Go programming language",
    "Rust programming language",
    "Python programming language",
}

req := perplexity.NewSearchRequest(queries)
resp, err := client.SendSearchRequest(req)

Request Validation

// Validate search request before sending
validator := perplexity.NewSearchRequestValidator()
if err := validator.ValidateSearchRequest(req); err != nil {
    fmt.Printf("Validation error: %v\n", err)
    return
}

Context Support

import "context"

// With timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

resp, err := client.SendSearchRequestWithContext(ctx, req)

Search vs Chat Completions

Feature Search API Chat Completions
Purpose Raw web search results AI-generated responses
Response Ranked list of URLs with snippets Natural language text
Use Case Research, data gathering Q&A, summarization, analysis
Pricing $5 per 1K requests Variable by model
Latency Lower (no generation) Higher (includes generation)

Documentation

For detailed documentation and more examples, please refer to the GoDoc page.

Max Tokens

  • General Use Cases: For most general-purpose applications, setting max_tokens to 4000 is a good starting point. This is because many Perplexity models, like the default sonar model, can generate responses up to this limit (It's the default value in this library).

  • Long-Form Content: If you are working with long-form content or need more extensive responses, you might consider models like sonar-pro, which can handle larger outputs. However, the maximum output tokens for such models might still be capped at 8,000 tokens.

  • Model-Specific Limits: Ensure that your chosen model supports the max_tokens value you set. For example, some models might have a maximum context window or output limit that you should not exceed.

  • Performance Considerations: Higher max_tokens values can increase response time and computational resources. Therefore, balance between the need for detailed responses and performance efficiency.

License

This project is licensed under the MIT License - see the LICENSE file for details.