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

# OpenAI SDK Compatibility

> Use OpenAI SDKs with the Sonar API by changing the base URL and API key

## Overview

Perplexity's Sonar API is fully compatible with OpenAI's Chat Completions format. You can use your existing OpenAI client libraries with the Sonar API by simply changing the base URL and providing your Perplexity API key.

<Info>
  **Endpoint Note:** Perplexity's canonical Sonar API endpoint is `POST /v1/sonar`. For OpenAI SDK compatibility, `POST /chat/completions` is also accepted as an alias. The OpenAI SDK automatically routes `client.chat.completions.create()` to `/chat/completions`, which Perplexity handles seamlessly. No SDK changes are needed beyond setting the base URL.
</Info>

<Tip>
  **We recommend using the [Perplexity SDK](/docs/sdk/overview)** for the best experience with full type safety, enhanced features, and preset support. Use OpenAI SDKs if you're already integrated and need drop-in compatibility.
</Tip>

## Quick Start

Use the OpenAI SDK with Perplexity's Sonar API:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    from openai import OpenAI

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

    completion = client.chat.completions.create(
        model="sonar-pro",
        messages=[
            {"role": "user", "content": "Explain the underlying physics of magnetic confinement fusion and the role of the Lawson criterion."}
        ]
    )

    print(completion.choices[0].message.content)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import OpenAI from 'openai';

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

    const completion = await client.chat.completions.create({
      model: "sonar-pro",
      messages: [
        { role: "user", content: "Explain the underlying physics of magnetic confinement fusion and the role of the Lawson criterion." }
      ]
    });

    console.log(completion.choices[0].message.content);
    ```
  </Tab>
</Tabs>

<Accordion title="Response">
  ```json theme={null}
  {
    "id": "258a700e-40fd-4e8d-956b-351e6ebc7f37",
    "choices": [
      {
        "delta": {
          "content": "",
          "role": "assistant",
          "reasoning_steps": null,
          "tool_call_id": null,
          "tool_calls": null
        },
        "index": 0,
        "message": {
          "content": "Magnetic confinement fusion uses strong magnetic fields to trap a very hot, ionized gas (plasma) so that light nuclei collide and fuse faster than the energy is lost, and the Lawson criterion quantifies the minimum combination of plasma density, temperature, and confinement time required for this to produce net energy. The core physics is charged-particle motion in magnetic fields (guiding centers following field lines plus gyration and drifts), collective plasma stability, and energy balance; the Lawson criterion is the formal expression of that energy balance.\n\n---\n\n### 1. Why fusion needs confinement\n\nFor deuterium–tritium (D–T) fusion to occur at an appreciable rate, the plasma must reach temperatures of order \\(10^8\\) K (∼10 keV), hotter than the Sun’s core, so that nuclei can overcome the Coulomb repulsion and get close enough for the strong nuclear force to fuse them.[1][4][6] At these temperatures:\n\n- All atoms are ionized → a **plasma** of electrons and ions.[1][4][6]  \n- No solid material can touch the plasma; it would vaporize instantly.[1][4]\n\nSo fusion requires:\n\n- **Heating** the fuel to fusion temperatures.  \n- **Confining** it long enough and dense enough that many fusion reactions occur before the energy escapes.[4][6]\n\nIn stars, gravity provides confinement; in labs, strong magnetic fields are used instead.[4][6]\n\n---\n\n### 2. Single-particle motion: how magnetic fields confine charges\n\nThe basic building block is the Lorentz force on a charged particle in a magnetic field: \\(\\mathbf{F} = q\\,\\mathbf{v} \\times \\mathbf{B}\\).\n\nFrom this follow key motions (as shown in standard plasma-physics treatments and educational material):[2][3][6]\n\n- A component of velocity **perpendicular** to \\(\\mathbf{B}\\) causes **circular gyro-motion** around the field line at the Larmor radius.  \n- A component **parallel** to \\(\\mathbf{B}\\) feels no magnetic force and moves freely along the field.[2]  \n\nCombined, ions and electrons **spiral** along magnetic field lines: they are tightly bound across the field but free to move along it.[2][3][6]\n\nThis leads to the confinement idea:\n\n- Shape the magnetic field so that **field lines are closed** (e.g., in a torus), forming a “magnetic bottle.”  \n- Particles spiral around these closed lines, remaining away from material walls.[1][3][6]\n\nThe stronger the magnetic field:\n\n- The **smaller** the Larmor radius.  \n- The **slower** cross-field drifts and diffusion.  \n- The **better** the confinement.[2][3]\n\n---\n\n### 3. From single particles to plasma: collective and MHD behavior\n\nAt fusion-relevant densities, the plasma’s own currents and charges significantly modify the externally applied magnetic field, and the medium must be treated collectively.[2][3][7] This is described by **magnetohydrodynamics (MHD)**:\n\n- The plasma behaves like a conducting fluid embedded in magnetic field lines.  \n- Magnetic field lines are often described as “frozen in” to the plasma: fluid elements move along field lines, and dragging the plasma across the field tends to drag the lines with it.[2]\n\nKey implications for magnetic confinement:\n\n- **Pressure balance:** Plasma pressure pushes outward, magnetic pressure and tension pull inward. Stable confinement demands that the magnetic field be strong enough and appropriately shaped to counter plasma pressure and currents.[3][7]  \n- **Instabilities:** Certain pressure/current configurations are unstable (e.g., kink, ballooning, interchange instabilities), leading to bulging, twisting, or breaking of confined regions and degraded confinement.[2][3][6][7]  \n- **Turbulence:** Small-scale fluctuations and turbulence cause enhanced transport of heat and particles across field lines, reducing the effective confinement time below what classical single-particle theory would predict.[2][3][7]\n\nDesigning a successful magnetic confinement system is largely about **finding magnetic geometries and operating regimes that avoid or tame these instabilities** and minimize turbulent transport.[3][6][7]\n\n---\n\n### 4. Magnetic geometry in practice: toroidal devices\n\nBecause particles stream freely along field lines, the field lines themselves must not intersect walls, which leads naturally to **toroidal (doughnut-shaped)** configurations:[1][5][6]\n\n- **Tokamak:**  \n  - Strong toroidal field from external coils.  \n  - Large plasma current generates a poloidal field, twisting field lines into helical paths, improving confinement and stability.[5][6][7]  \n- **Stellarator:**  \n  - Uses 3D-shaped external coils to create the required helical fields; does not rely on a large plasma current, which avoids some current-driven instabilities but demands complex coil engineering.[5][6][7]\n\nTwist in the field lines helps cancel or average out systematic drifts that would otherwise move particles to the wall.[2][6]\n\nOther configurations (mirror machines, reversed-field pinches, spherical tokamaks, etc.) explore different ways of shaping \\(\\mathbf{B}\\), but modern mainstream MCF focuses on tokamaks and stellarators.[5][6][7]\n\n---\n\n### 5. Energy balance and the Lawson criterion\n\nTo generate net power, the fusion plasma must satisfy an **energy balance condition**: fusion power produced must equal or exceed total power lost (radiation, conduction, convection, particle escape).[6][7]\n\nFor a D–T plasma, this condition is commonly expressed as the **Lawson criterion**, which relates:\n\n- **n** – plasma particle density  \n- **T** – temperature  \n- **τ\\_E** – energy confinement time (a measure of how long energy stays in the plasma before being lost)\n\nIn one common form, the Lawson criterion requires that the **triple product** \\(n T \\tau_E\\) exceed a critical value for ignition (self-sustaining fusion without external heating) or for net energy gain.[6][7]\n\nConceptually:\n\n- Fusion power density \\(\\propto n^2 \\langle \\sigma v \\rangle\\), where \\(\\langle \\sigma v \\rangle\\) increases with temperature up to an optimum.  \n- Loss power density \\(\\propto \\frac{3 n T}{\\tau_E}\\) (roughly, energy per particle divided by confinement time).  \n- Setting fusion power ≥ loss power gives a condition on \\(n T \\tau_E\\).[6][7]\n\nFor D–T at ∼10–20 keV, the required triple product is on the order of \\(10^{21}\\,\\text{keV·s·m}^{-3}\\) (order-of-magnitude; exact numbers depend on detailed assumptions), and modern large tokamaks operate near or approaching this regime in brief pulses.[6][7]\n\n**Role of the Lawson criterion in MCF:**\n\n- It defines the **minimum combination** of density, temperature, and confinement time needed for practical fusion.  \n- Because the temperature window is fairly constrained by fusion cross sections, MCF devices mostly trade off **density versus confinement time**:  \n  - Magnetic confinement operates at relatively **low density** and **long τ\\_E** (milliseconds to seconds or longer).  \n  - Inertial confinement operates at very **high density** and extremely **short τ\\_E** (nanoseconds).  \n- It provides a quantitative **performance metric**: experiments report their achieved \\(n T \\tau_E\\) and compare to the Lawson threshold for ignition or for specific gain factors.[6][7]\n\nIn short, the Lawson criterion translates “good enough confinement” into a precise inequality involving measurable plasma parameters.\n\n---\n\n### 6. Why magnetic confinement is hard\n\nLinking the physics pieces:\n\n- **Single-particle physics** explains why strong magnetic fields can, in principle, confine hot plasmas away from walls.  \n- **Collective and MHD physics** explain why real plasmas develop currents, instabilities, and turbulence that degrade that ideal confinement.  \n- The **Lawson criterion** states the quantitative target: despite all losses, achieve a triple product high enough that fusion heating balances or exceeds losses.\n\nMajor technical and physics challenges in MCF include:[3][4][6][7]\n\n- Achieving and sustaining **multi-tesla magnetic fields** with high precision.  \n- Controlling **MHD instabilities** and turbulent transport to attain long τ\\_E.  \n- Handling **extreme heat and particle loads** where confined plasma meets material surfaces (divertors, first wall).[3]  \n- Integrating materials, superconducting magnets, heating systems, and control systems to operate reliably for long durations.[3][6][7]\n\nAll of these are pursued with the Lawson criterion in mind: improving confinement time and allowable density at a given temperature to reach or surpass the ignition and net-gain conditions.\n\nIf you’d like, I can next walk through the Lawson criterion derivation step-by-step from the energy balance equations, or compare typical Lawson targets for magnetic vs inertial confinement.",
          "role": "assistant",
          "reasoning_steps": null,
          "tool_call_id": null,
          "tool_calls": null
        },
        "finish_reason": "stop"
      }
    ],
    "created": 1779896019,
    "model": "sonar-pro",
    "citations": [
      "https://www.york.ac.uk/physics-engineering-technology/ypi/research/mcf/",
      "https://www.youtube.com/watch?v=gwOrbr8KWDs",
      "https://www.peaknano.com/blog/magnetic-confinement-fusion-explained-history-challenges-and-enabling-technologies-peak-blog",
      "https://www.energy.gov/science/doe-explainsplasma-confinement",
      "http://www.iaea.org/bulletin/magnetic-fusion-confinement-with-tokamaks-and-stellarators",
      "https://en.wikipedia.org/wiki/Magnetic_confinement_fusion",
      "http://ui.adsabs.harvard.edu/abs/2016NatPh..12..398O/abstract"
    ],
    "object": "chat.completion",
    "search_results": [
      {
        "title": "Magnetic Confinement Fusion - University of York",
        "url": "https://www.york.ac.uk/physics-engineering-technology/ypi/research/mcf/",
        "date": null,
        "last_updated": "2026-04-21",
        "snippet": "In magnetic confinement fusion (MCF), the fuel (deuterium and tritium) is heated to a temperature which is ten times hotter than the centre of the Sun.",
        "source": "web"
      },
      {
        "title": "How nuclear fusion works (3) - magnetic confinement, tokamaks ...",
        "url": "https://www.youtube.com/watch?v=gwOrbr8KWDs",
        "date": "2022-07-11",
        "last_updated": "2026-03-31",
        "snippet": ".youtube.com/watch?v=IhHsOwLdCu4 [2] J. P. Freidberg, “Plasma Physics and Fusion Energy” (CUP 2010). [3] T. F. Neiser et al., “Gyrokinetic ...",
        "source": "web"
      },
      {
        "title": "Magnetic Confinement Fusion Explained: History, Challenges, and ...",
        "url": "https://www.peaknano.com/blog/magnetic-confinement-fusion-explained-history-challenges-and-enabling-technologies-peak-blog",
        "date": "2025-12-18",
        "last_updated": "2026-05-27",
        "snippet": "The principle behind MCF is grounded in charged particle motion. Plasmas naturally follow magnetic field lines. Under the right magnetic ...",
        "source": "web"
      },
      {
        "title": "DOE Explains...Plasma Confinement - Department of Energy",
        "url": "https://www.energy.gov/science/doe-explainsplasma-confinement",
        "date": "2026-05-22",
        "last_updated": "2026-05-17",
        "snippet": "Plasma confinement refers to the containment of a plasma by various forces at the extreme conditions necessary for fusion.",
        "source": "web"
      },
      {
        "title": "Magnetic Fusion Confinement with Tokamaks and Stellarators",
        "url": "http://www.iaea.org/bulletin/magnetic-fusion-confinement-with-tokamaks-and-stellarators",
        "date": null,
        "last_updated": null,
        "snippet": "Strong magnets in the reactors keep the ions confined. Electrons are also bound by the reactors' forces and play a role in the surroundings. The magnetic forces ...",
        "source": "web"
      },
      {
        "title": "Magnetic confinement fusion - Wikipedia",
        "url": "https://en.wikipedia.org/wiki/Magnetic_confinement_fusion",
        "date": "2005-04-04",
        "last_updated": "2026-03-03",
        "snippet": "Magnetic confinement fusion (MCF) is an approach to generate thermonuclear fusion power that uses magnetic fields to confine fusion fuel in the form of a ...",
        "source": "web"
      },
      {
        "title": "Magnetic-confinement fusion - NASA ADS",
        "url": "http://ui.adsabs.harvard.edu/abs/2016NatPh..12..398O/abstract",
        "date": "1999-01-01",
        "last_updated": "2025-03-17",
        "snippet": "Here we review the basic physics underlying magnetic fusion: past achievements, present efforts and the prospects for future production of electrical energy.",
        "source": "web"
      }
    ],
    "status": null,
    "type": null,
    "usage": {
      "completion_tokens": 1917,
      "cost": {
        "input_tokens_cost": 5e-05,
        "output_tokens_cost": 0.02875,
        "total_cost": 0.03481,
        "citation_tokens_cost": null,
        "reasoning_tokens_cost": null,
        "request_cost": 0.006,
        "search_queries_cost": null
      },
      "prompt_tokens": 18,
      "total_tokens": 1935,
      "citation_tokens": null,
      "num_search_queries": null,
      "reasoning_tokens": null,
      "search_context_size": "low"
    }
  }
  ```
</Accordion>

## Configuration

### Setting Up the OpenAI SDK

Configure OpenAI SDKs to work with Perplexity by setting the `base_url` to `https://api.perplexity.ai`:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    from openai import OpenAI

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

  <Tab title="TypeScript">
    ```typescript theme={null}
    import OpenAI from 'openai';

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

<Info>
  **Important**: Use `base_url="https://api.perplexity.ai"` for the Sonar API.
</Info>

## Basic Usage

Perplexity's Sonar API is fully compatible with OpenAI's Chat Completions interface.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    from openai import OpenAI

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

    completion = client.chat.completions.create(
        model="sonar-pro",
        messages=[
            {"role": "user", "content": "Explain the underlying physics of magnetic confinement fusion and the role of the Lawson criterion."}
        ]
    )

    print(completion.choices[0].message.content)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import OpenAI from 'openai';

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

    const completion = await client.chat.completions.create({
      model: "sonar-pro",
      messages: [
        { role: "user", content: "Explain the underlying physics of magnetic confinement fusion and the role of the Lawson criterion." }
      ]
    });

    console.log(completion.choices[0].message.content);
    ```
  </Tab>
