Skip to content

prefactor_http package

Prefactor HTTP Client - Async HTTP client for Prefactor API.

This package provides a high-level async HTTP client for interacting with the Prefactor API, including:

  • AgentInstance endpoints (register, start, finish)
  • AgentSpan endpoints (create, finish)
  • Bulk endpoints (execute multiple operations)
  • Automatic retry with exponential backoff
  • Comprehensive error handling
  • Type-safe data models
>>> import asyncio
>>> from prefactor_http import PrefactorHttpClient, HttpClientConfig
>>>
>>> async def main():
... config = HttpClientConfig(
... api_url="https://api.prefactor.ai",
... api_token="your-token"
... )
... async with PrefactorHttpClient(config) as client:
... instance = await client.agent_instances.register(...)
... print(instance)
>>>
>>> asyncio.run(main())

class prefactor_http.AgentInstance(, type: Literal[‘agent_instance’], id: str, account_id: str, agent_id: str, agent_version_id: str, environment_id: str, status: Literal[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’], inserted_at: datetime, updated_at: datetime, started_at: datetime | None = None, finished_at: datetime | None = None, span_counts: AgentInstanceSpanCounts | None = None)

Section titled “class prefactor_http.AgentInstance(, type: Literal[‘agent_instance’], id: str, account_id: str, agent_id: str, agent_version_id: str, environment_id: str, status: Literal[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’], inserted_at: datetime, updated_at: datetime, started_at: datetime | None = None, finished_at: datetime | None = None, span_counts: AgentInstanceSpanCounts | None = None)”

Bases: BaseModel

Agent instance model.

Resource type (always “agent_instance”)

  • Type: Literal[‘agent_instance’]

Instance ID

  • Type: str

Account ID

  • Type: str

Agent ID

  • Type: str

Agent version ID

  • Type: str

Environment ID

  • Type: str

Instance status

  • Type: Literal[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’]

When the instance was created

  • Type: datetime.datetime

When the instance was last updated

  • Type: datetime.datetime

When the instance started (null if not started)

  • Type: datetime.datetime | None

When the instance finished (null if not finished)

  • Type: datetime.datetime | None

Span counts for this instance

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

status : Literal[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’]

Section titled “status : Literal[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’]”

class prefactor_http.AgentInstanceSpanCounts(, total: int, pending: int, active: int, complete: int, failed: int, cancelled: int, finished: int)

Section titled “class prefactor_http.AgentInstanceSpanCounts(, total: int, pending: int, active: int, complete: int, failed: int, cancelled: int, finished: int)”

Bases: BaseModel

Span counts for an agent instance.

Total number of spans

  • Type: int

Number of pending spans

  • Type: int

Number of active spans

  • Type: int

Number of completed spans

  • Type: int

Number of failed spans

  • Type: int

Number of cancelled spans

  • Type: int

Number of finished spans (complete + failed + cancelled)

  • Type: int

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class prefactor_http.AgentSchemaVersionForRegister(, external_identifier: str | None = None, span_schemas: dict[str, dict] | None = None, span_result_schemas: dict[str, dict] | None = None, span_type_schemas: list[SpanTypeSchemaForCreate] | None = None)

Section titled “class prefactor_http.AgentSchemaVersionForRegister(, external_identifier: str | None = None, span_schemas: dict[str, dict] | None = None, span_result_schemas: dict[str, dict] | None = None, span_type_schemas: list[SpanTypeSchemaForCreate] | None = None)”

Bases: BaseModel

Schema version information for registration.

External identifier for the schema version

  • Type: str | None

Map of span type names to JSON schemas

  • Type: dict[str, dict] | None

Map of span type names to result JSON schemas

  • Type: dict[str, dict] | None

List of span type schema details

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

span_result_schemas : dict[str, dict] | None

Section titled “span_result_schemas : dict[str, dict] | None”

