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
Metadata
Release files for gravity-sdk 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| gravity_sdk-0.1.0.tar.gz | 9.6 kB | With provenance | Details for gravity_sdk-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| gravity_sdk-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for gravity_sdk-0.1.0-py3-none-any.whl |
Total release size: 18.0 kB
Release files / gravity_sdk-0.1.0.tar.gz
| Download URL | gravity_sdk-0.1.0.tar.gz |
|---|---|
| Size | 9.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
535ac51a1bdb40e69a5507cf580872eae097ac64d08cd48604fe4fa2cdb2cd88
|
|
BLAKE2b-256 checksum How to use checksums |
131e710da3172b28f3831d42ec841744ea3fece5a33dba4cc3a92015b16a9f2e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Feb 21, 2026.
Transparency logRelease files / gravity_sdk-0.1.0-py3-none-any.whl
| Download URL | gravity_sdk-0.1.0-py3-none-any.whl |
|---|---|
| Size | 8.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
82a43ead6c63c7808be304f13197c11f0862c1b6cb75ed75e5b710138e86afd4
|
|
BLAKE2b-256 checksum How to use checksums |
5acb347dc2367e545021b6814eccdd8b79a88ff92ca467e9fa5b069cfef1bd8d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Feb 21, 2026.
Transparency logSecurity for gravity-sdk 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for gravity_sdk-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Feb 21, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.