</Tabs>

<Accordion title="Response">
  ```json theme={null}
  {
    "id": "258a700e-40fd-4e8d-956b-351e6ebc7f37",
    "choices": [
      {
        "delta": {
          "content": "",
          "role": "assistant",
          "reasoning_steps": null,
          "tool_call_id": null,
          "tool_calls": null
        },
        "index": 0,
        "message": {
          "content": "Magnetic confinement fusion uses strong magnetic fields to trap a very hot, ionized gas (plasma) so that light nuclei collide and fuse faster than the energy is lost, and the Lawson criterion quantifies the minimum combination of plasma density, temperature, and confinement time required for this to produce net energy. The core physics is charged-particle motion in magnetic fields (guiding centers following field lines plus gyration and drifts), collective plasma stability, and energy balance; the Lawson criterion is the formal expression of that energy balance.\n\n---\n\n### 1. Why fusion needs confinement\n\nFor deuterium–tritium (D–T) fusion to occur at an appreciable rate, the plasma must reach temperatures of order \\(10^8\\) K (∼10 keV), hotter than the Sun’s core, so that nuclei can overcome the Coulomb repulsion and get close enough for the strong nuclear force to fuse them.[1][4][6] At these temperatures:\n\n- All atoms are ionized → a **plasma** of electrons and ions.[1][4][6]  \n- No solid material can touch the plasma; it would vaporize instantly.[1][4]\n\nSo fusion requires:\n\n- **Heating** the fuel to fusion temperatures.  \n- **Confining** it long enough and dense enough that many fusion reactions occur before the energy escapes.[4][6]\n\nIn stars, gravity provides confinement; in labs, strong magnetic fields are used instead.[4][6]\n\n---\n\n### 2. Single-particle motion: how magnetic fields confine charges\n\nThe basic building block is the Lorentz force on a charged particle in a magnetic field: \\(\\mathbf{F} = q\\,\\mathbf{v} \\times \\mathbf{B}\\).\n\nFrom this follow key motions (as shown in standard plasma-physics treatments and educational material):[2][3][6]\n\n- A component of velocity **perpendicular** to \\(\\mathbf{B}\\) causes **circular gyro-motion** around the field line at the Larmor radius.  \n- A component **parallel** to \\(\\mathbf{B}\\) feels no magnetic force and moves freely along the field.[2]  \n\nCombined, ions and electrons **spiral** along magnetic field lines: they are tightly bound across the field but free to move along it.[2][3][6]\n\nThis leads to the confinement idea:\n\n- Shape the magnetic field so that **field lines are closed** (e.g., in a torus), forming a “magnetic bottle.”  \n- Particles spiral around these closed lines, remaining away from material walls.[1][3][6]\n\nThe stronger the magnetic field:\n\n- The **smaller** the Larmor radius.  \n- The **slower** cross-field drifts and diffusion.  \n- The **better** the confinement.[2][3]\n\n---\n\n### 3. From single particles to plasma: collective and MHD behavior\n\nAt fusion-relevant densities, the plasma’s own currents and charges significantly modify the externally applied magnetic field, and the medium must be treated collectively.[2][3][7] This is described by **magnetohydrodynamics (MHD)**:\n\n- The plasma behaves like a conducting fluid embedded in magnetic field lines.  \n- Magnetic field lines are often described as “frozen in” to the plasma: fluid elements move along field lines, and dragging the plasma across the field tends to drag the lines with it.[2]\n\nKey implications for magnetic confinement:\n\n- **Pressure balance:** Plasma pressure pushes outward, magnetic pressure and tension pull inward. Stable confinement demands that the magnetic field be strong enough and appropriately shaped to counter plasma pressure and currents.[3][7]  \n- **Instabilities:** Certain pressure/current configurations are unstable (e.g., kink, ballooning, interchange instabilities), leading to bulging, twisting, or breaking of confined regions and degraded confinement.[2][3][6][7]  \n- **Turbulence:** Small-scale fluctuations and turbulence cause enhanced transport of heat and particles across field lines, reducing the effective confinement time below what classical single-particle theory would predict.[2][3][7]\n\nDesigning a successful magnetic confinement system is largely about **finding magnetic geometries and operating regimes that avoid or tame these instabilities** and minimize turbulent transport.[3][6][7]\n\n---\n\n### 4. Magnetic geometry in practice: toroidal devices\n\nBecause particles stream freely along field lines, the field lines themselves must not intersect walls, which leads naturally to **toroidal (doughnut-shaped)** configurations:[1][5][6]\n\n- **Tokamak:**  \n  - Strong toroidal field from external coils.  \n  - Large plasma current generates a poloidal field, twisting field lines into helical paths, improving confinement and stability.[5][6][7]  \n- **Stellarator:**  \n  - Uses 3D-shaped external coils to create the required helical fields; does not rely on a large plasma current, which avoids some current-driven instabilities but demands complex coil engineering.[5][6][7]\n\nTwist in the field lines helps cancel or average out systematic drifts that would otherwise move particles to the wall.[2][6]\n\nOther configurations (mirror machines, reversed-field pinches, spherical tokamaks, etc.) explore different ways of shaping \\(\\mathbf{B}\\), but modern mainstream MCF focuses on tokamaks and stellarators.[5][6][7]\n\n---\n\n### 5. Energy balance and the Lawson criterion\n\nTo generate net power, the fusion plasma must satisfy an **energy balance condition**: fusion power produced must equal or exceed total power lost (radiation, conduction, convection, particle escape).[6][7]\n\nFor a D–T plasma, this condition is commonly expressed as the **Lawson criterion**, which relates:\n\n- **n** – plasma particle density  \n- **T** – temperature  \n- **τ\\_E** – energy confinement time (a measure of how long energy stays in the plasma before being lost)\n\nIn one common form, the Lawson criterion requires that the **triple product** \\(n T \\tau_E\\) exceed a critical value for ignition (self-sustaining fusion without external heating) or for net energy gain.[6][7]\n\nConceptually:\n\n- Fusion power density \\(\\propto n^2 \\langle \\sigma v \\rangle\\), where \\(\\langle \\sigma v \\rangle\\) increases with temperature up to an optimum.  \n- Loss power density \\(\\propto \\frac{3 n T}{\\tau_E}\\) (roughly, energy per particle divided by confinement time).  \n- Setting fusion power ≥ loss power gives a condition on \\(n T \\tau_E\\).[6][7]\n\nFor D–T at ∼10–20 keV, the required triple product is on the order of \\(10^{21}\\,\\text{keV·s·m}^{-3}\\) (order-of-magnitude; exact numbers depend on detailed assumptions), and modern large tokamaks operate near or approaching this regime in brief pulses.[6][7]\n\n**Role of the Lawson criterion in MCF:**\n\n- It defines the **minimum combination** of density, temperature, and confinement time needed for practical fusion.  \n- Because the temperature window is fairly constrained by fusion cross sections, MCF devices mostly trade off **density versus confinement time**:  \n  - Magnetic confinement operates at relatively **low density** and **long τ\\_E** (milliseconds to seconds or longer).  \n  - Inertial confinement operates at very **high density** and extremely **short τ\\_E** (nanoseconds).  \n- It provides a quantitative **performance metric**: experiments report their achieved \\(n T \\tau_E\\) and compare to the Lawson threshold for ignition or for specific gain factors.[6][7]\n\nIn short, the Lawson criterion translates “good enough confinement” into a precise inequality involving measurable plasma parameters.\n\n---\n\n### 6. Why magnetic confinement is hard\n\nLinking the physics pieces:\n\n- **Single-particle physics** explains why strong magnetic fields can, in principle, confine hot plasmas away from walls.  \n- **Collective and MHD physics** explain why real plasmas develop currents, instabilities, and turbulence that degrade that ideal confinement.  \n- The **Lawson criterion** states the quantitative target: despite all losses, achieve a triple product high enough that fusion heating balances or exceeds losses.\n\nMajor technical and physics challenges in MCF include:[3][4][6][7]\n\n- Achieving and sustaining **multi-tesla magnetic fields** with high precision.  \n- Controlling **MHD instabilities** and turbulent transport to attain long τ\\_E.  \n- Handling **extreme heat and particle loads** where confined plasma meets material surfaces (divertors, first wall).[3]  \n- Integrating materials, superconducting magnets, heating systems, and control systems to operate reliably for long durations.[3][6][7]\n\nAll of these are pursued with the Lawson criterion in mind: improving confinement time and allowable density at a given temperature to reach or surpass the ignition and net-gain conditions.\n\nIf you’d like, I can next walk through the Lawson criterion derivation step-by-step from the energy balance equations, or compare typical Lawson targets for magnetic vs inertial confinement.",
          "role": "assistant",
          "reasoning_steps": null,
          "tool_call_id": null,
          "tool_calls": null
        },
        "finish_reason": "stop"
      }
    ],
    "created": 1779896019,
    "model": "sonar-pro",
    "citations": [
      "https://www.york.ac.uk/physics-engineering-technology/ypi/research/mcf/",
      "https://www.youtube.com/watch?v=gwOrbr8KWDs",
      "https://www.peaknano.com/blog/magnetic-confinement-fusion-explained-history-challenges-and-enabling-technologies-peak-blog",
      "https://www.energy.gov/science/doe-explainsplasma-confinement",
      "http://www.iaea.org/bulletin/magnetic-fusion-confinement-with-tokamaks-and-stellarators",
      "https://en.wikipedia.org/wiki/Magnetic_confinement_fusion",
      "http://ui.adsabs.harvard.edu/abs/2016NatPh..12..398O/abstract"
    ],
    "object": "chat.completion",
    "search_results": [
      {
        "title": "Magnetic Confinement Fusion - University of York",
        "url": "https://www.york.ac.uk/physics-engineering-technology/ypi/research/mcf/",
        "date": null,
        "last_updated": "2026-04-21",
        "snippet": "In magnetic confinement fusion (MCF), the fuel (deuterium and tritium) is heated to a temperature which is ten times hotter than the centre of the Sun.",
        "source": "web"
      },
      {
        "title": "How nuclear fusion works (3) - magnetic confinement, tokamaks ...",
        "url": "https://www.youtube.com/watch?v=gwOrbr8KWDs",
        "date": "2022-07-11",
        "last_updated": "2026-03-31",
        "snippet": ".youtube.com/watch?v=IhHsOwLdCu4 [2] J. P. Freidberg, “Plasma Physics and Fusion Energy” (CUP 2010). [3] T. F. Neiser et al., “Gyrokinetic ...",
        "source": "web"
      },
      {
        "title": "Magnetic Confinement Fusion Explained: History, Challenges, and ...",
        "url": "https://www.peaknano.com/blog/magnetic-confinement-fusion-explained-history-challenges-and-enabling-technologies-peak-blog",
        "date": "2025-12-18",
        "last_updated": "2026-05-27",
        "snippet": "The principle behind MCF is grounded in charged particle motion. Plasmas naturally follow magnetic field lines. Under the right magnetic ...",
        "source": "web"
      },
      {
        "title": "DOE Explains...Plasma Confinement - Department of Energy",
        "url": "https://www.energy.gov/science/doe-explainsplasma-confinement",
        "date": "2026-05-22",
        "last_updated": "2026-05-17",
        "snippet": "Plasma confinement refers to the containment of a plasma by various forces at the extreme conditions necessary for fusion.",
        "source": "web"
      },
      {
        "title": "Magnetic Fusion Confinement with Tokamaks and Stellarators",
        "url": "http://www.iaea.org/bulletin/magnetic-fusion-confinement-with-tokamaks-and-stellarators",
        "date": null,
        "last_updated": null,
        "snippet": "Strong magnets in the reactors keep the ions confined. Electrons are also bound by the reactors' forces and play a role in the surroundings. The magnetic forces ...",
        "source": "web"
      },
      {
        "title": "Magnetic confinement fusion - Wikipedia",
        "url": "https://en.wikipedia.org/wiki/Magnetic_confinement_fusion",
        "date": "2005-04-04",
        "last_updated": "2026-03-03",
        "snippet": "Magnetic confinement fusion (MCF) is an approach to generate thermonuclear fusion power that uses magnetic fields to confine fusion fuel in the form of a ...",
        "source": "web"
      },
      {
        "title": "Magnetic-confinement fusion - NASA ADS",
        "url": "http://ui.adsabs.harvard.edu/abs/2016NatPh..12..398O/abstract",
        "date": "1999-01-01",
        "last_updated": "2025-03-17",
        "snippet": "Here we review the basic physics underlying magnetic fusion: past achievements, present efforts and the prospects for future production of electrical energy.",
        "source": "web"
      }
    ],
    "status": null,
    "type": null,
    "usage": {
      "completion_tokens": 1917,
      "cost": {
        "input_tokens_cost": 5e-05,
        "output_tokens_cost": 0.02875,
        "total_cost": 0.03481,
        "citation_tokens_cost": null,
        "reasoning_tokens_cost": null,
        "request_cost": 0.006,
        "search_queries_cost": null
      },
      "prompt_tokens": 18,
      "total_tokens": 1935,
      "citation_tokens": null,
      "num_search_queries": null,
      "reasoning_tokens": null,
      "search_context_size": "low"
    }
  }
  ```