class prefactor_http.AgentSpan(*, type: ~typing.Literal[‘agent_span’], id: str, account_id: str | None = None, agent_id: str | None = None, agent_instance_id: str, parent_span_id: str | None = None, schema_name: str, schema_title: str | None = None, status: ~typing.Literal[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’], payload: dict = , result_payload: dict | None = None, summary: str | None = None, started_at: ~datetime.datetime | None = None, inserted_at: ~datetime.datetime | None = None, updated_at: ~datetime.datetime | None = None, finished_at: ~datetime.datetime | None = None)

Section titled “class prefactor_http.AgentSpan(*, type: ~typing.Literal[‘agent_span’], id: str, account_id: str | None = None, agent_id: str | None = None, agent_instance_id: str, parent_span_id: str | None = None, schema_name: str, schema_title: str | None = None, status: ~typing.Literal[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’], payload: dict = , result_payload: dict | None = None, summary: str | None = None, started_at: ~datetime.datetime | None = None, inserted_at: ~datetime.datetime | None = None, updated_at: ~datetime.datetime | None = None, finished_at: ~datetime.datetime | None = None)”

Bases: BaseModel

Agent span model.

Resource type (always “agent_span”)

  • Type: Literal[‘agent_span’]

Span ID

  • Type: str

Account ID

  • Type: str | None

Agent ID

  • Type: str | None

Agent instance ID

  • Type: str

Parent span ID (None if root span)

  • Type: str | None

Name of the schema for this span

  • Type: str

Title of the schema for this span

  • Type: str | None

Span status

  • Type: Literal[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’]

Span payload data

  • Type: dict

Result payload data

  • Type: dict | None

Optional span summary

  • Type: str | None

When the span started

  • Type: datetime.datetime | None

When the span was created

  • Type: datetime.datetime | None

When the span was last updated

  • Type: datetime.datetime | None

When the span finished (None if in progress)

  • Type: datetime.datetime | None

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

status : Literal[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’]

Section titled “status : Literal[‘pending’, ‘active’, ‘complete’, ‘failed’, ‘cancelled’]”

class prefactor_http.AgentVersionForRegister(, name: str | None = None, external_identifier: str | None = None, description: str | None = None)

Section titled “class prefactor_http.AgentVersionForRegister(, name: str | None = None, external_identifier: str | None = None, description: str | None = None)”

Bases: BaseModel

Agent version information for registration.

Name of the agent version

  • Type: str | None

External identifier for the version (e.g., “v1.0.0”)

  • Type: str | None

Optional description of the version

  • Type: str | None

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class prefactor_http.ApiResponse(, status: str, details: T)

Section titled “class prefactor_http.ApiResponse(, status: str, details: T)”

Bases: BaseModel, Generic[T]

Generic API response wrapper.

Response status (always “success” for successful requests)

  • Type: str

Detailed response data

  • Type: prefactor_http.models.base.T

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class prefactor_http.BulkItem(, _type: str, idempotency_key: Annotated[str, MinLen(min_length=8), MaxLen(max_length=64)], **extra_data: Any)

Section titled “class prefactor_http.BulkItem(, _type: str, idempotency_key: Annotated[str, MinLen(min_length=8), MaxLen(max_length=64)], **extra_data: Any)”

Bases: BaseModel

A single item in a bulk request.

Each item must include _type and idempotency_key, plus any additional parameters required by the specific action type.

Required unique idempotency key for this item. Must be at least 8 characters long and unique within the request.

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

The type of query/action to execute (e.g., ‘agents/list’, ‘agents/create’).

class prefactor_http.BulkOutput(, status: str, **extra_data: Any)

Section titled “class prefactor_http.BulkOutput(, status: str, **extra_data: Any)”

Bases: BaseModel

Output from a query or action.

Contains either a success response (with ‘status’: ‘success’ and operation-specific data) or an error response (with ‘status’: ‘error’, ‘code’, ‘message’, and optionally ‘errors’).

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

‘success’ or ‘error’.

  • Type: Status of the operation

classmethod validate_status(v: str) → str

Section titled “classmethod validate_status(v: str) → str”

class prefactor_http.BulkRequest(, items: Annotated[list[BulkItem], MinLen(min_length=1)])

Section titled “class prefactor_http.BulkRequest(, items: Annotated[list[BulkItem], MinLen(min_length=1)])”

