# Google AI Mode API in Python: answer text and citations as JSON

A client asked me to "pull the AI answer" for forty questions and put it in a spreadsheet. The hard part was not the request. It was that the answer, the Markdown version, and the pages Google cites are three different things, and I wanted all three in one record.

AI Mode is not AI Overview. An AI Overview is a module on a normal results page. AI Mode answers the question in a conversation-style block and attaches the pages it used. SerpBase exposes it as `POST /google/ai_mode`, and the response has a clean `ai_mode` object: `text`, `markdown`, and `sources`.

Here is the whole call:

```python
import json
import os

import requests

API = "https://api.serpbase.dev/google/ai_mode"


def ai_mode(question: str, gl: str = "us", hl: str = "en") -> dict:
    resp = requests.post(
        API,
        headers={
            "X-API-Key": os.environ["SERPBASE_API_KEY"],
            "Content-Type": "application/json",
        },
        json={"q": question, "gl": gl, "hl": hl},
        timeout=60,
    )
    resp.raise_for_status()
    data = resp.json()

    # HTTP 200 is not the success signal. status == 0 is.
    if data.get("status") != 0:
        raise RuntimeError(
            f"status={data.get('status')} request_id={data.get('request_id')}"
        )

    block = data.get("ai_mode") or {}
    return {
        "question": question,
        "answer": block.get("text", ""),
        "markdown": block.get("markdown", ""),
        "sources": [
            {
                "title": s.get("page_title") or s.get("title"),
                "url": s.get("link"),
                "snippet": s.get("snippet"),
            }
            for s in block.get("sources", [])
        ],
        "request_id": data.get("request_id"),
        "credits_charged": data.get("credits_charged"),
    }


if __name__ == "__main__":
    result = ai_mode("how does a heat pump work")
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

The response fields I rely on:

- `ai_mode.text` — the answer as plain text.
- `ai_mode.markdown` — the same answer with headings, lists and tables kept as Markdown.
- `ai_mode.sources[]` — each cited page with `title`, `page_title`, `link`, `snippet`. `link` is the real destination, not a `google.com/goto` wrapper.
- `status`, `request_id`, `credits_charged` — from the envelope, next to the payload.

A trimmed response looks like this (fields only, text shortened):

```json
{
  "status": 0,
  "request_id": "r-...",
  "credits_charged": 1,
  "product_id": "google_ai_mode",
  "query": "how does a heat pump work",
  "ai_mode": {
    "text": "A heat pump moves heat instead of generating it...",
    "markdown": "## How it works\n\nA heat pump moves heat...",
    "sources": [
      {
        "title": "Heat pump",
        "page_title": "Heat pump - Wikipedia",
        "link": "https://en.wikipedia.org/wiki/Heat_pump",
        "snippet": "A heat pump is a device that transfers heat energy..."
      }
    ]
  }
}
```

## Checking whether Google cited you

The reason I wanted `sources` as structured data was to answer a simple question: did the AI answer use our page? Once the call returns a dict, that is a one-liner:

```python
from urllib.parse import urlparse


def cited(result: dict, domain: str) -> list[dict]:
    return [
        s
        for s in result["sources"]
        if urlparse(s["url"]).netloc.endswith(domain)
    ]


hits = cited(result, "serpbase.dev")
print(len(hits))
```

Run it for a fixed list of questions once a day, store the JSON, and you have a citation monitor. The same loop also gives you the answer text, so you can diff what changed.

## Two details that matter

`format` changes the response type. The default `json` gives the envelope above. With `"format": "markdown"` the endpoint returns Markdown directly (`text/markdown`, no envelope), which is the right shape for feeding an LLM. Keep the JSON mode when you need the citations and the request ID.

The endpoint is priced per request. At the time of writing (2026-11-16) it is 1 credit under a launch promo; the docs say it becomes 3 credits on 2026-11-26 16:00 UTC. Failed requests return a non-zero `status` and are not charged.

The request contract and field names are in the [Google AI Mode API docs](https://serpbase.dev/docs/google_ai_mode). I work on SerpBase, so that is our endpoint; the code above is the same call I use when I need the answer and its sources in one record.

Pick twenty questions your buyers actually ask, run them through the function, and check the `sources` list before you write anything else. The answer is the easy part. The citations tell you whether you are in the conversation at all.