</Accordion>

## Streaming

Streaming works exactly like OpenAI's API:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    from openai import OpenAI

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

    stream = client.chat.completions.create(
        model="sonar-pro",
        messages=[
            {"role": "user", "content": "Explain the underlying physics of magnetic confinement fusion and the role of the Lawson criterion."}
        ],
        stream=True
    )

    for chunk in stream:
        if chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="", flush=True)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import OpenAI from 'openai';

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

    const stream = await client.chat.completions.create({
      model: "sonar-pro",
      messages: [
        { role: "user", content: "Explain the underlying physics of magnetic confinement fusion and the role of the Lawson criterion." }
      ],
      stream: true
    });

    for await (const chunk of stream) {
      if (chunk.choices[0]?.delta?.content) {
        process.stdout.write(chunk.choices[0].delta.content);
      }
    }
    ```
  </Tab>
</Tabs>

<Accordion title="Response">
  ```json theme={null}
  {
    "id": "258a700e-40fd-4e8d-956b-351e6ebc7f37",
    "choices": [
      {
        "delta": {
          "content": "",
          "role": "assistant",
          "reasoning_steps": null,
          "tool_call_id": null,
          "tool_calls": null
        },
        "index": 0,
        "message": {
          "content": "Magnetic confinement fusion uses strong magnetic fields to trap a very hot, ionized gas (plasma) so that light nuclei collide and fuse faster than the energy is lost, and the Lawson criterion quantifies the minimum combination of plasma density, temperature, and confinement time required for this to produce net energy. The core physics is charged-particle motion in magnetic fields (guiding centers following field lines plus gyration and drifts), collective plasma stability, and energy balance; the Lawson criterion is the formal expression of that energy balance.\n\n---\n\n### 1. Why fusion needs confinement\n\nFor deuterium–tritium (D–T) fusion to occur at an appreciable rate, the plasma must reach temperatures of order \\(10^8\\) K (∼10 keV), hotter than the Sun’s core, so that nuclei can overcome the Coulomb repulsion and get close enough for the strong nuclear force to fuse them.[1][4][6] At these temperatures:\n\n- All atoms are ionized → a **plasma** of electrons and ions.[1][4][6]  \n- No solid material can touch the plasma; it would vaporize instantly.[1][4]\n\nSo fusion requires:\n\n- **Heating** the fuel to fusion temperatures.  \n- **Confining** it long enough and dense enough that many fusion reactions occur before the energy escapes.[4][6]\n\nIn stars, gravity provides confinement; in labs, strong magnetic fields are used instead.[4][6]\n\n---\n\n### 2. Single-particle motion: how magnetic fields confine charges\n\nThe basic building block is the Lorentz force on a charged particle in a magnetic field: \\(\\mathbf{F} = q\\,\\mathbf{v} \\times \\mathbf{B}\\).\n\nFrom this follow key motions (as shown in standard plasma-physics treatments and educational material):[2][3][6]\n\n- A component of velocity **perpendicular** to \\(\\mathbf{B}\\) causes **circular gyro-motion** around the field line at the Larmor radius.  \n- A component **parallel** to \\(\\mathbf{B}\\) feels no magnetic force and moves freely along the field.[2]  \n\nCombined, ions and electrons **spiral** along magnetic field lines: they are tightly bound across the field but free to move along it.[2][3][6]\n\nThis leads to the confinement idea:\n\n- Shape the magnetic field so that **field lines are closed** (e.g., in a torus), forming a “magnetic bottle.”  \n- Particles spiral around these closed lines, remaining away from material walls.[1][3][6]\n\nThe stronger the magnetic field:\n\n- The **smaller** the Larmor radius.  \n- The **slower** cross-field drifts and diffusion.  \n- The **better** the confinement.[2][3]\n\n---\n\n### 3. From single particles to plasma: collective and MHD behavior\n\nAt fusion-relevant densities, the plasma’s own currents and charges significantly modify the externally applied magnetic field, and the medium must be treated collectively.[2][3][7] This is described by **magnetohydrodynamics (MHD)**:\n\n- The plasma behaves like a conducting fluid embedded in magnetic field lines.  \n- Magnetic field lines are often described as “frozen in” to the plasma: fluid elements move along field lines, and dragging the plasma across the field tends to drag the lines with it.[2]\n\nKey implications for magnetic confinement:\n\n- **Pressure balance:** Plasma pressure pushes outward, magnetic pressure and tension pull inward. Stable confinement demands that the magnetic field be strong enough and appropriately shaped to counter plasma pressure and currents.[3][7]  \n- **Instabilities:** Certain pressure/current configurations are unstable (e.g., kink, ballooning, interchange instabilities), leading to bulging, twisting, or breaking of confined regions and degraded confinement.[2][3][6][7]  \n- **Turbulence:** Small-scale fluctuations and turbulence cause enhanced transport of heat and particles across field lines, reducing the effective confinement time below what classical single-particle theory would predict.[2][3][7]\n\nDesigning a successful magnetic confinement system is largely about **finding magnetic geometries and operating regimes that avoid or tame these instabilities** and minimize turbulent transport.[3][6][7]\n\n---\n\n### 4. Magnetic geometry in practice: toroidal devices\n\nBecause particles stream freely along field lines, the field lines themselves must not intersect walls, which leads naturally to **toroidal (doughnut-shaped)** configurations:[1][5][6]\n\n- **Tokamak:**  \n  - Strong toroidal field from external coils.  \n  - Large plasma current generates a poloidal field, twisting field lines into helical paths, improving confinement and stability.[5][6][7]  \n- **Stellarator:**  \n  - Uses 3D-shaped external coils to create the required helical fields; does not rely on a large plasma current, which avoids some current-driven instabilities but demands complex coil engineering.[5][6][7]\n\nTwist in the field lines helps cancel or average out systematic drifts that would otherwise move particles to the wall.[2][6]\n\nOther configurations (mirror machines, reversed-field pinches, spherical tokamaks, etc.) explore different ways of shaping \\(\\mathbf{B}\\), but modern mainstream MCF focuses on tokamaks and stellarators.[5][6][7]\n\n---\n\n### 5. Energy balance and the Lawson criterion\n\nTo generate net power, the fusion plasma must satisfy an **energy balance condition**: fusion power produced must equal or exceed total power lost (radiation, conduction, convection, particle escape).[6][7]\n\nFor a D–T plasma, this condition is commonly expressed as the **Lawson criterion**, which relates:\n\n- **n** – plasma particle density  \n- **T** – temperature  \n- **τ\\_E** – energy confinement time (a measure of how long energy stays in the plasma before being lost)\n\nIn one common form, the Lawson criterion requires that the **triple product** \\(n T \\tau_E\\) exceed a critical value for ignition (self-sustaining fusion without external heating) or for net energy gain.[6][7]\n\nConceptually:\n\n- Fusion power density \\(\\propto n^2 \\langle \\sigma v \\rangle\\), where \\(\\langle \\sigma v \\rangle\\) increases with temperature up to an optimum.  \n- Loss power density \\(\\propto \\frac{3 n T}{\\tau_E}\\) (roughly, energy per particle divided by confinement time).  \n- Setting fusion power ≥ loss power gives a condition on \\(n T \\tau_E\\).[6][7]\n\nFor D–T at ∼10–20 keV, the required triple product is on the order of \\(10^{21}\\,\\text{keV·s·m}^{-3}\\) (order-of-magnitude; exact numbers depend on detailed assumptions), and modern large tokamaks operate near or approaching this regime in brief pulses.[6][7]\n\n**Role of the Lawson criterion in MCF:**\n\n- It defines the **minimum combination** of density, temperature, and confinement time needed for practical fusion.  \n- Because the temperature window is fairly constrained by fusion cross sections, MCF devices mostly trade off **density versus confinement time**:  \n  - Magnetic confinement operates at relatively **low density** and **long τ\\_E** (milliseconds to seconds or longer).  \n  - Inertial confinement operates at very **high density** and extremely **short τ\\_E** (nanoseconds).  \n- It provides a quantitative **performance metric**: experiments report their achieved \\(n T \\tau_E\\) and compare to the Lawson threshold for ignition or for specific gain factors.[6][7]\n\nIn short, the Lawson criterion translates “good enough confinement” into a precise inequality involving measurable plasma parameters.\n\n---\n\n### 6. Why magnetic confinement is hard\n\nLinking the physics pieces:\n\n- **Single-particle physics** explains why strong magnetic fields can, in principle, confine hot plasmas away from walls.  \n- **Collective and MHD physics** explain why real plasmas develop currents, instabilities, and turbulence that degrade that ideal confinement.  \n- The **Lawson criterion** states the quantitative target: despite all losses, achieve a triple product high enough that fusion heating balances or exceeds losses.\n\nMajor technical and physics challenges in MCF include:[3][4][6][7]\n\n- Achieving and sustaining **multi-tesla magnetic fields** with high precision.  \n- Controlling **MHD instabilities** and turbulent transport to attain long τ\\_E.  \n- Handling **extreme heat and particle loads** where confined plasma meets material surfaces (divertors, first wall).[3]  \n- Integrating materials, superconducting magnets, heating systems, and control systems to operate reliably for long durations.[3][6][7]\n\nAll of these are pursued with the Lawson criterion in mind: improving confinement time and allowable density at a given temperature to reach or surpass the ignition and net-gain conditions.\n\nIf you’d like, I can next walk through the Lawson criterion derivation step-by-step from the energy balance equations, or compare typical Lawson targets for magnetic vs inertial confinement.",
          "role": "assistant",
          "reasoning_steps": null,
          "tool_call_id": null,
          "tool_calls": null
        },
        "finish_reason": "stop"
      }
    ],
    "created": 1779896019,
    "model": "sonar-pro",
    "citations": [
      "https://www.york.ac.uk/physics-engineering-technology/ypi/research/mcf/",
      "https://www.youtube.com/watch?v=gwOrbr8KWDs",
      "https://www.peaknano.com/blog/magnetic-confinement-fusion-explained-history-challenges-and-enabling-technologies-peak-blog",
      "https://www.energy.gov/science/doe-explainsplasma-confinement",
      "http://www.iaea.org/bulletin/magnetic-fusion-confinement-with-tokamaks-and-stellarators",
      "https://en.wikipedia.org/wiki/Magnetic_confinement_fusion",
      "http://ui.adsabs.harvard.edu/abs/2016NatPh..12..398O/abstract"
    ],
    "object": "chat.completion",
    "search_results": [
      {
        "title": "Magnetic Confinement Fusion - University of York",
        "url": "https://www.york.ac.uk/physics-engineering-technology/ypi/research/mcf/",
        "date": null,
        "last_updated": "2026-04-21",
        "snippet": "In magnetic confinement fusion (MCF), the fuel (deuterium and tritium) is heated to a temperature which is ten times hotter than the centre of the Sun.",
        "source": "web"
      },
      {
        "title": "How nuclear fusion works (3) - magnetic confinement, tokamaks ...",
        "url": "https://www.youtube.com/watch?v=gwOrbr8KWDs",
        "date": "2022-07-11",
        "last_updated": "2026-03-31",
        "snippet": ".youtube.com/watch?v=IhHsOwLdCu4 [2] J. P. Freidberg, “Plasma Physics and Fusion Energy” (CUP 2010). [3] T. F. Neiser et al., “Gyrokinetic ...",
        "source": "web"
      },
      {
        "title": "Magnetic Confinement Fusion Explained: History, Challenges, and ...",
        "url": "https://www.peaknano.com/blog/magnetic-confinement-fusion-explained-history-challenges-and-enabling-technologies-peak-blog",
        "date": "2025-12-18",
        "last_updated": "2026-05-27",
        "snippet": "The principle behind MCF is grounded in charged particle motion. Plasmas naturally follow magnetic field lines. Under the right magnetic ...",
        "source": "web"
      },
      {
        "title": "DOE Explains...Plasma Confinement - Department of Energy",
        "url": "https://www.energy.gov/science/doe-explainsplasma-confinement",
        "date": "2026-05-22",
        "last_updated": "2026-05-17",
        "snippet": "Plasma confinement refers to the containment of a plasma by various forces at the extreme conditions necessary for fusion.",
        "source": "web"
      },
      {
        "title": "Magnetic Fusion Confinement with Tokamaks and Stellarators",
        "url": "http://www.iaea.org/bulletin/magnetic-fusion-confinement-with-tokamaks-and-stellarators",
        "date": null,
        "last_updated": null,
        "snippet": "Strong magnets in the reactors keep the ions confined. Electrons are also bound by the reactors' forces and play a role in the surroundings. The magnetic forces ...",
        "source": "web"
      },
      {
        "title": "Magnetic confinement fusion - Wikipedia",
        "url": "https://en.wikipedia.org/wiki/Magnetic_confinement_fusion",
        "date": "2005-04-04",
        "last_updated": "2026-03-03",
        "snippet": "Magnetic confinement fusion (MCF) is an approach to generate thermonuclear fusion power that uses magnetic fields to confine fusion fuel in the form of a ...",
        "source": "web"
      },
      {
        "title": "Magnetic-confinement fusion - NASA ADS",
        "url": "http://ui.adsabs.harvard.edu/abs/2016NatPh..12..398O/abstract",
        "date": "1999-01-01",
        "last_updated": "2025-03-17",
        "snippet": "Here we review the basic physics underlying magnetic fusion: past achievements, present efforts and the prospects for future production of electrical energy.",
        "source": "web"
      }
    ],
    "status": null,
    "type": null,
    "usage": {
      "completion_tokens": 1917,
      "cost": {
        "input_tokens_cost": 5e-05,
        "output_tokens_cost": 0.02875,
        "total_cost": 0.03481,
        "citation_tokens_cost": null,
        "reasoning_tokens_cost": null,
        "request_cost": 0.006,
        "search_queries_cost": null
      },
      "prompt_tokens": 18,
      "total_tokens": 1935,
      "citation_tokens": null,
      "num_search_queries": null,
      "reasoning_tokens": null,
      "search_context_size": "low"
    }
  }
  ```
</Accordion>

## Perplexity-Specific Parameters

Add Perplexity-specific search parameters using `extra_body` (Python) or direct parameters (TypeScript):

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    from openai import OpenAI

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

    completion = client.chat.completions.create(
        model="sonar-pro",
        messages=[
            {"role": "user", "content": "What does the National Snow and Ice Data Center (NSIDC) report about long-term trends in Arctic sea ice extent?"}
        ],
        extra_body={
            "search_domain_filter": ["nature.com", "science.org"],
            "search_recency_filter": "month"
        }
    )

    print(completion.choices[0].message.content)
    print(f"Sources: {len(completion.search_results)} articles found")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import OpenAI from 'openai';

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

    const completion = await client.chat.completions.create({
      model: "sonar-pro",
      messages: [
        { role: "user", content: "What does the National Snow and Ice Data Center (NSIDC) report about long-term trends in Arctic sea ice extent?" }
      ],
      search_domain_filter: ["nature.com", "science.org"],
      search_recency_filter: "month"
    } as any);

    console.log(completion.choices[0].message.content);
    console.log(`Sources: ${(completion as any).search_results.length} articles found`);
    ```
  </Tab>