Bases: BaseModel

Request body for bulk query/action operations.

Allows executing multiple API operations in a single request.

List of items to process in bulk. Each item will be processed independently in its own transaction.

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Validate that all idempotency keys are unique within the request.

class prefactor_http.BulkResponse(, status: str = ‘success’, outputs: dict[str, BulkOutput])

Section titled “class prefactor_http.BulkResponse(, status: str = ‘success’, outputs: dict[str, BulkOutput])”

Bases: BaseModel

Response from bulk query/action operations.

Contains a map of results keyed by the idempotency_key from each request item.

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Map where keys are the idempotency_key values from the request, and values are the corresponding query/action outputs or error responses.

Response status, always ‘success’ when the request is processed.

class prefactor_http.FinishInstanceRequest(, status: Literal[‘complete’, ‘failed’, ‘cancelled’] | None = None, timestamp: str | None = None, idempotency_key: str | None = None)

Section titled “class prefactor_http.FinishInstanceRequest(, status: Literal[‘complete’, ‘failed’, ‘cancelled’] | None = None, timestamp: str | None = None, idempotency_key: str | None = None)”

Bases: BaseModel

Request to finish an agent instance.

Optional finish status (complete, failed, cancelled)

  • Type: Literal[‘complete’, ‘failed’, ‘cancelled’] | None

Optional ISO 8601 timestamp (defaults to current time)

  • Type: str | None

Optional idempotency key

  • Type: str | None

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

status : Literal[‘complete’, ‘failed’, ‘cancelled’] | None

Section titled “status : Literal[‘complete’, ‘failed’, ‘cancelled’] | None”

class prefactor_http.HttpClientConfig(api_url: str, api_token: str, request_timeout: float = 30.0, connect_timeout: float = 10.0, max_retries: int = 3, initial_retry_delay: float = 1.0, max_retry_delay: float = 60.0, retry_multiplier: float = 2.0, retry_on_status_codes: tuple[int, …] = (429, 500, 502, 503, 504), default_idempotency_key: str | None = None)

Section titled “class prefactor_http.HttpClientConfig(api_url: str, api_token: str, request_timeout: float = 30.0, connect_timeout: float = 10.0, max_retries: int = 3, initial_retry_delay: float = 1.0, max_retry_delay: float = 60.0, retry_multiplier: float = 2.0, retry_on_status_codes: tuple[int, …] = (429, 500, 502, 503, 504), default_idempotency_key: str | None = None)”

Bases: object

Configuration for the HTTP client.

Base URL for the Prefactor API. Example: ‘https://api.prefactor.ai

  • Type: str

Bearer token for API authentication.

  • Type: str

Total timeout for requests in seconds (default: 30.0).

  • Type: float

Connection timeout in seconds (default: 10.0).

  • Type: float

Maximum number of retry attempts (default: 3).

  • Type: int

Initial delay between retries in seconds (default: 1.0).

  • Type: float

Maximum delay between retries in seconds (default: 60.0).

  • Type: float

Multiplier for exponential backoff (default: 2.0).

  • Type: float

HTTP status codes to retry on (default: 429, 500, 502, 503, 504).

  • Type: tuple[int, …]

Optional default idempotency key prefix.

  • Type: str | None

default_idempotency_key : str | None = None

Section titled “default_idempotency_key : str | None = None”

retry_on_status_codes : tuple[int, …] = (429, 500, 502, 503, 504)

Section titled “retry_on_status_codes : tuple[int, …] = (429, 500, 502, 503, 504)”

exception prefactor_http.PrefactorApiError(message: str, code: str, status_code: int)

Section titled “exception prefactor_http.PrefactorApiError(message: str, code: str, status_code: int)”

Bases: PrefactorHttpError

API returned an error response.

Human-readable error message

Error code from the API

HTTP status code

exception prefactor_http.PrefactorAuthError(message: str, code: str, status_code: int)

Section titled “exception prefactor_http.PrefactorAuthError(message: str, code: str, status_code: int)”

Bases: PrefactorApiError

