Skip to main content

04 - From Sonar to the Agent API: migrating safely

Sonar has been folded into Perplexity's Agent API: what changes in request, response and citations, a body translator and a test on your own traffic.

What do you think about this article?

04 - From Sonar to the Agent API: migrating safely
Perplexityfedericocalo.dev

At a Glance

Sonar has been folded into Perplexity's Agent API: what changes in request, response and citations, a body translator and a test on your own traffic.

Direct answer. Migrating from Sonar to Perplexity's Agent API is not a replacement of the model name: the endpoint changes (POST /v1/agent), the shape of the request (input in place of messages), the shape of the response (a typed output array in place of choices) and the place where the citations sit. The documentation gives sonar and sonar-pro to fast, sonar-reasoning-pro to low, sonar-deep-research to high as a starting point, and says it as a starting point, not as an equivalence. The biggest risk is not code that fails to compile: it is behavior that changes without you touching anything, because synchronous and streaming requests are rewritten by Perplexity with a gradual rollout, model by model.

What follows comes from the "Migrate from Sonar to the Agent API", "How to migrate from Sonar" and "Web Search" pages opened on 13 November 2026, and from the developer forum. I do not have a key and I have not called the product, and I have not read the benchmarks page: the improvement tables that the guide publishes are declared by the vendor, with internal benchmarks, and I do not report them as proof. The scripts run without a network, on requests and responses that I built myself in the documented shape.

What the documentation says, word for word

The migration overview page states, in the version read today: "Sonar Chat Completions support ended on September 27, 2026". Right after, it specifies that synchronous and streaming requests keep working because they are rewritten as Agent API requests, with a gradual rollout by model, while asynchronous requests are not rewritten and are no longer supported: they must be moved to background mode. In the developer forum, on 10 September 2026, a member of staff answered someone who asked whether the old endpoint would stay after 27 September by saying that the Sonar chat completions endpoint would be retired that day and that one had to move to the Agent API responses endpoint. The guide recommends migrating existing usage and using the Agent API for every new project.

The practical consequence is double. Whoever has synchronous requests sees no error: they see, perhaps, answers with a different shape or tone, and do not know since when. Whoever has asynchronous requests already has a failure, not a risk. For both the same method holds: inventory, test on your own questions, controlled switch, as in the paragraphs that follow.

Before and after: the request

In the migration quickstart, the call changes from client.chat.completions.create(model="sonar", messages=[...]) to client.responses.create(effort="fast", input=...), and the text of the response is read from risposta.output_text instead of from choices[0].message.content. The schema that follows puts the two forms side by side; it is to be adapted, not run, because it requires a key and a project that really uses Sonar.

# BEFORE (chat completions, Sonar)
risposta = client.chat.completions.create(
    model="sonar-pro",
    messages=[
        {"role": "system", "content": "You are a concise assistant."},
        {"role": "user", "content": domanda},
    ],
    max_tokens=800,
)
testo = risposta.choices[0].message.content

# AFTER (Agent API)
risposta = client.responses.create(
    effort="fast",                       # starting point given for sonar-pro
    instructions="You are a concise assistant.",
    input=domanda,
    max_output_tokens=800,
)
testo = risposta.output_text

The three visible differences are the system prompt, which moves into instructions instead of sitting in the messages array, the name of the token ceiling and the field the text is read from. The rest is below the surface: what the fast level does more (it searches the web by default) and less (there is no longer a citations field) you see only by reading the whole response. The starting point for sonar-pro is fast: the guide says so, and also says that the right level is decided by testing.

The translation rules, from the official guide:

  • the system prompt moves into the instructions field; messages becomes input, a string or an array of items with type: "message", role and content;
  • max_tokens becomes max_output_tokens; reasoning_effort becomes reasoning.effort;
  • response_format with json_schema keeps the same shape; the regex type has no equivalent and must be redesigned on a JSON schema;
  • the filters (search_domain_filter, search_recency_filter, the date filters) move with the same names inside filters of the web_search tool; num_search_results becomes the tool's max_results, a ceiling on the total; user_location sits on the tool, not inside filters;
  • the fast level enables web search by default; if you choose a model directly you must add the web_search tool;
  • in streaming, the text arrives in the response.output_text.delta events and no longer in delta.content; tool calls and reasoning have their own events;
  • for dialogues: previous_response_id, or you send back the earlier turns, assistant included, inside input.