</Tabs>

<Accordion title="Response">
  ```json theme={null}
  {
    "id": "31d5d419-b5f0-413e-8f86-4d55bad6866e",
    "choices": [
      {
        "delta": {
          "content": "",
          "role": "assistant",
          "reasoning_steps": null,
          "tool_call_id": null,
          "tool_calls": null
        },
        "index": 0,
        "message": {
          "content": "NSIDC reports that **Arctic sea ice extent has declined over the long term** since the satellite record began in 1979, and that the decline is **statistically significant** across all months.[5] NSIDC also says the Arctic trend is part of a broader pattern of **less ice overall, including lower seasonal minima and less multi-year ice**.[1][5]\n\nA few specific points NSIDC emphasizes:\n\n- **All months have shown a declining trend** in Arctic sea ice extent from November 1978 through March 2025.[5]\n- The **annual minimum** and **annual maximum** extents are now both lower than earlier decades, with recent minimums about **50% of 1980s values**.[3]\n- NSIDC uses the long satellite record to show the **big picture**, noting that short-term ups and downs do not outweigh the longer downward trend.[5]\n- Scientists at NSIDC and NASA have said recent low-ice years continue the **long-term trend observed over several decades**.[1]\n\nIn short, NSIDC’s message is that Arctic sea ice extent is **shrinking over time**, especially in the context of the full satellite record, even though year-to-year variability remains large.[1][5][6]",
          "role": "assistant",
          "reasoning_steps": null,
          "tool_call_id": null,
          "tool_calls": null
        },
        "finish_reason": "stop"
      }
    ],
    "created": 1779896048,
    "model": "sonar-pro",
    "citations": [
      "https://science.nasa.gov/earth/arctic-winter-sea-ice-2026/",
      "https://www.climate.gov/news-features/event-tracker/2024-antarctic-sea-ice-winter-maximum-second-lowest-record",
      "https://arctic.noaa.gov/report-card/report-card-2024/sea-ice-2024/",
      "https://svs.gsfc.nasa.gov/5521/",
      "https://nsidc.org/learn/ask-scientist/what-value-sea-ice-time-series-data",
      "https://nsidc.org/sea-ice-today",
      "https://nsidc.org/sea-ice-today/sea-ice-tools/charctic-interactive-sea-ice-graph",
      "https://climatedataguide.ucar.edu/climate-data/nsidc-sea-ice-index",
      "https://zacklabe.com/arctic-sea-ice-figures/"
    ],
    "object": "chat.completion",
    "search_results": [
      {
        "title": "Arctic Winter Sea Ice Ties Record Low, NASA, NSIDC Scientists Find",
        "url": "https://science.nasa.gov/earth/arctic-winter-sea-ice-2026/",
        "date": "2026-03-26",
        "last_updated": "2026-05-15",
        "snippet": "Scientists with NASA and NSIDC found that this winter's peak Arctic ice coverage continues the long-term trend observed over the past several ...",
        "source": "web"
      },
      {
        "title": "2024 Antarctic sea ice winter maximum second lowest on record",
        "url": "https://www.climate.gov/news-features/event-tracker/2024-antarctic-sea-ice-winter-maximum-second-lowest-record",
        "date": "2024-10-08",
        "last_updated": "2026-03-04",
        "snippet": "I think the long-term trend will be a decreasing ice extent in all seasons, but there is such variability on the time scale of a few years ...",
        "source": "web"
      },
      {
        "title": "Sea Ice - NOAA Arctic",
        "url": "https://arctic.noaa.gov/report-card/report-card-2024/sea-ice-2024/",
        "date": "2024-11-11",
        "last_updated": "2026-05-26",
        "snippet": "Sea ice extent in September 2024 was the 6th lowest in the satellite record (1979 to present); the last 18 September extents (2007-24) are the ...",
        "source": "web"
      },
      {
        "title": "Sea Ice Extent 1978-2025 - NASA Scientific Visualization Studio",
        "url": "https://svs.gsfc.nasa.gov/5521/",
        "date": "2025-03-27",
        "last_updated": "2026-05-27",
        "snippet": "The Sea Ice Index provides a quick look at Arctic- and Antarctic-wide changes in sea ice. It is a source for consistent, up-to-date sea ice ...",
        "source": "web"
      },
      {
        "title": "What is the value of sea ice time series data?",
        "url": "https://nsidc.org/learn/ask-scientist/what-value-sea-ice-time-series-data",
        "date": "2025-05-15",
        "last_updated": "2026-03-03",
        "snippet": "From November 1978 to March 2025, Arctic sea ice extent showed a declining trend in all months. Meanwhile, Antarctic sea ice has been linked ...",
        "source": "web"
      },
      {
        "title": "Sea Ice Today | National Snow and Ice Data Center",
        "url": "https://nsidc.org/sea-ice-today",
        "date": null,
        "last_updated": "2026-05-26",
        "snippet": "In the Arctic, the annual minimum sea ice extent occurs in September and the annual sea ice maximum extent occurs in March. In the Antarctic, the minimum extent ...",
        "source": "web"
      },
      {
        "title": "Charctic Interactive Sea Ice Graph",
        "url": "https://nsidc.org/sea-ice-today/sea-ice-tools/charctic-interactive-sea-ice-graph",
        "date": null,
        "last_updated": "2026-05-27",
        "snippet": "For both the Arctic and Antarctic, the graph compares sea ice extent (area of ocean with at least 15 percent sea ice concentration) between all years selected.",
        "source": "web"
      },
      {
        "title": "NSIDC Sea Ice Index - Climate Data Guide",
        "url": "https://climatedataguide.ucar.edu/climate-data/nsidc-sea-ice-index",
        "date": "2025-12-11",
        "last_updated": "2026-05-26",
        "snippet": "The Sea Ice Index provides consistent long-term statistics on sea ice extent and area change. However, it is not reliable for operational uses ...",
        "source": "web"
      },
      {
        "title": "Polar Climate Change Figures - Zachary Labe",
        "url": "https://zacklabe.com/arctic-sea-ice-figures/",
        "date": "2026-01-04",
        "last_updated": "2026-05-26",
        "snippet": "Animation of changes in average September sea ice extent from 1979 through 2025 – with substantial natural variability and a long-term decline.",
        "source": "web"
      }
    ],
    "status": null,
    "type": null,
    "usage": {
      "completion_tokens": 263,
      "cost": {
        "input_tokens_cost": 8e-05,
        "output_tokens_cost": 0.00394,
        "total_cost": 0.01002,
        "citation_tokens_cost": null,
        "reasoning_tokens_cost": null,
        "request_cost": 0.006,
        "search_queries_cost": null
      },
      "prompt_tokens": 26,
      "total_tokens": 289,
      "citation_tokens": null,
      "num_search_queries": null,
      "reasoning_tokens": null,
      "search_context_size": "low"
    }
  }
  ```
