> ## Documentation Index
> Fetch the complete documentation index at: https://docs.perplexity.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Sonar API

> Get started with Perplexity's Sonar API for web-grounded AI responses. Make your first API call in minutes.

## Overview

Perplexity's Sonar API provides web-grounded AI responses with support for streaming, tools, search options, and more. You can use it with OpenAI-compatible client libraries or our native SDKs for type safety and enhanced features.

Use the Sonar API when you need web search capabilities built-in, streaming responses, or Perplexity's Sonar models. For structured outputs and third-party models, use our [Agent API](/docs/agent-api/quickstart).

<Tip>
  Keep using your existing OpenAI SDKs to get started fast; switch to our [native SDKs](/docs/sdk/overview) later as needed.
</Tip>

## Installation

Install the SDK for your preferred language:

<CodeGroup>
  ```bash Python theme={null}
  pip install perplexityai
  ```

  ```bash Typescript theme={null}
  npm install @perplexity-ai/perplexity_ai
  ```

  ```bash OpenAI Python (Compatible) theme={null}
  pip install openai
  ```

  ```bash OpenAI Typescript (Compatible) theme={null}
  npm install openai
  ```
</CodeGroup>

## Authentication

Set your API key as an environment variable. The SDK will automatically read it:

<Tabs>
  <Tab title="macOS/Linux">
    ```bash theme={null}
    export PERPLEXITY_API_KEY="your_api_key_here"
    ```
  </Tab>

  <Tab title="Windows">
    ```powershell theme={null}
    setx PERPLEXITY_API_KEY "your_api_key_here"
    ```
  </Tab>
</Tabs>

<Info>
  All SDK examples below automatically use the `PERPLEXITY_API_KEY` environment variable. You can also pass the key explicitly if needed.
</Info>

## Generating an API Key

<Card title="Get your Perplexity API Key" icon="key" arrow="True" horizontal="True" iconType="solid" cta="Click here" href="https://console.perplexity.ai">
  Navigate to the **API Keys** tab in the API Portal and generate a new key.
</Card>

<Note>
  **OpenAI SDK Compatible:** Perplexity's API supports the OpenAI Chat Completions format. You can use OpenAI client libraries by pointing to our endpoint.
</Note>

## Basic Usage

### Non-Streaming Request

<CodeGroup>
  ```python Python SDK theme={null}
  from perplexity import Perplexity

  client = Perplexity()

  completion = client.chat.completions.create(
      model="sonar-pro",
      messages=[
          {"role": "user", "content": "What are the latest developments in quantum computing?"}
      ]
  )

  print(completion.choices[0].message.content)
  ```

  ```typescript Typescript SDK theme={null}
  import Perplexity from '@perplexity-ai/perplexity_ai';

  const client = new Perplexity();

  const completion = await client.chat.completions.create({
      model: "sonar-pro",
      messages: [
          { role: "user", content: "What are the latest developments in quantum computing?" }
      ],
  });

  console.log(completion.choices[0].message.content);
  ```

  ```python OpenAI Python SDK theme={null}
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ.get("PERPLEXITY_API_KEY"),
      base_url="https://api.perplexity.ai"
  )

  resp = client.chat.completions.create(
      model="sonar-pro",
      messages=[
          {"role": "user", "content": "What are the latest developments in quantum computing?"}
      ]
  )
  print(resp.choices[0].message.content)
  ```

  ```typescript OpenAI Typescript SDK theme={null}
  import OpenAI from 'openai';

  const client = new OpenAI({
      apiKey: process.env.PERPLEXITY_API_KEY,
      baseURL: "https://api.perplexity.ai"
  });

  const resp = await client.chat.completions.create({
      model: "sonar-pro",
      messages: [
          { role: "user", content: "What are the latest developments in quantum computing?" }
      ],
  });
  console.log(resp.choices[0].message.content);
  ```

  ```bash cURL theme={null}
  curl https://api.perplexity.ai/v1/sonar \
    -H "Authorization: Bearer $PERPLEXITY_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "sonar-pro",
      "messages": [
        {
          "role": "user",
          "content": "What are the latest developments in quantum computing?"
        }
      ]
    }' | jq
  ```
</CodeGroup>

### Streaming Response

<CodeGroup>
  ```python Python SDK theme={null}
  from perplexity import Perplexity

  client = Perplexity()

  stream = client.chat.completions.create(
      model="sonar-pro",
      messages=[
          {"role": "user", "content": "What are the most popular open-source alternatives to OpenAI's GPT models?"}
      ],
      stream=True
  )

  for chunk in stream:
      if chunk.choices[0].delta.content:
          print(chunk.choices[0].delta.content, end="")
  ```

  ```typescript Typescript SDK theme={null}
  import Perplexity from '@perplexity-ai/perplexity_ai';

  const client = new Perplexity();

  const stream = await client.chat.completions.create({
      model: "sonar-pro",
      messages: [
          { role: "user", content: "What are the most popular open-source alternatives to OpenAI's GPT models?" }
      ],
      stream: true,
  });

  for await (const chunk of stream) {
      if (chunk.choices[0].delta.content) {
          process.stdout.write((chunk.choices[0]?.delta?.content ?? '') as string);
      }
  }
  ```

  ```bash cURL theme={null}
  curl https://api.perplexity.ai/v1/sonar \
    -H "Authorization: Bearer $PERPLEXITY_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "sonar-pro",
      "messages": [
        {
          "role": "user",
          "content": "What are the most popular open-source alternatives to OpenAI'\''s GPT models?"
        }
      ],
      "stream": true
    }'
  ```
</CodeGroup>

<Info title="Complete Streaming Guide" href="/docs/agent-api/output-control#streaming-responses">
  For a full guide on streaming, including parsing, error handling, citation management, and best practices, see our [Agent API streaming guide](/docs/agent-api/output-control#streaming-responses).
</Info>

## Response Structure

Sonar API responses follow an OpenAI-compatible format:

```json theme={null}
{
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "model": "sonar-pro",
    "created": 1234567890,
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "Recent developments in quantum computing include advances in error correction, new qubit architectures, and progress toward fault-tolerant systems..."
            },
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 14,
        "completion_tokens": 287,
        "total_tokens": 301
    }
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Agent API" icon="code-circle" href="/docs/agent-api/quickstart">
    Need structured outputs or third-party models? Check out the Agent API.
  </Card>

  <Card title="Search API" icon="search" href="/docs/search/quickstart">
    Get raw search results with the Search API.
  </Card>

  <Card title="Sonar API Features" icon="book" href="/docs/sonar/features">
    Complete guide to the Sonar API with advanced features and examples.
  </Card>

  <Card title="Models" icon="brain" href="/docs/sonar/models">
    Explore available Sonar models and their capabilities.
  </Card>

  <Card title="API Reference" icon="code-circle" href="/api-reference/sonar-post">
    View complete endpoint documentation and parameters.
  </Card>

  <Card title="Search Filters" icon="search" href="/docs/sonar/filters#search-control">
    Learn how to control search behavior with filters and parameters.
  </Card>
</CardGroup>

<Info>
  Need help? Check out our [community](https://community.perplexity.ai) for support and discussions with other developers.
</Info>
