Skip to main content

Prefactor HTTP Client

A low-level async HTTP client for the Prefactor API.

Features

  • Typed Endpoint Clients: Dedicated clients for agent instances, agent spans, and bulk operations
  • Automatic Retries: Exponential backoff with jitter for transient failures
  • Type Safety: Full Pydantic models for all request/response data
  • Clear Error Hierarchy: Specific exception types for different failure modes
  • Idempotency: Built-in support for idempotency keys

Installation

pip install prefactor-http

Quick Start

import asyncio
from prefactor_http import PrefactorHttpClient, HttpClientConfig


async def main():
    config = HttpClientConfig(
        api_url="https://app.prefactorai.com",
        api_token="your-api-token",
    )

    async with PrefactorHttpClient(config) as client:
        instance = await client.agent_instances.register(
            agent_id="agent_123",
            agent_version={"name": "My Agent", "external_identifier": "v1.0.0"},
            agent_schema_version={
                "external_identifier": "v1.0.0",
                "span_type_schemas": [
                    {
                        "name": "agent:llm",
                        "title": "LLM Call",
                        "description": "A call to a language model",
                        "params_schema": {
                            "type": "object",
                            "properties": {
                                "model": {"type": "string"},
                                "prompt": {"type": "string"},
                            },
                            "required": ["model", "prompt"],
                        },
                        "result_schema": {
                            "type": "object",
                            "properties": {"response": {"type": "string"}},
                        },
                        "template": "{{model}}: {{prompt}} → {{response}}",
                    },
                ],
            },
        )
        print(f"Registered instance: {instance.id}")


asyncio.run(main())

agent_instances.register() supports two auth modes:

  • Account-scoped token: pass agent_id and usually environment_id.
  • Deployment-scoped token: omit agent_id and environment_id; the API derives both from the token.

Endpoints

Agent Instances (client.agent_instances)

# Register a new agent instance
instance = await client.agent_instances.register(
    agent_id="agent_123",
    agent_version={
        "name": "My Agent",
        "external_identifier": "v1.0.0",
        "description": "Optional description",
    },
    agent_schema_version={
        "external_identifier": "schema-v1",
        "span_type_schemas": [
            {
                "name": "agent:llm",
                "title": "LLM Call",  # Optional
                "description": "A call to a language model",  # Optional
                "params_schema": {"type": "object", "properties": {...}},
                "result_schema": {"type": "object", "properties": {...}},  # Optional
                "template": "{{model}}: {{prompt}} → {{response}}",  # Optional
            },
        ],
        # Alternatively, use flat maps for simpler cases:
        # "span_schemas": {"agent:llm": {"type": "object", ...}},
        # "span_result_schemas": {"agent:llm": {"type": "object", ...}},
    },
    id=None,  # Optional: pre-assign an ID
    idempotency_key=None,  # Optional: idempotency key
    update_current_version=True,  # Optional: update the agent's current version
)

# Register with a deployment-scoped token
instance = await client.agent_instances.register(
    agent_version={
        "name": "My Agent",
        "external_identifier": "v1.0.0",
    },
    agent_schema_version={
        "external_identifier": "schema-v1",
        "span_type_schemas": [],
    },
)

# Start an instance
instance = await client.agent_instances.start(
    agent_instance_id=instance.id,
    timestamp=None,  # Optional: override start time
    idempotency_key=None,
)

# Finish an instance
instance = await client.agent_instances.finish(
    agent_instance_id=instance.id,
    status=None,  # Optional: "complete" | "failed" | "cancelled"
    timestamp=None,  # Optional: override finish time
    idempotency_key=None,
)

The AgentInstance response includes: id, agent_id, status, started_at, finished_at, span_counts, and more.

Agent Spans (client.agent_spans)

# Create a span
span = await client.agent_spans.create(
    agent_instance_id="instance_123",
    schema_name="agent:llm",
    status="active",
    payload={"model": "gpt-4", "prompt": "Hello"},  # Optional
    result_payload=None,  # Optional
    id=None,  # Optional: pre-assign an ID
    parent_span_id=None,  # Optional: parent for nesting
    started_at=None,  # Optional: override start time
    finished_at=None,
    idempotency_key=None,
)

# Finish a span
span = await client.agent_spans.finish(
    agent_span_id=span.id,
    status=None,  # Optional: "complete" | "failed" | "cancelled"
    result_payload=None,  # Optional: final result data
    timestamp=None,  # Optional: override finish time
    idempotency_key=None,
)

