Skip to main content

Ad network that delivers ads to the LLM's response

Project description

Adstract SDK for Python

Python Python 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:

  1. Call request_ad() or request_ad_async() to get an EnhancementResult.
  2. After your LLM produces its final response, call acknowledge() or acknowledge_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_id
  • user_agent
  • user_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 model
  • session_id: the request session identifier
  • ad_response: parsed backend response when available
  • success: whether ad enhancement succeeded
  • error: captured failure when raise_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_id
  • status
  • success

success means the acknowledgment itself completed successfully:

  • status="ok" -> success=True
  • status="no_ad_used" -> success=True
  • status="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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

adstractai-1.0.1.tar.gz (23.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

adstractai-1.0.1-py3-none-any.whl (18.5 kB view details)

Uploaded Python 3

File details

Details for the file adstractai-1.0.1.tar.gz.

File metadata

  • Download URL: adstractai-1.0.1.tar.gz
  • Upload date:
  • Size: 23.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for adstractai-1.0.1.tar.gz
Algorithm Hash digest
SHA256 5b74af110c14d4d8fa526cb95ac8ef93c7339aed55f5b46f8616de83c45473f8
MD5 f61f89ec450372ba4e368fc013d323b9
BLAKE2b-256 3f6c789a84abe492a563ba598630f953268d4e144518826bb76bcf99938de60b

See more details on using hashes here.

Provenance

The following attestation bundles were made for adstractai-1.0.1.tar.gz:

Publisher: publish.yml on Adstract-AI/adstract-library

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file adstractai-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: adstractai-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 18.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for adstractai-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 99157494cb1f249beb9e4b49662003ecdf5006f622dd1efd66f3fcb919e0859e
MD5 14e0e7935c55a31f4ca7ed8d48ec0c9a
BLAKE2b-256 3e5d5352e79759b20d1b9c4f53aa15322f8a81179afd6400ce146dc7202b3101

See more details on using hashes here.

Provenance

The following attestation bundles were made for adstractai-1.0.1-py3-none-any.whl:

Publisher: publish.yml on Adstract-AI/adstract-library

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page