These are rules of relocation: the same concepts change address, and almost all the lines apply with a search in the code. The three to treat with care are the one on regex (it is not translated, it is redesigned), the one on the fast level versus choosing a model directly (search disappears if you forget the tool) and the one on streaming, because a consumer that looks for delta.content stops showing text without signaling errors. The script that follows applies these rules to a Sonar request body and says out loud what it cannot translate.

"""Translates the BODY of a Sonar request into an Agent API body, following the migration guide."""
import json

LIVELLO_DI_PARTENZA = {"sonar": "fast", "sonar-pro": "fast", "sonar-reasoning-pro": "low", "sonar-deep-research": "high"}
FILTRI = {"search_domain_filter", "search_recency_filter", "search_after_date_filter", "search_before_date_filter",
          "last_updated_after_filter", "last_updated_before_filter"}
DA_TOGLIERE = {"search_language_filter", "stream_mode", "return_videos", "num_videos", "media_response"}


def sonar_a_agent(sonar: dict):
    agent, note = {}, []
    modello = sonar.get("model")
    if modello in LIVELLO_DI_PARTENZA:
        agent["effort"] = LIVELLO_DI_PARTENZA[modello]
        note.append(f"{modello} -> effort {agent['effort']}: starting point, to be tested")
    else:
        note.append(f"model {modello!r}: no mapping, you choose")
    sistema = [m["content"] for m in sonar.get("messages", []) if m["role"] == "system"]
    if sistema:
        agent["instructions"] = "\n".join(sistema)
    agent["input"] = [{"type": "message", "role": m["role"], "content": m["content"]}
                      for m in sonar.get("messages", []) if m["role"] != "system"]
    if "max_tokens" in sonar:
        agent["max_output_tokens"] = sonar["max_tokens"]
    if "reasoning_effort" in sonar:
        agent["reasoning"] = {"effort": sonar["reasoning_effort"]}
    for campo in ("stream", "temperature", "top_p"):
        if campo in sonar:
            agent[campo] = sonar[campo]
    if "temperature" in sonar or "top_p" in sonar:
        note.append("temperature/top_p: ignored by the GPT-5, o1, o3 families (migration guide)")
    strumento = {"type": "web_search"}
    filtri = {k: v for k, v in sonar.items() if k in FILTRI}
    if filtri:
        strumento["filters"] = filtri
    if "num_search_results" in sonar:
        strumento["max_results"] = sonar["num_search_results"]
    posizione = sonar.get("web_search_options", {}).get("user_location")
    if posizione:
        strumento["user_location"] = posizione
    if not sonar.get("disable_search"):
        agent["tools"] = [strumento]
    else:
        note.append("disable_search: no tool to add, but the levels bring their own; see the guide")
    formato = sonar.get("response_format")
    if formato and formato.get("type") == "regex":
        note.append("response_format regex: NO equivalent, to be redesigned on json_schema")
    elif formato:
        agent["response_format"] = formato
    if sonar.get("return_images"):
        note.append("return_images: add the image_search tool")
    if sonar.get("return_related_questions"):
        note.append("return_related_questions: ask for them in the prompt or with a structured output")
    if sonar.get("search_mode") == "academic":
        note.append("search_mode academic: no direct equivalent")
    for campo in sorted(DA_TOGLIERE & sonar.keys()):
        note.append(f"{campo}: no equivalent, remove it")
    return agent, note


PROVE = [
    {"model": "sonar-pro", "max_tokens": 800,
     "messages": [{"role": "system", "content": "Be concise."}, {"role": "user", "content": "News about crawlers?"}],
     "search_domain_filter": ["docs.perplexity.ai"], "search_recency_filter": "month", "num_search_results": 8},
    {"model": "sonar-deep-research", "messages": [{"role": "user", "content": "Report"}],
     "search_language_filter": ["en"], "stream_mode": "full", "response_format": {"type": "regex", "regex": {"regex": "^a+$"}}},
    {"model": "sonar-reasoning", "messages": [{"role": "user", "content": "x"}], "return_images": True, "temperature": 0.2},
]
for sonar in PROVE:
    agent, note = sonar_a_agent(sonar)
    print(json.dumps(agent, ensure_ascii=False))
    for n in note:
        print("  *", n)