The AgentSpan response includes: id, agent_instance_id, schema_name, status, payload, result_payload, parent_span_id, started_at, finished_at, and more.

Bulk Operations (client.bulk)

Execute multiple POST actions in a single HTTP request.

from prefactor_http import BulkRequest, BulkItem

request = BulkRequest(
    items=[
        BulkItem(
            _type="agent_instances/register",
            idempotency_key="register-instance-001",
            agent_id="agent_123",
            agent_version={"name": "My Agent", "external_identifier": "v1.0.0"},
            agent_schema_version={
                "external_identifier": "v1.0.0",
                "span_type_schemas": [
                    {
                        "name": "agent:llm",
                        "title": "LLM Call",
                        "params_schema": {
                            "type": "object",
                            "properties": {
                                "model": {"type": "string"},
                                "prompt": {"type": "string"},
                            },
                            "required": ["model", "prompt"],
                        },
                        "result_schema": {
                            "type": "object",
                            "properties": {"response": {"type": "string"}},
                        },
                    },
                ],
            },
        ),
        BulkItem(
            _type="agent_spans/create",
            idempotency_key="create-span-001",
            agent_instance_id="instance_123",
            schema_name="agent:llm",
            status="active",
        ),
    ]
)

response = await client.bulk.execute(request)

for key, output in response.outputs.items():
    print(f"{key}: {output.status}")  # "success" or "error"

Validation rules:

  • Each item must have a unique idempotency_key (8–64 characters)
  • The request must contain at least one item

Error Handling

from prefactor_http import (
    PrefactorHttpError,
    PrefactorApiError,
    PrefactorAuthError,
    PrefactorNotFoundError,
    PrefactorValidationError,
    PrefactorRetryExhaustedError,
    PrefactorClientError,
)

try:
    async with PrefactorHttpClient(config) as client:
        instance = await client.agent_instances.register(...)
except PrefactorValidationError as e:
    print(f"Validation error: {e.errors}")
except PrefactorAuthError:
    print("Authentication failed - check your API token")
except PrefactorNotFoundError:
    print("Resource not found")
except PrefactorRetryExhaustedError as e:
    print(f"Request failed after retries: {e.last_error}")
except PrefactorApiError as e:
    print(f"API error {e.status_code}: {e.code}")

Configuration

config = HttpClientConfig(
    # Required
    api_url="https://app.prefactorai.com",
    api_token="your-token",
    # Retry behavior
    max_retries=3,
    initial_retry_delay=1.0,
    max_retry_delay=60.0,
    retry_multiplier=2.0,
    # Timeouts
    request_timeout=30.0,
    connect_timeout=10.0,
)

Types

from prefactor_http import AgentStatus, FinishStatus

# AgentStatus = Literal["pending", "active", "complete", "failed", "cancelled", "terminated"]
# FinishStatus = Literal["complete", "failed", "cancelled"]

License

MIT

Metadata

Release files for prefactor-http 0.4.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for prefactor-http 0.4.2
File Size Uploaded
prefactor_http-0.4.2.tar.gz 28.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for prefactor-http 0.4.2
File Interpreter ABI Platform
prefactor_http-0.4.2-py3-none-any.whl Python 3 none any Details

Total release size: 56.0 kB

Release files / prefactor_http-0.4.2.tar.gz

Download URL prefactor_http-0.4.2.tar.gz
Size 28.3 kB
Tags Source
SHA-256 checksum
How to use checksums
f0d74f9d72f4783e6187686901d30930429477d8274993bbd98c31b166ceaea0
BLAKE2b-256 checksum
How to use checksums
3a469f255ccedd9f087b0881445a2eea9af89dc5597eb2832c9713ed356d7471
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / prefactor_http-0.4.2-py3-none-any.whl

Download URL prefactor_http-0.4.2-py3-none-any.whl
Size 27.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f04c04306e6aa07cbfd10a37b74a84c5b4bc5d7947a98cecc37742508ce81b0f
BLAKE2b-256 checksum
How to use checksums
10b0a0d4ca6625f81d4221312b811b73daaa3c8e95038c98e84366bed22320a9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release history Release notifications | RSS feed

0.4.3

2 release files

This release

0.4.2 This release

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

1 release file

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page