Authentication/authorization errors (401, 403).

exception prefactor_http.PrefactorClientError

Section titled “exception prefactor_http.PrefactorClientError”

Bases: PrefactorHttpError

Client-side error (not related to API).

Bases: object

Main HTTP client for interacting with the Prefactor API.

This client provides high-level methods for all API endpoints with built-in retry logic, error handling, and idempotency support.

Usage: : async with PrefactorHttpClient(config) as client: : instance = await client.agent_instances.register(…) span = await client.agent_spans.create(…)

Access the agent instance endpoint client.

Provides methods to interact with agent instances:

  • register: Create a new agent instance
  • start: Mark an instance as started
  • finish: Mark an instance as finished

instance = await client.agent_instances.register(agent_id, agent_version)

Access the agent span endpoint client.

Provides methods to interact with agent spans:

  • create: Create a new agent span
  • finish: Mark a span as finished

span = await client.agent_spans.create( : agent_instance_id, schema_name, payload

)

Access the bulk endpoint client.

Provides methods to execute multiple queries/actions in a single request:

  • execute: Execute bulk operations

response = await client.bulk.execute(bulk_request)

Close the HTTP session.

async request(method: str, path: str, , params: dict[str, Any] | None = None, json_data: dict[str, Any] | None = None, idempotency_key: str | None = None) → dict[str, Any]

Section titled “async request(method: str, path: str, , params: dict[str, Any] | None = None, json_data: dict[str, Any] | None = None, idempotency_key: str | None = None) → dict[str, Any]”

Make an HTTP request with retry logic.

This is the public request method that wraps the core request with retry handling.

  • Parameters:
    • method – HTTP method (GET, POST, PUT, DELETE).
    • path – API path.
    • params – Query parameters.
    • json_data – JSON body data.
    • idempotency_key – Optional idempotency key.
  • Returns: Parsed JSON response.
  • Raises:

exception prefactor_http.PrefactorHttpError

Section titled “exception prefactor_http.PrefactorHttpError”

Bases: Exception

Base exception for all HTTP client errors.

exception prefactor_http.PrefactorNotFoundError(message: str, code: str, status_code: int)

Section titled “exception prefactor_http.PrefactorNotFoundError(message: str, code: str, status_code: int)”

Bases: PrefactorApiError

Resource not found (404).

exception prefactor_http.PrefactorResponseContractError(message: str, , status_code: int | None = None, body_snippet: str | None = None, cause: Exception | None = None)

Section titled “exception prefactor_http.PrefactorResponseContractError(message: str, , status_code: int | None = None, body_snippet: str | None = None, cause: Exception | None = None)”

Bases: PrefactorHttpError

Backend response violated the SDK’s expected response contract.

exception prefactor_http.PrefactorRetryExhaustedError(message: str, last_error: Exception | None = None)

Section titled “exception prefactor_http.PrefactorRetryExhaustedError(message: str, last_error: Exception | None = None)”

Bases: PrefactorHttpError

All retry attempts exhausted.

The last exception that caused the retry to fail

exception prefactor_http.PrefactorValidationError(message: str, code: str, status_code: int, errors: dict)

Section titled “exception prefactor_http.PrefactorValidationError(message: str, code: str, status_code: int, errors: dict)”

Bases: PrefactorApiError

Validation errors (400, 422).

Detailed validation errors mapping field names to error messages

class prefactor_http.SpanTypeSchemaForCreate(, name: str, params_schema: dict, result_schema: dict | None = None, title: str | None = None, description: str | None = None, template: str | None = None)

Section titled “class prefactor_http.SpanTypeSchemaForCreate(, name: str, params_schema: dict, result_schema: dict | None = None, title: str | None = None, description: str | None = None, template: str | None = None)”

Bases: BaseModel

Span type schema details for registration.

Name of the span type

  • Type: str

JSON schema for span parameters

  • Type: dict

Optional JSON schema for span results

  • Type: dict | None

Optional human-readable title

  • Type: str | None

Optional description

  • Type: str | None

Optional template string

  • Type: str | None

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].