</Accordion>

## API Compatibility

### Standard OpenAI Parameters

These parameters work exactly the same as OpenAI's API:

* `model` - Model name (use Perplexity model names like `sonar-pro`)
* `messages` - Chat messages array
* `max_tokens` - Maximum tokens in response
* `stream` - Enable streaming responses
* `temperature` - Response randomness (0-2)
* `top_p` - Nucleus sampling parameter
* `response_format` - Response format specification

### Perplexity-Specific Parameters

Sonar API supports additional search and response parameters:

* `search_domain_filter` - Limit or exclude specific domains
* `search_recency_filter` - Filter by content recency ("day", "week", "month", "year")
* `return_images` - Include image URLs in response
* `return_related_questions` - Include related questions
* `search_mode` - "web" (default) or "academic" mode selector
* `enable_search_classifier` - Let AI decide when to search
* `disable_search` - Turn off web search completely

<Info>
  See [Sonar API Reference](/api-reference/sonar-post) for complete parameter details.
</Info>

## Endpoint Mapping

| Method                                    | Perplexity Endpoint    | OpenAI Equivalent              | Notes                                               |
| ----------------------------------------- | ---------------------- | ------------------------------ | --------------------------------------------------- |
| `client.chat.completions.create()`        | `POST /v1/sonar`       | `POST /chat/completions`       | Both paths accepted by Perplexity for compatibility |
| `client.async_.chat.completions.create()` | `POST /v1/async/sonar` | `POST /async/chat/completions` | Both paths accepted by Perplexity for compatibility |