# Output:
# {"effort": "fast", "instructions": "Be concise.", "input": [{"type": "message", "role": "user", "content": "News about crawlers?"}], "max_output_tokens": 800, "tools": [{"type": "web_search", "filters": {"search_domain_filter": ["docs.perplexity.ai"], "search_recency_filter": "month"}, "max_results": 8}]}
#   * sonar-pro -> effort fast: starting point, to be tested
# {"effort": "high", "input": [{"type": "message", "role": "user", "content": "Report"}], "tools": [{"type": "web_search"}]}
#   * sonar-deep-research -> effort high: starting point, to be tested
#   * response_format regex: NO equivalent, to be redesigned on json_schema
#   * search_language_filter: no equivalent, remove it
#   * stream_mode: no equivalent, remove it
# {"input": [{"type": "message", "role": "user", "content": "x"}], "temperature": 0.2, "tools": [{"type": "web_search"}]}
#   * model 'sonar-reasoning': no mapping, you choose
#   * temperature/top_p: ignored by the GPT-5, o1, o3 families (migration guide)
#   * return_images: add the image_search tool

The code was run twice with identical output (Python 3.14, standard library). The three test requests are chosen to show three outcomes. The first translates entirely: the system prompt goes into instructions, the filters end up inside the tool and num_search_results becomes max_results. The second loses two fields with no equivalent and a response_format of type regex, and the script writes it instead of staying silent. The third uses a model name that the guide does not map (sonar-reasoning, without -pro): the script does not invent a level and asks you to choose. It is a translator of the body, written by me on the guide's rules: it does not replace a test on your traffic and does not know what the guide does not say.

What has no equivalent, and what to do

The guide lists the parameters with no equivalent: search_language_filter, stream_mode, an image relevance option and the video results. Others have a different model: search_mode: "academic" has no direct counterpart (you use web_search with domain filters and the instructions), return_images becomes the image_search tool, return_related_questions becomes a request in the prompt or a structured output, and enable_search_classifier becomes the simple presence of the web_search tool. One case deserves to be read in full: for disable_search the guide says you omit the tool, but that with an effort level the level's tools stay enabled, that tools: [] does not clear them and that max_tool_calls: 0 is a blunt workaround to disable all tool calls.

For the GPT-5, o1 and o3 families the guide warns that temperature and top_p are silently ignored: do not migrate logic that depends on their effect. For the parameters the guide does not mention I have no source saying what happens, and I do not invent one: list them in your inventory and test them one by one. There is finally a design consequence: the language filter that the Agent API does not have exists instead in the Search API (article 3). If it is essential for your product, the road may be to retrieve with the Search API and have your own model answer.

Citations change home

In the old format the references sat next to the text, in the citations and search_results fields of the choices response. In the new one they sit in a search_results item of the output array, with the results identified by an id, while the markers in the text are [1] at fast and [web:1] from low upwards: the guide says the number points to the result with that id. The same guide says the text has no separate annotations field: the map between markers and sources you build yourself (article 2 has a check that handles both formats).

The typical failure is in the front end: if it turns [n] into a link with a regular expression written for Sonar, it does not recognize [web:1]. The script that follows does two things on a test project created on the fly in a temporary folder (three files that I wrote, one of them with no code): it looks for the points to migrate with regular expressions and shows what the old expression does on the new marker.

"""Inventory of the points to migrate in a TEST project created here, and a test of the marker."""
import re
import tempfile
from pathlib import Path

