Skip to content

Commit b35d971

Browse files
authored
docs(search): add comprehensive Search API documentation (#112)
* feat(search): add Perplexity Search API support Implement direct access to Perplexity's real-time web index via Search API, providing raw ranked search results without the generative LLM layer. Core features: - SearchRequest with functional options pattern (WithSearchMaxResults, etc.) - Support for single and multi-query searches - SearchResponse with result items, images, snippets, scores - SearchRequestValidator with comprehensive validation - Complete test coverage for request, response, and validation - Working example demonstrating simple, advanced, and multi-query searches API endpoint: https://api.perplexity.ai/search Pricing: $5 per 1K requests (separate from chat completions) * style: improve code formatting and alignment - Align struct field indentation across multiple files - Fix whitespace alignment in switch case comments - Add missing newlines at end of files - Improve code readability with consistent formatting No functional changes. * test(search): add comprehensive test suite for Search API Add extensive test coverage including benchmarks, compliance tests, integration tests, and edge case validation. Test additions: - Benchmark tests for request marshaling performance - API compliance tests verifying specification adherence - Integration tests for real API interactions (require PPLX_API_KEY) - Extended validator tests for edge cases (unicode, special chars, long strings) Total: 1,434 lines of new test coverage * docs(search): add comprehensive Search API documentation Update README and add example documentation covering Search API features, usage patterns, and comparison with chat completions. Changes: - Add Search API section to main README with features and pricing - Include basic, advanced, and multi-query search examples - Add comparison table: Search API vs Chat Completions - Create detailed search-example README with build/run instructions - Document all search options and validation patterns - Add context support examples
1 parent efc2d9f commit b35d971

29 files changed

+3174
-111
lines changed

README.md

Lines changed: 125 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,17 @@
77
[![Release](https://github.com/sgaunet/perplexity-go/actions/workflows/release.yml/badge.svg)](https://github.com/sgaunet/perplexity-go/actions/workflows/release.yml)
88
[![golangci-lint](https://github.com/sgaunet/perplexity-go/actions/workflows/linter.yml/badge.svg)](https://github.com/sgaunet/perplexity-go/actions/workflows/linter.yml)
99

10-
A lightweight Go library for interacting with the [Perplexity AI API](https://docs.perplexity.ai/reference/post_chat_completions), focusing on the chat completion endpoint.
10+
A lightweight Go library for interacting with the [Perplexity AI API](https://docs.perplexity.ai/reference/post_chat_completions), supporting both chat completions and the Search API.
1111

12-
Features
12+
## Features
1313

14-
Simple and easy-to-use interface for making chat completion requests
15-
Supports all Perplexity models, including online LLMs
16-
Handles authentication and API key management
17-
Provides convenient methods for common operations
14+
* Simple and easy-to-use interface for chat completion requests
15+
* **Search API support** for direct access to Perplexity's real-time web index
16+
* Supports all Perplexity models, including online LLMs
17+
* Handles authentication and API key management
18+
* Comprehensive request validation
19+
* Concurrent request support with thread-safe operations
20+
* Context-aware request handling with cancellation support
1821

1922
If you need a **CLI tool** to interact with the API, check out the [pplx](https://github.com/sgaunet/pplx) project.
2023

@@ -70,9 +73,124 @@ client := perplexity.NewClient(os.Getenv("PPLX_API_KEY"))
7073
}
7174
```
7275

76+
## Search API
77+
78+
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.
79+
80+
### Features
81+
82+
* Direct web search without AI generation layer
83+
* Single query or multi-query search support
84+
* Structured results with titles, URLs, snippets, and scores
85+
* Optional image results
86+
* Domain filtering
87+
* Country-specific results
88+
89+
### Pricing
90+
91+
The Search API is priced at **$5 per 1,000 requests** (as of 2024), separate from chat completion pricing.
92+
93+
### Basic Search Usage
94+
95+
```go
96+
package main
97+
98+
import (
99+
"fmt"
100+
"os"
101+
102+
"github.com/sgaunet/perplexity-go/v2"
103+
)
104+
105+
func main() {
106+
client := perplexity.NewClient(os.Getenv("PPLX_API_KEY"))
107+
108+
// Simple search
109+
req := perplexity.NewSearchRequest("golang best practices")
110+
111+
resp, err := client.SendSearchRequest(req)
112+
if err != nil {
113+
fmt.Printf("Error: %v\n", err)
114+
os.Exit(1)
115+
}
116+
117+
// Print results
118+
for i, result := range resp.Results {
119+
fmt.Printf("%d. %s\n", i+1, result.Title)
120+
fmt.Printf(" URL: %s\n", result.URL)
121+
if result.Snippet != nil {
122+
fmt.Printf(" Snippet: %s\n", *result.Snippet)
123+
}
124+
}
125+
}
126+
```
127+
128+
### Advanced Search Options
129+
130+
```go
131+
// Search with all options
132+
req := perplexity.NewSearchRequest(
133+
"machine learning papers",
134+
perplexity.WithSearchMaxResults(10),
135+
perplexity.WithSearchReturnImages(true),
136+
perplexity.WithSearchReturnSnippets(true),
137+
perplexity.WithSearchCountry("US"),
138+
perplexity.WithSearchDomains([]string{"arxiv.org", "github.com"}),
139+
)
140+
141+
resp, err := client.SendSearchRequest(req)
142+
```
143+
144+
### Multi-Query Search
145+
146+
```go
147+
// Search multiple queries at once
148+
queries := []string{
149+
"Go programming language",
150+
"Rust programming language",
151+
"Python programming language",
152+
}
153+
154+
req := perplexity.NewSearchRequest(queries)
155+
resp, err := client.SendSearchRequest(req)
156+
```
157+
158+
### Request Validation
159+
160+
```go
161+
// Validate search request before sending
162+
validator := perplexity.NewSearchRequestValidator()
163+
if err := validator.ValidateSearchRequest(req); err != nil {
164+
fmt.Printf("Validation error: %v\n", err)
165+
return
166+
}
167+
```
168+
169+
### Context Support
170+
171+
```go
172+
import "context"
173+
174+
// With timeout
175+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
176+
defer cancel()
177+
178+
resp, err := client.SendSearchRequestWithContext(ctx, req)
179+
```
180+
181+
### Search vs Chat Completions
182+
183+
| Feature | Search API | Chat Completions |
184+
|---------|------------|------------------|
185+
| **Purpose** | Raw web search results | AI-generated responses |
186+
| **Response** | Ranked list of URLs with snippets | Natural language text |
187+
| **Use Case** | Research, data gathering | Q&A, summarization, analysis |
188+
| **Pricing** | $5 per 1K requests | Variable by model |
189+
| **Latency** | Lower (no generation) | Higher (includes generation) |
190+
73191
## Documentation
74192

75-
For detailed documentation and more examples, please refer to the GoDoc page.
193+
For detailed documentation and more examples, please refer to the [GoDoc page](https://godoc.org/github.com/sgaunet/perplexity-go/v2).
76194

77195
## Max Tokens
78196

cmd/async-completion/main.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,10 @@ func main() {
8787
// Configure custom polling options
8888
opts := &perplexity.AsyncPollingOptions{
8989
InitialInterval: 3 * time.Second, // Start with 3-second intervals
90-
MaxInterval: 30 * time.Second, // Cap at 30 seconds
91-
BackoffMultiplier: 1.5, // Gradual backoff
92-
MaxWaitTime: 10 * time.Minute, // Total timeout
93-
JitterEnabled: true, // Add randomness to avoid thundering herd
90+
MaxInterval: 30 * time.Second, // Cap at 30 seconds
91+
BackoffMultiplier: 1.5, // Gradual backoff
92+
MaxWaitTime: 10 * time.Minute, // Total timeout
93+
JitterEnabled: true, // Add randomness to avoid thundering herd
9494
}
9595

9696
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
@@ -247,4 +247,4 @@ func exampleManualPolling(client *perplexity.Client, jobID string) {
247247
}
248248

249249
fmt.Println("✅ Manual polling example completed!")
250-
}
250+
}

cmd/basic-completion/main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func main() {
3737
req := perplexity.NewCompletionRequest(
3838
perplexity.WithMessages(msg),
3939
perplexity.WithWebSearchOptions(webSearchOpts),
40-
perplexity.WithSearchMode("web"), // Use "web" or "academic" mode
40+
perplexity.WithSearchMode("web"), // Use "web" or "academic" mode
4141
perplexity.WithReturnRelatedQuestions(true), // Enable related questions
4242
)
4343

@@ -98,4 +98,4 @@ func main() {
9898
fmt.Printf("%d. %s\n", i+1, question)
9999
}
100100
}
101-
}
101+
}

cmd/image-search/main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ func main() {
2525
// Create a request with image return enabled
2626
req := perplexity.NewCompletionRequest(
2727
perplexity.WithMessages(msg),
28-
perplexity.WithReturnImages(true), // Enable image returns
28+
perplexity.WithReturnImages(true), // Enable image returns
2929
perplexity.WithSearchRecencyFilter(""), // Clear default recency filter (incompatible with images)
3030
)
3131

@@ -75,4 +75,4 @@ func main() {
7575
fmt.Printf("%d. %s\n", i+1, c)
7676
}
7777
}
78-
}
78+
}

0 commit comments

Comments
 (0)