Skip to main content

The official Python library for the atla API

Project description

Atla Python API library

PyPI version

The Atla Python library provides convenient access to the Atla REST API from any Python 3.7+ application. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by httpx.

Documentation

The REST API documentation can be found on docs.atla-ai.com. The full API of this library can be found in api.md.

Installation

# install from PyPI
pip install atla

Usage

The full API of this library can be found in api.md.

import os
from atla import Atla

client = Atla(
    # This is the default and can be omitted
    api_key=os.environ.get("ATLA_API_KEY"),
)

eval = client.evaluation.create(
    input="Is it legal to monitor employee emails under European privacy laws?",
    metrics=["precision", "recall"],
    response="Monitoring employee emails is permissible under European privacy laws like GDPR, provided there's a legitimate purpose.",
    context="European privacy laws, including GDPR, allow for the monitoring of employee emails under strict conditions. The employer must demonstrate that the monitoring is necessary for a legitimate purpose, such as protecting company assets or compliance with legal obligations. Employees must be informed about the monitoring in advance, and the privacy impact should be assessed to minimize intrusion.",
)
print(f"Precision score {eval.evaluations['precision'].score} / 5")

While you can provide an api_key keyword argument, we recommend using python-dotenv to add ATLA_API_KEY="My API Key" to your .env file so that your API Key is not stored in source control.

Async usage

Simply import AsyncAtla instead of Atla and use await with each API call:

import os
import asyncio
from atla import AsyncAtla

client = AsyncAtla(
    # This is the default and can be omitted
    api_key=os.environ.get("ATLA_API_KEY"),
)


async def main() -> None:
    eval = await client.evaluation.create(
        input="Is it legal to monitor employee emails under European privacy laws?",
        metrics=["precision", "recall"],
        response="Monitoring employee emails is permissible under European privacy laws like GDPR, provided there's a legitimate purpose.",
        context="European privacy laws, including GDPR, allow for the monitoring of employee emails under strict conditions. The employer must demonstrate that the monitoring is necessary for a legitimate purpose, such as protecting company assets or compliance with legal obligations. Employees must be informed about the monitoring in advance, and the privacy impact should be assessed to minimize intrusion.",
    )
    print(f"Precision score {eval.evaluations['precision'].score} / 5")


asyncio.run(main())

Functionality between the synchronous and asynchronous clients is otherwise identical.

Using types

Nested request parameters are TypedDicts. Responses are Pydantic models which also provide helper methods for things like:

  • Serializing back into JSON, model.to_json()
  • Converting to a dictionary, model.to_dict()

Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set python.analysis.typeCheckingMode to basic.

Handling errors

When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of atla.APIConnectionError is raised.

When the API returns a non-success status code (that is, 4xx or 5xx response), a subclass of atla.APIStatusError is raised, containing status_code and response properties.

All errors inherit from atla.APIError.

import atla
from atla import Atla

client = Atla()

try:
    client.evaluation.create(
        input="Is it legal to monitor employee emails under European privacy laws?",
        metrics=["precision", "recall"],
        response="Monitoring employee emails is permissible under European privacy laws like GDPR, provided there's a legitimate purpose.",
        context="European privacy laws, including GDPR, allow for the monitoring of employee emails under strict conditions. The employer must demonstrate that the monitoring is necessary for a legitimate purpose, such as protecting company assets or compliance with legal obligations. Employees must be informed about the monitoring in advance, and the privacy impact should be assessed to minimize intrusion.",
    )
except atla.APIConnectionError as e:
    print("The server could not be reached")
    print(e.__cause__)  # an underlying Exception, likely raised within httpx.
except atla.RateLimitError as e:
    print("A 429 status code was received; we should back off a bit.")
except atla.APIStatusError as e:
    print("Another non-200-range status code was received")
    print(e.status_code)
    print(e.response)

Error codes are as followed:

Status Code Error Type
400 BadRequestError
401 AuthenticationError
403 PermissionDeniedError
404 NotFoundError
422 UnprocessableEntityError
429 RateLimitError
>=500 InternalServerError
N/A APIConnectionError

Retries

Certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors are all retried by default.

You can use the max_retries option to configure or disable retry settings:

from atla import Atla

# Configure the default for all requests:
client = Atla(
    # default is 2
    max_retries=0,
)

# Or, configure per-request:
client.with_options(max_retries=5).evaluation.create(
    input="Is it legal to monitor employee emails under European privacy laws?",
    metrics=["precision", "recall"],
    response="Monitoring employee emails is permissible under European privacy laws like GDPR, provided there's a legitimate purpose.",
    context="European privacy laws, including GDPR, allow for the monitoring of employee emails under strict conditions. The employer must demonstrate that the monitoring is necessary for a legitimate purpose, such as protecting company assets or compliance with legal obligations. Employees must be informed about the monitoring in advance, and the privacy impact should be assessed to minimize intrusion.",
)

Timeouts

By default requests time out after 1 minute. You can configure this with a timeout option, which accepts a float or an httpx.Timeout object:

from atla import Atla

# Configure the default for all requests:
client = Atla(
    # 20 seconds (default is 1 minute)
    timeout=20.0,
)

# More granular control:
client = Atla(
    timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
)

# Override per-request:
client.with_options(timeout=5.0).evaluation.create(
    input="Is it legal to monitor employee emails under European privacy laws?",
    metrics=["precision", "recall"],
    response="Monitoring employee emails is permissible under European privacy laws like GDPR, provided there's a legitimate purpose.",
    context="European privacy laws, including GDPR, allow for the monitoring of employee emails under strict conditions. The employer must demonstrate that the monitoring is necessary for a legitimate purpose, such as protecting company assets or compliance with legal obligations. Employees must be informed about the monitoring in advance, and the privacy impact should be assessed to minimize intrusion.",
)

On timeout, an APITimeoutError is thrown.

Note that requests that time out are retried twice by default.

Versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes that only affect static types, without breaking runtime behavior.
  2. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals).
  3. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Requirements

Python 3.7 or higher.

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

atla-0.3.0.tar.gz (54.3 kB view hashes)

Uploaded Source

Built Distribution

atla-0.3.0-py3-none-any.whl (65.5 kB view hashes)

Uploaded Python 3

Supported by

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