SCHEMI = {
    "Sonar call": r"chat\.completions\.create",
    "reading choices": r"\.choices\[|\[\"choices\"\]",
    "reading citations": r"\.citations\b|\[\"citations\"\]",
    "fields that disappear": r"related_questions|\.images\b|return_images|stream_mode|search_language_filter",
    "Sonar model": r"model\s*=\s*[\"']sonar[\w-]*[\"']",
    "marker regex [n]": r"\\\[\(\\d\+\)\\\]",
}
FILE_DI_PROVA = {
    "bot.py": 'r = client.chat.completions.create(model="sonar-pro", messages=m)\ntesto = r.choices[0].message.content\nfonti = r.citations\n',
    "web/app.js": 'const link = testo.replace(/\\[(\\d+)\\]/g, "<a>$1</a>");\nconst q = r.related_questions;\n',
    "note.md": "This file contains no code.\n",
}

with tempfile.TemporaryDirectory() as d:
    radice = Path(d)
    for nome, contenuto in FILE_DI_PROVA.items():
        (radice / nome).parent.mkdir(parents=True, exist_ok=True)
        (radice / nome).write_text(contenuto, encoding="utf-8")
    for file in sorted(radice.rglob("*")):
        if not file.is_file():
            continue
        for numero, riga in enumerate(file.read_text(encoding="utf-8").splitlines(), start=1):
            for nome, schema in SCHEMI.items():
                if re.search(schema, riga):
                    print(f"{file.relative_to(radice)}:{numero}: {nome}")

vecchio = re.compile(r"\[(\d+)\]")
nuovo = re.compile(r"\[(?:[a-z]+:)?(\d+)\]")
testo = "First[1] and second[web:2]."
print("old regex:", vecchio.findall(testo))
print("new regex  :", nuovo.findall(testo))

# Output:
# bot.py:1: Sonar call
# bot.py:1: Sonar model
# bot.py:2: reading choices
# bot.py:3: reading citations
# web/app.js:1: marker regex [n]
# web/app.js:2: fields that disappear
# old regex: ['1']
# new regex  : ['1', '2']

The output lists, by file and line number, every point to touch: the call and the model name, the reading of choices and of citations, the marker regex and the fields that disappear. The last pair of lines is the proof: the old expression finds only 1, the new one finds 1 and 2. On a real project the inventory is a starting point, not a verdict: a search by regular expression misses dynamically built names and fields read with a name in a variable, so it must be completed by rereading the points where the code uses the response.

The test you need: a set of "golden" questions

I do not compare prices per token (model prices are published page by page and depend on the level you choose) nor do I trust the vendor's benchmarks: the only evidence that counts is the one on your traffic. You need 30-50 real questions, each with the facts that must appear and, where it makes sense, a domain from which a source is expected. The loop that produces the answers is one call per question, with the time measured around it; the outline is this and it is not run, because it requires a key:

import time

for d in DOMANDE:
    t0 = time.time()
    r = client.responses.create(effort="fast", input=d["testo"])
    durata = round(time.time() - t0, 2)
    # r.effort holds level and version; r.output holds sources and text
    # ...pass r (converted to a dict) to the evaluation function below

The loop is deliberately poor: it records the duration and hands the whole response to the function that evaluates, because everything that can be checked mechanically is in the response. That function I can run, on two synthetic responses that I built myself, one for fast and one for low.

"""Comparison of two levels on a set of questions: the part that needs no network."""
import re
from urllib.parse import urlparse

# TEST "golden" set: one question, the facts that must appear, the expected domain.
DOMANDE = [{"id": "q1", "fatti": [r"root", r"robots\.txt"], "dominio": "example.test"}]

# Two SYNTHETIC responses in the documented shape (search_results + message): invented content.
def risposta(testo, url):
    return {"output": [
        {"type": "search_results", "results": [{"id": i + 1, "url": u} for i, u in enumerate(url)]},
        {"type": "message", "content": [{"type": "output_text", "text": testo}]},
    ]}

RISPOSTE = {
    "fast": {"q1": risposta("The robots.txt file lives in the root[1].", ["https://example.test/guide"])},
    "low": {"q1": risposta("A text file for crawlers[web:1].", ["https://altro.test/a", "https://altro.test/b"])},
}


