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

Uploaded Source

Built Distribution

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

Uploaded Python 3

File details

Details for the file atla-0.3.0.tar.gz.

File metadata

  • Download URL: atla-0.3.0.tar.gz
  • Upload date:
  • Size: 54.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.12.1

File hashes

Hashes for atla-0.3.0.tar.gz
Algorithm Hash digest
SHA256 737f33274d91876e9b47e5dcccf18fb4e49ec62783144ab85d728d9360a86e83
MD5 09afd7f47f22fcf81425ecf0fb148182
BLAKE2b-256 9667775f9cfff7e60b147dd1ef326452387eb4a596d692500dee121a2ee0c3f3

See more details on using hashes here.

File details

Details for the file atla-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: atla-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 65.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.12.1

File hashes

Hashes for atla-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4cfa8f85c5b5e131ed893ee61eb1b8a068053e048a257e43838c14baebce44e5
MD5 80c3c9b29b2927ad29243465887b62de
BLAKE2b-256 52e2a63299d0d730d19f1850d13c9a0cc6576922bce6ea63bacb8a8f99d7b5f6

See more details on using hashes here.

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