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

# Python SDK

> Request contextual ads from the Gravity API in a Python server.

Use the `gravity-sdk` package to request Gravity ads from your Python server. This page describes version 0.1.0, the version on PyPI. For the terms on this page, see [Core concepts](https://docs.trygravity.com/introduction/concepts.md).

## Before you start

* Your server runs Python 3.10 or later.
* You have a Gravity API key. Get it from your dashboard under **Settings → Platform Settings**.
* Your web client calls `gravityContext()` from `@gravity-ai/api` and posts the result as `gravity_context`. See [Prepare the context](https://docs.trygravity.com/sdks/javascript.md#step-1-prepare-the-context-in-the-client).

## Install

1. Install the package. Its only dependency is [httpx](https://www.python-httpx.org/).

   ```bash theme={null}
   pip install gravity-sdk
   ```

2. Set `GRAVITY_API_KEY` in your server environment.

## Quick start

Add these lines to the chat endpoint that streams your model response. The ad request runs at the same time as your model call, so it does not delay the response.

```diff theme={null}
+ import asyncio
+ from gravity_sdk import Gravity

+ gravity = Gravity()

  @app.post("/api/chat")
  async def chat(request: Request):
      body = await request.json()
      messages = body["messages"]

+     ad_task = asyncio.create_task(
+         gravity.get_ads(request, messages, [{"placement": "below_response", "placement_id": "YOUR_PLACEMENT_ID"}])
+     )

      async def event_stream():
          async for token in stream_your_llm(messages):
              yield f"data: {json.dumps({'type': 'chunk', 'content': token})}\n\n"

-         yield f"data: {json.dumps({'type': 'done'})}\n\n"
+         ad_result = await ad_task
+         ads = [a.to_dict() for a in ad_result.ads]
+         yield f"data: {json.dumps({'type': 'done', 'ads': ads})}\n\n"

      return StreamingResponse(event_stream(), media_type="text/event-stream")
```

The last event of the stream contains the ads. When no ad matches, `ads` is an empty list. The SDK works with **FastAPI**, **Starlette**, **Django**, and **Flask**.

## Constructor

```python theme={null}
Gravity(*, api_key=None, api_url="https://server.trygravity.ai/api/v1/ad", timeout=3.0, production=False, relevancy=0.2)
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `api_key` | `str` | The `GRAVITY_API_KEY` environment variable | Your Gravity API key. |
| `api_url` | `str` | `https://server.trygravity.ai/api/v1/ad` | The Gravity ad endpoint. |
| `timeout` | `float` | `3.0` | The request timeout in seconds. |
| `production` | `bool` | `False` | When `False`, Gravity returns test ads and does not bill. |
| `relevancy` | `float` | `0.2` | The minimum relevancy, from 0.0 to 1.0. A lower value returns more ads with weaker matches. |

The client keeps its HTTP connection pool between calls. To close it, use `async with Gravity() as g:` or call `await gravity.close()`.

## `get_ads()`

```python theme={null}
await gravity.get_ads(request, messages, placements, *, production=None, relevancy=None)
```

From version 0.6.0, `get_ads()` also takes `consent`:

```python theme={null}
await gravity.get_ads(request, messages, placements, *, production=None, relevancy=None, consent=None)
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `request` | Framework request | Required | The request object of your server (FastAPI, Django, Flask, and others). |
| `messages` | `list[dict]` | Required | The conversation messages: `[{"role": ..., "content": ...}]`. |
| `placements` | `list[dict]` | Required | The ad slots, for example `[{"placement": "below_response", "placement_id": "YOUR_PLACEMENT_ID"}]`. |
| `production` | `bool \| None` | `None` | Replaces the `production` value of the constructor for this call. |
| `relevancy` | `float \| None` | `None` | Replaces the `relevancy` value of the constructor for this call. |
| `consent` | `Consent \| None` | `None` | From version 0.6.0. The end user's privacy signals. Replaces `gravity_context.consent` as a whole. See [Send privacy signals](https://docs.trygravity.com/ai-platforms/privacy-signals.md). |

`get_ads()` reads `gravity_context` (session, user, and device) from the body of the request. It adds the end user's IP address from the request headers. It does not make a device object. Your browser client must call `gravityContext()` and post the result, and your backend must keep it in the body.

Privacy signals are required. Version 0.1.0 doesn't forward the `consent` object from `gravity_context`. From version 0.6.0, `get_ads()` forwards it, sets `gpc` to `True` when the incoming request has `Sec-GPC: 1`, and takes a `consent` argument: a `Consent` dict (exported from `gravity_sdk`) with the keys `gdprApplies`, `tcfString`, `usPrivacy`, `gpc`, `gpp`, and `gppSid`. An explicit `consent` replaces `gravity_context.consent` as a whole. With an earlier version, request ads with a [direct HTTP request](https://docs.trygravity.com/ai-platforms/request-ads.md) that includes `consent`. See [Send privacy signals](https://docs.trygravity.com/ai-platforms/privacy-signals.md).

```python theme={null}
await gravity.get_ads(request, messages, placements, consent={"gpp": gpp_string, "gppSid": [7], "gpc": True})
```

> [!WARNING]
>
> Forward the `device` object from the client, with `device.ip` and `device.ua`, in each request. If the request has no end-user `ua` and `ip`, Gravity cannot run fraud and bot detection on it, and the Device and Geography reports do not include it. See [Device signals](https://docs.trygravity.com/ai-platforms/request-ads.md#device-signals).

`get_ads()` never raises an exception. On any failure, it returns an `AdResult` with an empty `ads` list. You can await it at the end of your stream with no risk to the stream.

## User tags and model usage

`user.tags` travel in the `gravity_context.user` your client posts, next to the user ID: `{ "gravity_context": { "user": { "userId": "u123", "tags": { "plan": "free" } } } }`. See [Understand what your users earn you](https://docs.trygravity.com/ai-platforms/user-earnings.md) for the rules.

> [!NOTE]
>
> `gravity-sdk` doesn't have a model `usage` option. To report model usage, send it in a direct HTTP request to the ad API: see [Report model usage](https://docs.trygravity.com/ai-platforms/request-ads.md#report-model-usage).

## Return types

```python theme={null}
@dataclass
class AdResult:
    ads: list[AdResponse]   # Parsed ad objects
    status: int             # 200, 204, an error status, or 0 (no response)
    elapsed_ms: str         # for example "142"
    request_body: dict | None
    error: str | None

@dataclass
class AdResponse:
    ad_text: str
    title: str | None
    cta: str | None
    brand_name: str | None
    url: str | None
    favicon: str | None
    imp_url: str | None
    click_url: str | None
    placement: str | None
    placement_id: str | None
```

Both classes have a `to_dict()` method. It returns the camelCase JSON shape that the JavaScript renderers use.

> [!NOTE]
>
> `AdResponse` in version 0.1.0 keeps only the fields above. It drops `renderer_spec`, `brandImage`, and the experiment fields. A React `GravityAd` that gets these ads shows the built-in text card.

## Messages that the SDK sends

The SDK sends the last two conversation messages to Gravity for contextual matching. It keeps only messages with these roles:

* `user`, `assistant`, `system`, `developer`, and `model` (the Gemini name for `assistant`)

The SDK removes messages with other roles (for example `tool`, `function`, or `ipython`), because they usually contain structured data, not natural language.

## Experiments

Gravity runs experiments on the server. Return the ad as usual and show it with the standard SDK component. You do not need experiment code.

## Troubleshoot

| Problem | Cause and fix |
| - | - |
| `status` is `0` and `error` has a message | The request did not get a response, for example because of a timeout. Read `error`. |
| `status` is `401` | The API key is not valid. Copy it again from the dashboard. |
| The log shows "no API key provided" | The SDK found no key. Set `GRAVITY_API_KEY` or pass `api_key`. |
| `status` is `204` | No ad matched. This is a normal result. Hide the slot. |
| The dashboard shows your server as the device | The request body has no `gravity_context`. Send it from the client and keep it in the body. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.