def valuta(domanda, r):
    testo = "".join(p["text"] for v in r["output"] if v["type"] == "message" for p in v["content"])
    url = [x["url"] for v in r["output"] if v["type"] == "search_results" for x in v["results"]]
    domini = {urlparse(u).netloc for u in url}
    return {
        "n_sources": len(url),
        "expected_domain": domanda["dominio"] in domini,
        "facts_present": all(re.search(f, testo, re.I) for f in domanda["fatti"]),
    }


for livello, per_domanda in RISPOSTE.items():
    for d in DOMANDE:
        print(livello, d["id"], valuta(d, per_domanda[d["id"]]))

# Output:
# fast q1 {'n_sources': 1, 'expected_domain': True, 'facts_present': True}
# low q1 {'n_sources': 2, 'expected_domain': False, 'facts_present': False}

The code measures three things that can be checked mechanically: how many sources, whether the expected domain appears, whether the expected facts are in the text. In the example, built by me, low "gets worse" on all three measures: it is not a result about the product, it is the shape of the comparison, and it shows why the choice of level is not made by eye. It does not measure whether the facts are supported by the sources: that needs a sample read by a person. Run the set once now and save the results, together with the effort field with the version: they are the basis for noticing a drift when Perplexity changes the model under a level.

A migration plan in five steps

  1. Inventory: find all the Sonar calls (synchronous, streaming, asynchronous) and all the code that reads choices, citations, images, related_questions.
  2. Golden set: 30-50 real questions, with the expected facts.
  3. Test at fast and at low: with the evaluation function; choose the lowest level that passes.
  4. Shadow mode: for a week send a copy of the real traffic to the new path without showing its outcome, and compare.
  5. Switch with a spending cap: a daily counter in your service (article 6) turns a cost drift into an error.

The order is essential: the inventory says what changes, the golden set says what must not get worse, the test chooses the level, shadow mode catches what the golden questions do not cover, the spending cap protects the switch. Skipping the second step turns the migration into an act of faith. Asynchronous work moves separately, with background: true and checking by identifier, and it must go into the inventory first, because it is already stopped.

A declared scenario: the widget that changes without you touching anything

A hypothetical scenario. A two-person travel agency has on its site a widget that answers "are there strikes or events at the destination on the days of the trip?", resting on a synchronous call to Sonar. The day Perplexity rewrites that request as an Agent API request, the widget does not change a line but may change its answer: longer, with the sources in a different order, or with markers that the front end does not recognize. A customer thus receives a reassuring answer with a source that does not talk about their date.

In a sector where information steers an already paid expense, the measures are three, and they cost little: always show source and date next to the answer; a fixed sentence ("check the official site before leaving"); a weekly sample of recorded questions to reread. If the agency has promised its customers that their data is not stored, what was said in article 1 also applies: with the Agent API the server-side storage of response state exists, and store: false does not switch it off. The promise must be rechecked before migrating, not after.

What you can do now

You can say what changed in the shape of a request, a response and a citation, and you can translate a Sonar body into the equivalent body for the Agent API knowing where the translation stops. You can search your code for the points to touch, recognize the rule that makes the new markers vanish from the front end, and compare two levels on your own questions with a criterion you can repeat after every update. What remains out is what the product really answers: you will see that only with your own key. Article 5 shifts attention to development tools, with the official MCP server.

← Article 3: the Search API Article 5: Perplexity MCP →

Frequently asked questions

Is Sonar still available?

The migration page read on 13 November 2026 says that support for Sonar chat completions ended on 27 September 2026, that synchronous and streaming requests are rewritten as Agent API requests and that asynchronous ones are no longer supported.

Which effort level does sonar-pro correspond to?

The documentation gives fast as the starting point, not as an equivalence. To decide the right level you need a set of questions of your own, tested on several levels.

How do citations change?

The sources are in a search_results item of the output array, and the markers in the text are [1] at fast and [web:1] from low upwards. Code that looked for citations in the choices response must be rewritten.

What happens to asynchronous requests?

They are not rewritten and are no longer supported: they must move to the Agent API background mode, submitting with background true and checking the response state by identifier.

Later in the series you will also find article 7 on PerplexityBot and robots.txt and article 8 on what is proven about getting cited.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects