Skip to main content

Ad network that delivers ads to the LLM's response

Project description

Adstract AI Python SDK

Python Python Python

Ad network SDK that enhances LLM prompts with integrated advertisements.

Official Documentation

Full documentation is available at: https://adstract-ai.github.io/adstract-documentation/

Install

pip install adstractai

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",
    ),
)

# Enhanced prompt with integrated ads, or original prompt on failure
print(result.prompt)

client.close()

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()

Required Parameters

request_ad and request_ad_async require session_id, user_agent, and user_ip. Missing any of these returns an EnhancementResult with success=False and a MissingParameterError in error.

from adstractai import Adstract, AdRequestContext
from adstractai.errors import MissingParameterError

client = Adstract(api_key="adpk_live_123")

result = client.request_ad(
    prompt="Test prompt",
    context=AdRequestContext(
        session_id="sess-1",
        user_agent="",        # empty — will trigger MissingParameterError
        user_ip="203.0.113.24",
    ),
    raise_exception=False,
)

if isinstance(result.error, MissingParameterError):
    print(f"Missing parameter: {result.error}")

Optional Context

Pass an OptionalContext to provide additional 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 ...",
        user_ip="203.0.113.24",
    ),
    optional_context=OptionalContext(
        country="US",
        region="California",
        city="San Francisco",
        asn=15169,
        age=30,
        gender="female",
    ),
)

OptionalContext fields are all optional. Validation rules:

Field Rule
age Integer between 0 and 120 inclusive
gender One of "male", "female", "other"
country ISO 3166-1 alpha-2 code (e.g. "US", "DE")

Error Handling

By default (raise_exception=True) errors are raised as exceptions. Set raise_exception=False to receive errors in the result instead, which is useful when you want the original prompt as a fallback.

from adstractai import Adstract, AdRequestContext
from adstractai.errors import (
    AdEnhancementError,
    NoFillError,
    PromptRejectedError,
)

client = Adstract(api_key="adpk_live_123")

result = client.request_ad(
    prompt="My prompt",
    context=AdRequestContext(
        session_id="sess-1",
        user_agent="Mozilla/5.0 ...",
        user_ip="203.0.113.24",
    ),
    raise_exception=False,
)

if result.success:
    print(result.prompt)          # enhanced prompt
elif isinstance(result.error, PromptRejectedError):
    print("Prompt not suitable for ad injection")
    print(result.prompt)          # original prompt
elif isinstance(result.error, NoFillError):
    print("No ad inventory available")
    print(result.prompt)          # original prompt
elif isinstance(result.error, AdEnhancementError):
    print(f"Enhancement failed: {result.error}")

Both PromptRejectedError and NoFillError are subclasses of AdEnhancementError.

Acknowledge

After sending the enhanced prompt to your LLM and receiving a response, call acknowledge to report the outcome back to Adstract.

llm_response = "..."   # response from your LLM

client.acknowledge(
    enhancement_result=result,
    llm_response=llm_response,
)

acknowledge is a no-op when result.success is False, so it is safe to call unconditionally.

Wrapping Type

Control how ads are wrapped in the enhanced prompt. Defaults to "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",
        ),
    )

    print(result.prompt)

    if result.success:
        llm_response = "..."  # your LLM call here
        await client.acknowledge_async(
            enhancement_result=result,
            llm_response=llm_response,
        )

    await client.aclose()

asyncio.run(main())

Available Methods

Method Description
request_ad() Request ad enhancement (sync)
request_ad_async() Request ad enhancement (async)
acknowledge() Report LLM response back to Adstract (sync)
acknowledge_async() Report LLM response back to Adstract (async)
close() Close the sync HTTP client
aclose() Close the async HTTP client

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.0.tar.gz (20.3 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.0-py3-none-any.whl (16.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: adstractai-1.0.0.tar.gz
  • Upload date:
  • Size: 20.3 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.0.tar.gz
Algorithm Hash digest
SHA256 453e9d29905640dee698c030a5392a39ddf1824ae56932020625038eb291f78c
MD5 d1a5349dea92784f6edc021b922e03c6
BLAKE2b-256 b6d82112e7bedd961243f37e397ba8cbc9380840d0a7c17077c7692713222edd

See more details on using hashes here.

Provenance

The following attestation bundles were made for adstractai-1.0.0.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.0-py3-none-any.whl.

File metadata

  • Download URL: adstractai-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 16.2 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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e24f747199998aa16d92734718b4562b5ffe7180da2e7cab8aaa0e3744da5663
MD5 100771eea8d62734967b3036fc0b310a
BLAKE2b-256 7419686328fcfdb59ee2581790b9d270cbfd3949c3bab8479009b63b01b652e5

See more details on using hashes here.

Provenance

The following attestation bundles were made for adstractai-1.0.0-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