Adstract SDK for Python
Adstract integrates ad-enhanced prompts into LLM applications and provides the acknowledgment flow required to close the ad cycle after the final model response is produced.
Official Documentation
Full documentation is available at Adstract Documentation.
Install
pip install adstractai
Authentication
Pass an API key when initializing the client, or set the ADSTRACT_API_KEY
environment variable.
export ADSTRACT_API_KEY="adpk_live_123"
from adstractai import Adstract
client = Adstract()
Quickstart
from adstractai import Adstract, AdRequestContext
client = Adstract(api_key="adpk_live_123")
result = client.request_ad(
prompt="How do I improve analytics in my LLM app?",
context=AdRequestContext(
session_id="sess-1",
user_agent=(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
),
user_ip="203.0.113.24",
),
)
prompt_for_model = result.prompt
llm_response = "Your final LLM response here"
ack = client.acknowledge(
enhancement_result=result,
llm_response=llm_response,
)
if ack is not None:
print(ack.ad_ack_id)
print(ack.status)
print(ack.success)
client.close()
Core Flow
The SDK integration flow has two main steps:
- Call
request_ad()orrequest_ad_async()to get anEnhancementResult. - After your LLM produces its final response, call
acknowledge()oracknowledge_async()to close the ad cycle.
EnhancementResult.prompt always gives you the prompt your application should
use next:
- enhanced prompt when ad injection succeeds;
- original prompt when the SDK falls back.
Required Request Context
request_ad() and request_ad_async() require an AdRequestContext with:
session_iduser_agentuser_ip
from adstractai.models import AdRequestContext
context = AdRequestContext(
session_id="sess-1",
user_agent="Mozilla/5.0 (X11; Linux x86_64)",
user_ip="203.0.113.24",
)
Missing required values raise MissingParameterError, or are captured in
EnhancementResult.error when raise_exception=False.
Optional Context
Pass OptionalContext to include optional targeting signals.
from adstractai import Adstract, AdRequestContext, OptionalContext
client = Adstract(api_key="adpk_live_123")
result = client.request_ad(
prompt="How do I improve analytics in my LLM app?",
context=AdRequestContext(
session_id="sess-1",
user_agent="Mozilla/5.0 (X11; Linux x86_64)",
user_ip="203.0.113.24",
),
optional_context=OptionalContext(
country="US",
region="California",
city="San Francisco",
asn=15169,
age=30,
gender="female",
),
)
Validation rules:
| Field | Rule |
|---|---|
age |
Integer between 0 and 120 |
gender |
One of "male", "female", "other" |
country |
ISO 3166-1 alpha-2 code such as "US" |
Enhancement Results
request_ad() and request_ad_async() return EnhancementResult.
Important fields:
prompt: the prompt your application should pass to the modelsession_id: the request session identifierad_response: parsed backend response when availablesuccess: whether ad enhancement succeedederror: captured failure whenraise_exception=False
if result.success:
prompt_for_model = result.prompt
else:
print(result.error)
prompt_for_model = result.prompt
Acknowledgment Results
acknowledge() and acknowledge_async() return AdAckResponse on successful
acknowledgment.
AdAckResponse includes:
ad_ack_idstatussuccess
success means the acknowledgment itself completed successfully:
status="ok"->success=Truestatus="no_ad_used"->success=Truestatus="recoverable_error"->success=False
If enhancement_result.success is False, acknowledgment is skipped and the
method returns None.
Error Handling
By default, SDK methods raise on failure.
request_ad(..., raise_exception=True)acknowledge(..., raise_exception=True)
Set raise_exception=False if you want a fallback-first integration flow.
Enhancement exceptions
from adstractai.errors import (
AdEnhancementError,
AuthenticationError,
DuplicateAdRequestError,
NoFillError,
PromptRejectedError,
)
result = client.request_ad(
prompt="My prompt",
context=context,
raise_exception=False,
)
if result.success:
print(result.prompt)
elif isinstance(result.error, PromptRejectedError):
print("Prompt not suitable for ad injection")
elif isinstance(result.error, NoFillError):
print("No ad inventory available")
elif isinstance(result.error, DuplicateAdRequestError):
print("This message already has an ad request")
elif isinstance(result.error, AuthenticationError):
print("Authentication failed")
elif isinstance(result.error, AdEnhancementError):
print(result.error)
Acknowledgment exceptions
from adstractai.errors import (
AdResponseNotFoundError,
AuthenticationError,
DuplicateAcknowledgmentError,
UnsuccessfulAdResponseError,
)
try:
ack = client.acknowledge(
enhancement_result=result,
llm_response="Final response",
)
except AuthenticationError:
print("Authentication failed")
except AdResponseNotFoundError:
print("The ad response was not found")
except UnsuccessfulAdResponseError:
print("The ad response was not created by a successful enhancement")
except DuplicateAcknowledgmentError:
print("This response was already acknowledged")
Wrapping Type
Control how ads are wrapped in the enhanced prompt. The default is "xml".
client = Adstract(api_key="adpk_live_123", wrapping_type="markdown")
Supported values:
"xml""plain""markdown"
Async Usage
import asyncio
from adstractai import Adstract, AdRequestContext
async def main() -> None:
client = Adstract(api_key="adpk_live_123")
result = await client.request_ad_async(
prompt="Need performance tips",
context=AdRequestContext(
session_id="sess-99",
user_agent=(
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
),
user_ip="192.0.2.1",
),
)
llm_response = "Your final LLM response here"
ack = await client.acknowledge_async(
enhancement_result=result,
llm_response=llm_response,
)
if ack is not None:
print(ack.ad_ack_id)
await client.aclose()
asyncio.run(main())
Public API
| Method | Description |
|---|---|
request_ad() |
Request ad enhancement synchronously |
request_ad_async() |
Request ad enhancement asynchronously |
acknowledge() |
Report the final LLM response and return AdAckResponse |
acknowledge_async() |
Async acknowledgment flow returning AdAckResponse |
close() |
Close the owned sync HTTP client |
aclose() |
Close the owned async HTTP client |
License
This SDK is distributed under the Adstract SDK Proprietary License. See LICENSE.
Metadata
Release files for adstractai 1.0.1
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 | |
|---|---|---|---|---|
| adstractai-1.0.1.tar.gz | 23.4 kB | With provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| adstractai-1.0.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 41.9 kB
Release files / adstractai-1.0.1.tar.gz
| Download URL | adstractai-1.0.1.tar.gz |
|---|---|
| Size | 23.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5b74af110c14d4d8fa526cb95ac8ef93c7339aed55f5b46f8616de83c45473f8
|
|
BLAKE2b-256 checksum How to use checksums |
3f6c789a84abe492a563ba598630f953268d4e144518826bb76bcf99938de60b
|
| 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 Mar 17, 2026.
Transparency logRelease files / adstractai-1.0.1-py3-none-any.whl
| Download URL | adstractai-1.0.1-py3-none-any.whl |
|---|---|
| Size | 18.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
99157494cb1f249beb9e4b49662003ecdf5006f622dd1efd66f3fcb919e0859e
|
|
BLAKE2b-256 checksum How to use checksums |
3e5d5352e79759b20d1b9c4f53aa15322f8a81179afd6400ce146dc7202b3101
|
| 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 Mar 17, 2026.
Transparency logSecurity for adstractai 1.0.1
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
All 2 files in this release have been uploaded with provenance metadata.
Attestation for adstractai-1.0.1.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 Mar 17, 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.