<Info>
  When using the OpenAI SDK, `client.chat.completions.create()` sends requests to `/chat/completions`. Perplexity accepts this path as an alias for `/v1/sonar`, so no SDK configuration changes are needed beyond `base_url`.
</Info>

## Response Structure

Perplexity responses match OpenAI's format exactly, with additional fields:

### Standard OpenAI Fields

* `choices[0].message.content` - The AI-generated response
* `model` - The model name used
* `usage` - Token consumption details
* `id`, `created`, `object` - Standard response metadata

### Perplexity-Specific Fields

* `search_results` - Array of web sources with `title`, `url`, and `date`
* `citations` - Array of citation URLs referenced in the response

**Example Response:**

```json theme={null}
{
  "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "model": "sonar-pro",
  "created": 1234567890,
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The latest developments in AI include..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 315,
    "total_tokens": 327
  },
  "search_results": [
    {
      "title": "Latest AI Developments",
      "url": "https://example.com/ai-news",
      "date": "2025-02-01"
    }
  ],
  "citations": [
    "https://example.com/ai-news"
  ]
}
```

## Best Practices

<Steps>
  <Step title="Use the correct base URL">
    Always use `https://api.perplexity.ai` for the Sonar API.

    ```python theme={null}
    client = OpenAI(
        api_key=os.environ.get("PERPLEXITY_API_KEY"),
        base_url="https://api.perplexity.ai"  # Correct
    )
    ```
  </Step>

  <Step title="Handle errors gracefully">
    Use the OpenAI SDK's error handling:

    ```python theme={null}
    import os
    from openai import OpenAI, APIError, RateLimitError

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

    try:
        completion = client.chat.completions.create(
            model="sonar-pro",
            messages=[{"role": "user", "content": "Hello"}]
        )
    except RateLimitError:
        print("Rate limit exceeded, please retry later")
    except APIError as e:
        print(f"API error: {e.message}")
    ```
  </Step>

  <Step title="Use streaming for better UX">
    Stream responses for real-time user experience:

    ```python theme={null}
    stream = client.chat.completions.create(
        model="sonar-pro",
        messages=[{"role": "user", "content": "Long query..."}],
        stream=True
    )

    for chunk in stream:
        if chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="", flush=True)
    ```
  </Step>

  <Step title="Access search results">
    Use the `search_results` field to get accurate source URLs:

    ```python theme={null}
    completion = client.chat.completions.create(
        model="sonar-pro",
        messages=[{"role": "user", "content": "What was NVIDIA's data-center segment revenue growth in fiscal 2024, and how did the stock react to the Q4 print?"}]
    )

    # Access search results
    for result in completion.search_results:
        print(f"{result['title']}: {result['url']}")
    ```

    <Accordion title="Response">
      ```json theme={null}
      {
        "id": "1ca706ec-87b5-4e45-b4a1-0a0b4e015085",
        "choices": [
          {
            "delta": {
              "content": "",
              "role": "assistant",
              "reasoning_steps": null,
              "tool_call_id": null,
              "tool_calls": null
            },
            "index": 0,
            "message": {
              "content": "NVIDIA’s data-center segment revenue growth in fiscal 2024 and the stock reaction to the Q4 print can be summarized as follows:\n\n**1. Data-center revenue growth in fiscal 2024**\n\nFrom NVIDIA’s own fiscal 2024 results release ([source 4](https://investor.nvidia.com/news/press-release-details/2024/NVIDIA-Announces-Financial-Results-for-Fourth-Quarter-and-Fiscal-2024/)):\n\n- Fiscal 2024 **data-center revenue**: **$47.5 billion**\n- Year-over-year growth: **up 217%** versus the prior fiscal year  \n\nSo, NVIDIA’s data-center segment revenue grew **217% year over year** in fiscal 2024.\n\n**2. Stock reaction to the Q4 FY2024 print**\n\nS&P Global’s post-earnings analysis for the subsequent Q1 FY2025 report includes a backward look at the Q4 FY2024 earnings release on Feb. 21, 2024 ([source 3](https://www.spglobal.com/market-intelligence/en/news-insights/research/2024/05/data-center-revenue-growth-continues-nvidias-fiscal-q1-2025-earnings)):\n\n- It notes that **NVDA stock was up close to 58% since the Q4 release on February 21, 2024** (measured by the time of their May 2024 analysis).\n\nIn other words, following the **Q4 FY2024 earnings print** (which reported the huge data-center growth), NVIDIA’s stock **rallied on the order of ~58% over the subsequent weeks/months**, according to S&P Global Market Intelligence.",
              "role": "assistant",
              "reasoning_steps": null,
              "tool_call_id": null,
              "tool_calls": null
            },
            "finish_reason": "stop"
          }
        ],
        "created": 1779391605,
        "model": "sonar-pro",
        "citations": [
          "https://www.govconwire.com/articles/nvidia-revenue-climbs-126-to-60-9b-in-fiscal-2024-jensen-huang-quoted",
          "https://www.statista.com/chart/25578/nvidias-quarterly-revenue-by-segments/",
          "https://www.spglobal.com/market-intelligence/en/news-insights/research/2024/05/data-center-revenue-growth-continues-nvidias-fiscal-q1-2025-earnings",
          "https://investor.nvidia.com/news/press-release-details/2024/NVIDIA-Announces-Financial-Results-for-Fourth-Quarter-and-Fiscal-2024/",
          "https://ycharts.com/indicators/nvidia_corp_nvda_data_center_revenue_quarterly",
          "http://bullfincher.io/companies/nvidia-corporation/revenue-by-segment"
        ],
        "object": "chat.completion",
        "search_results": [
          {
            "title": "NVIDIA Revenue Climbs 126% to $60.9B in Fiscal 2024",
            "url": "https://www.govconwire.com/articles/nvidia-revenue-climbs-126-to-60-9b-in-fiscal-2024-jensen-huang-quoted",
            "date": "2024-02-22",
            "last_updated": "2026-04-22",
            "snippet": "NVIDIA's Data Center segment contributed $47.5 billion revenue in the full year, a 217 percent growth from the previous year. “Our Data ...",
            "source": "web"
          },
          {
            "title": "Data Centers Almost Sole Driver of Nvidia's Revenue Boom - Statista",
            "url": "https://www.statista.com/chart/25578/nvidias-quarterly-revenue-by-segments/",
            "date": "2024-05-24",
            "last_updated": "2026-05-18",
            "snippet": "Between February and April 2024, $22.6 billion or 87 percent of Nvidia's overall revenue was attributable to data center solutions.",
            "source": "web"
          },
          {
            "title": "Data Center Revenue Growth Continues: Nvidia's Fiscal Q1 2025 ...",
            "url": "https://www.spglobal.com/market-intelligence/en/news-insights/research/2024/05/data-center-revenue-growth-continues-nvidias-fiscal-q1-2025-earnings",
            "date": "2024-05-29",
            "last_updated": "2026-05-17",
            "snippet": "The top-end estimate expects $189.9 billion, up from $182.6 billion, while the low-end estimate is now at $119.5 billion, up from $95.8 billion, ...",
            "source": "web"
          },
          {
            "title": "NVIDIA Announces Financial Results for Fourth Quarter and Fiscal ...",
            "url": "https://investor.nvidia.com/news/press-release-details/2024/NVIDIA-Announces-Financial-Results-for-Fourth-Quarter-and-Fiscal-2024/",
            "date": "2024-02-21",
            "last_updated": "2026-05-13",
            "snippet": "For fiscal 2024, revenue was up 126% to $60.9 billion. GAAP earnings per diluted share was $11.93, up 586% from a year ago. Non-GAAP earnings ...",
            "source": "web"
          },
          {
            "title": "NVIDIA Corp (NVDA) - Data Center Revenue (Quarterly) - YCharts",
            "url": "https://ycharts.com/indicators/nvidia_corp_nvda_data_center_revenue_quarterly",
            "date": "2026-03-23",
            "last_updated": "2026-05-18",
            "snippet": "NVIDIA Corp (NVDA) - Data Center Revenue is at a current level of 62.31B, up from 51.22B last quarter and up from 30.77B one year ago. This is a change of ...",
            "source": "web"
          },
          {
            "title": "NVIDIA Corporation Revenue Breakdown By Segment - Bullfincher",
            "url": "http://bullfincher.io/companies/nvidia-corporation/revenue-by-segment",
            "date": null,
            "last_updated": "2026-03-30",
            "snippet": "In fiscal year 2026, Data Center revenue reached $193.74 Billion, representing 89.72% of NVIDIA Corporation's total revenue and making it the largest segment ...",
            "source": "web"
          }
        ],
        "status": null,
        "type": null,
        "usage": {
          "completion_tokens": 354,
          "cost": {
            "input_tokens_cost": 8e-05,
            "output_tokens_cost": 0.00531,
            "total_cost": 0.01139,
            "citation_tokens_cost": null,
            "reasoning_tokens_cost": null,
            "request_cost": 0.006,
            "search_queries_cost": null
          },
          "prompt_tokens": 28,
          "total_tokens": 382,
          "citation_tokens": null,
          "num_search_queries": null,
          "reasoning_tokens": null,
          "search_context_size": "low"
        }
      }
      ```
    </Accordion>
  </Step>
</Steps>

## Recommended: Perplexity SDK

We recommend using Perplexity's native SDKs for the best developer experience:

* **Type safety** - Full TypeScript/Python type definitions for all parameters
* **Enhanced features** - Direct access to all Perplexity-specific features
* **Better error messages** - Perplexity-specific error handling
* **Simpler setup** - No need to configure base URLs

See the [Perplexity SDK Guide](/docs/sdk/overview) for details.

## Next Steps

<CardGroup cols={2}>
  <Card title="Sonar Quickstart" icon="rocket" href="/docs/sonar/quickstart">
    Get started with Sonar API using OpenAI SDKs.
  </Card>

  <Card title="Sonar API Features" icon="book" href="/docs/sonar/features">
    Learn best practices for prompting and using the Sonar API.
  </Card>

  <Card title="API Reference" icon="code-circle" href="/api-reference/sonar-post">
    View complete API documentation for the Sonar endpoint.
  </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>
