asyncio. Synchronous methods release the Python global interpreter lock while requests run.
See the Performance Client overview for shared batching, retry, and connection settings.
Installation
OpenAIEmbeddingsResponse.numpy().
First request
Set your API key, an embeddings deployment URL, and themodel value expected by that deployment:
embeddings.py:
embeddings.py
python embeddings.py. A successful response prints 2 embeddings, followed by token usage and elapsed time. For reranking, classification, or generic requests, set the base URL to a deployment that supports the corresponding operation.
PerformanceClient
Base URL for requests. The client appends the request path. For an embeddings deployment, use the URL ending in
/sync, without /v1/embeddings.Inference API key. Defaults to
None, so the client checks BASETEN_API_KEY, then OPENAI_API_KEY. Construction fails if no key is available.Shared HTTP connection pool. When supplied, its HTTP version and proxy configuration take precedence. Defaults to
None.Set of endpoints the client can send requests to. When supplied, these URLs replace
base_url. Defaults to None.get_client_wrapper
client.get_client_wrapper() returns the HttpClientWrapper used by the client. Pass it to another client to share connections.
api_key
Inference methods
Each method has a synchronous and an asynchronous version with the same arguments and response type. Asynchronous methods return awaitables forasyncio; they don’t submit jobs to the asynchronous inference API.
embed
Generates embeddings for the input texts.
Requested embedding dimensions. The Python binding accepts 1 through 1,000,000; the model determines which values it supports. Defaults to
None.Batching, concurrency, timeout, and retry settings. Defaults to
None.OpenAIEmbeddingsResponse, with embedding results, token usage, and timing fields.
async_embed
await client.async_embed(...) accepts the same arguments as embed and returns OpenAIEmbeddingsResponse.
async_embeddings.py
python async_embeddings.py. In an application that already runs an event loop, await async_embed from your existing async function.
rerank
Scores texts against a query.
Batching, concurrency, timeout, and retry settings. Defaults to
None.model, raw_scores, return_text, truncate, and truncation_direction.
Returns RerankResponse, with an original input index and score for each result.
Configure client for a reranking deployment, then score the texts:
async_rerank
await client.async_rerank(...) accepts the same arguments as rerank and returns RerankResponse.
classify
Assigns labels and scores to the input texts.
Nonempty list of texts to classify. The client wraps each string in a one-element list in the request’s
inputs field.Batching, concurrency, timeout, and retry settings. Defaults to
None.model, raw_scores, truncate, and truncation_direction.
Returns ClassificationResponse, whose data contains a list of label-score results for each input.
Configure client for a classification deployment, then classify the texts:
async_classify
await client.async_classify(...) accepts the same arguments as classify and returns ClassificationResponse.
batch_system_one
Sends one System One decision request per input dictionary. Configure client with a base URL that serves /v1/systemone, without that path appended.
For supported models and complete request examples, see Decision models.
Nonempty list of System One request bodies. Each dictionary contains
state and questions. Include model when the endpoint requires a model slug. Additional fields pass through to the server.Concurrency, timeout, retry, and header settings. Defaults to
None. Each dictionary is a separate POST request; batch_size doesn’t combine them.BatchPostResponse. Its data list contains the server responses in input order, with timing and response headers on the enclosing object. An empty list raises ValueError.
batch_post
Sends one HTTP request per payload and returns responses in input order.
Concurrency, timeout, retry, and header settings. Defaults to
None.Defaults to
None, which uses "POST". Also accepts "GET", "PUT", "PATCH", "DELETE", "HEAD", and "OPTIONS". Use uppercase names.Defaults to
False. Set it to True to get each response body undecoded, as bytes. Requests still ask the server for JSON; the client skips the parse that runs while holding the GIL. Parse the bytes yourself with orjson.loads or json.loads.batch_size and max_chars_per_request don’t combine the payloads into a single request. For DELETE, HEAD, and OPTIONS, the response data contains empty dictionaries rather than decoded response bodies.
batch_post and async_batch_post don’t accept custom_headers, despite the argument appearing in the package’s type hints. Set headers with RequestProcessingPreference(extra_headers={"x-request-source": "batch-job"}).client for a deployment that serves /v1/completions, then send non-streaming completion requests:
async_batch_post
await client.async_batch_post(url_path, payloads, preference=None, method=None, raw_bytes=False) returns BatchPostResponse.
Request preferences
Pass aRequestProcessingPreference to an inference method to set batching, concurrency, timeouts, and retries for that call. Use keyword arguments when creating preferences.
RequestProcessingPreference() and RequestProcessingPreference.default() apply the defaults below. Fields are readable and writable. Passing None to an optional constructor argument uses its default.
Maximum concurrent requests. Must be 1 to 1,024, or 1 to 512 when
batch_size is below 16.Character threshold for splitting text batches. Accepts 50 to 1,048,576. The client sends any text that exceeds the threshold intact in its own batch.
Delay in seconds before sending a duplicate request. Defaults to
None, which disables hedging. When set, must be at least 0.045 seconds and less than timeout_s - 0.045.Timeout for the entire operation. Must be at least
timeout_s when supplied. Defaults to None.Fraction used to calculate the operation’s hedge budget. Defaults to
0.10, or 10%. Accepts 0 to 3.Fraction used to calculate the operation’s budget for timeout and network retries. Defaults to
0.05, or 5%. HTTP-status retries don’t consume this budget. Accepts 0 to 3.Cancellation state checked by
async_embed before starting. Doesn’t interrupt requests in flight. Defaults to None. See CancellationToken for method-specific behavior.API key sent with this call’s requests in place of the client’s
api_key. Defaults to None.Send the call’s request ID as
x-baseten-batch-key on every request, retry, and hedge, so a deployment running active-active across clusters serves the whole call from one cluster. You can’t combine it with x-baseten-batch-key in extra_headers.Response types
All response types include these timing and header fields. Times are in seconds.OpenAIEmbeddingsResponse
Embedding results. See
OpenAIEmbeddingData for each result’s fields.Token counts. See
OpenAIUsage.response.numpy() converts float embeddings to a two-dimensional NumPy float32 array. It raises ValueError for empty data, base64 embeddings, or inconsistent dimensions.
Install NumPy with pip install numpy, then convert the response from the first request:
OpenAIEmbeddingData
OpenAIUsage
RerankResponse
Reranking results. See
RerankResult for each result’s fields.RerankResult
ClassificationResponse
A list of label-score results for each input. See
ClassificationResult for each result’s fields.ClassificationResult
BatchPostResponse
Response payloads. Each element corresponds to one input payload: a parsed Python object, or
bytes when the call passed raw_bytes=True.Helper types
Import these types frombaseten_performance_client.
HttpClientWrapper
HttpClientWrapper(http_version=1, proxy=None) creates a reusable HTTP connection pool. Pass it through PerformanceClient(client_wrapper=...) or to an Endpoint.
Set BASETEN_SECOND_BASE_URL to another deployment URL, then share the wrapper between clients:
CancellationToken
CancellationToken() creates a token. Pass it as RequestProcessingPreference(cancel_token=token). token.cancel() sets its cancelled state, and token.is_cancelled() returns that state. A cancelled token can’t be reset.
async_embed checks the token before starting and raises ValueError if it’s already cancelled. The other Python inference methods don’t check the token. No method polls it while requests run, so calling cancel() doesn’t interrupt requests in flight. Use timeout_s and total_timeout_s to bound request duration.
TraceContext
Use TraceContext(traceparent, tracestate=None) to attach requests to a parent trace. Pass it as RequestProcessingPreference(trace_context=...).
The constructed object exposes these read-only properties:
Don’t also set traceparent or tracestate in extra_headers; the client rejects that combination.
To export client spans to an OpenTelemetry collector, configure client tracing.
Endpoint
Endpoint configures a base URL and the health checks used by an EndpointPool.
Ignore a timeout from the deployment check when deciding whether the endpoint is healthy. Defaults to
None, which uses True.Ignore a timeout from the deep health check when deciding whether the endpoint is healthy. Defaults to
None, which uses True.EndpointPool
EndpointPool(endpoints, endpoint_weights=None) groups endpoints for request routing.
Routing weights for the endpoints. Defaults to
None, which gives each endpoint equal weight. Custom weights must match the endpoint count, be finite and nonnegative, and include at least one positive value.PerformanceClient(endpoint_pool=pool, ...). An endpoint’s health-check key doesn’t replace the client’s inference API key.
Errors
HTTP errors don’t attach a
requests.Response object. Read the exception’s args instead of assuming error.response.status_code is available.
Handle errors from the embedding client:
Package source
Checkbaseten_performance_client.__version__ for the installed version. The PyPI source distribution includes the type hints and Rust implementation. See the Python binding source on GitHub for current development.