Python server SDK for fetching Gravity ads
Project description
gravity-py
Python SDK for requesting ads from the Gravity API.
from gravity_sdk import Gravity
gravity = Gravity(production=True) # reads GRAVITY_API_KEY from env
result = await gravity.get_ads(request, messages, placements)
Works with FastAPI, Starlette, Django, and Flask. Only dependency is httpx.
Install
pip install gravity-sdk
Set GRAVITY_API_KEY in your server environment.
Integration
Add a few lines to your existing streaming chat endpoint. The ad request runs in parallel with your LLM call — zero added latency.
+ import asyncio
+ from gravity_sdk import Gravity
+ gravity = Gravity(production=True)
@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": "chat", "placement_id": "main"}])
+ )
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")
gravity.get_ads() takes your server's request object, the conversation messages, and your ad placements, then calls the Gravity API and returns the ads. Never raises — returns AdResult(ads=[]) on any failure.
Message handling
The SDK sends the last 2 conversational messages to the Gravity API for contextual ad matching. Only messages with recognized conversational roles are included:
user,assistant,system,developer,model(Gemini's alias forassistant)
Messages with other roles (e.g. tool, function, ipython) are filtered out because they typically contain structured data rather than natural language.
Constructor
Gravity(*, api_key=None, api_url=None, timeout=3.0, production=False, relevancy=0.2)
| Parameter | Type | Description |
|---|---|---|
api_key |
str |
Gravity API key (default: GRAVITY_API_KEY env var) |
api_url |
str |
Gravity API endpoint URL (default: production) |
timeout |
float |
Request timeout in seconds (default: 3.0) |
production |
bool |
Serve real ads when True. Defaults to False (test ads). |
relevancy |
float |
Minimum relevancy threshold, 0.0–1.0 (default: 0.2). Lower = more ads with weaker contextual matches. |
The client reuses its HTTP connection pool across calls. Use async with Gravity() as g: or call await gravity.close() for explicit cleanup.
Return types
@dataclass
class AdResult:
ads: list[AdResponse] # Parsed ad objects
status: int # 200, 204, 0 (error)
elapsed_ms: str # e.g. "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
Both have .to_dict() methods that serialize to the camelCase JSON shape renderers expect.
Development
uv sync
uv run pytest
uv run ruff check src/ tests/
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file gravity_sdk-0.1.0.tar.gz.
File metadata
- Download URL: gravity_sdk-0.1.0.tar.gz
- Upload date:
- Size: 9.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
535ac51a1bdb40e69a5507cf580872eae097ac64d08cd48604fe4fa2cdb2cd88
|
|
| MD5 |
67bc9d7492666be16edd7d0c56320702
|
|
| BLAKE2b-256 |
131e710da3172b28f3831d42ec841744ea3fece5a33dba4cc3a92015b16a9f2e
|
Provenance
The following attestation bundles were made for gravity_sdk-0.1.0.tar.gz:
Publisher:
workflow.yml on Try-Gravity/gravity-py
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
gravity_sdk-0.1.0.tar.gz -
Subject digest:
535ac51a1bdb40e69a5507cf580872eae097ac64d08cd48604fe4fa2cdb2cd88 - Sigstore transparency entry: 975437852
- Sigstore integration time:
-
Permalink:
Try-Gravity/gravity-py@96693b3562546f9d35868405633b33a0fd5be231 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/Try-Gravity
-
Access:
internal
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
workflow.yml@96693b3562546f9d35868405633b33a0fd5be231 -
Trigger Event:
release
-
Statement type:
File details
Details for the file gravity_sdk-0.1.0-py3-none-any.whl.
File metadata
- Download URL: gravity_sdk-0.1.0-py3-none-any.whl
- Upload date:
- Size: 8.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
82a43ead6c63c7808be304f13197c11f0862c1b6cb75ed75e5b710138e86afd4
|
|
| MD5 |
726b7633a411fad3594432105c7b203c
|
|
| BLAKE2b-256 |
5acb347dc2367e545021b6814eccdd8b79a88ff92ca467e9fa5b069cfef1bd8d
|
Provenance
The following attestation bundles were made for gravity_sdk-0.1.0-py3-none-any.whl:
Publisher:
workflow.yml on Try-Gravity/gravity-py
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
gravity_sdk-0.1.0-py3-none-any.whl -
Subject digest:
82a43ead6c63c7808be304f13197c11f0862c1b6cb75ed75e5b710138e86afd4 - Sigstore transparency entry: 975437862
- Sigstore integration time:
-
Permalink:
Try-Gravity/gravity-py@96693b3562546f9d35868405633b33a0fd5be231 -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/Try-Gravity
-
Access:
internal
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
workflow.yml@96693b3562546f9d35868405633b33a0fd5be231 -
Trigger Event:
release
-
Statement type: