> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agents.kolena.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Quickstart Guide

> Call Agents from Python

Follow our quickstart guide below or use an [interactive notebook](https://colab.research.google.com/github/kolenaIO/agents-notebooks/blob/main/quickstart.ipynb).

## Installation

To connect to your Kolena Agents using Python, install the `kolena-agents` client from
[PyPI](https://pypi.org/project/kolena-agents/) using any Python package manager such as [pip](https://pypi.org/project/pip/)
or [poetry](https://python-poetry.org):

> [tab] pip
>
> ```shell theme={null}
> pip install kolena-agents
> ```

> [tab] poetry
>
> ```shell theme={null}
> poetry add kolena-agents
> ```

## Initialization

An [API Key](https://docs.agents.kolena.com/api-keys.md) is required to use the python client.
Create and copy a key, then store the value in a `KOLENA_API_KEY` environment variable:

```shell theme={null}
export KOLENA_API_KEY="your-api-key"
```

## Usage

Here's an example of how to use the client to add, download and delete Agent Runs:

```python theme={null}
from kolena_agents import Client

client = Client()

# add new Agent Run
new_run = client.agent_run.add(agent_id=1, files=["path/to/file1", "path/to/file2"])

# each entry may be a path, an open binary file object, bytes, or a (filename, bytes_or_file_object) tuple
with open("path/to/large_file", "rb") as f:
    streamed_run = client.agent_run.add(agent_id=1, files=[f])

# download Agent Run
run = client.agent_run.get(agent_id=1, run_id=2)

# alternatively, list all Agent Runs
all_runs = client.agent_run.list(agent_id=1)

# delete Agent Run
client.agent_run.delete(agent_id=1, run_id=2)

# list all Agents
all_agents = client.agent.list()

# get an Agent
agent = client.agent.get(agent_id=1)

# update Agent properties
updated_agent = client.agent.update(
    agent_id=1,
    metadata={
        "environment": "production",
        "version": 2,
        "tags": ["nlp", "extraction"]
    }
)
```

### Managing Agent Properties

You can attach key-value pairs metadata to your Agents for organizing, filtering, and tracking purposes. Metadata values can be primitives (strings, numbers, booleans, or null) or arrays (lists of primitive values). See the [API reference](https://docs.agents.kolena.com/api-reference/update-agent.md) for more details.

```python theme={null}
# update Agent properties
agent = client.agent.update(
    agent_id=1,
    metadata={
        "environment": "production",
        "version": 2,
        "department": "finance",
        "tags": ["invoice-processing", "high-priority"],
        "threshold": 0.85,
        "enabled": True
    }
)

# access metadata from retrieved agent
agent = client.agent.get(agent_id=1)
print(agent.metadata)

# clear metadata
client.agent.update(agent_id=1, metadata={})
```

### Synchronous Usage

You can also add an Agent Run synchronously, which creates a Run and waits for processing of all prompts to complete. Note that this endpoint has [rate limits](https://docs.agents.kolena.com/api-reference/add-agent-run-wait.md#rate-limits).

```python theme={null}
# add new Agent Run and wait for processing to complete
new_run = client.agent_run.add_wait(agent_id=1, files=["path/to/file1"])

# pass an idempotency key to safely retry: retrying with the same key returns the
# existing Run instead of creating a duplicate
idempotency_key = str(uuid.uuid4())
new_run = client.agent_run.add_wait(agent_id=1, files=["path/to/file1"], idempotency_key=idempotency_key)

# if the Run times out (still in "running" status), fall back to polling:
while new_run.status == "running":
    new_run = client.agent_run.get(agent_id=1, run_id=new_run.run_id)
    time.sleep(10)
```

### Download Templated Output

When an Agent has an [Output Template](https://docs.agents.kolena.com/templated-outputs.md) configured, Runs can be downloaded into the Template.

```py theme={null}
agent = client.agent.get(agent_id=...)
output_template_id = agent.output_templates[0].id

# download Agent Run output as PDF
client.agent_run.download_templated_output(
    agent_id=...,
    run_id=...,
    output_template_id=output_template_id,
    output_format="pdf",
    filename="output.pdf",
)

# download all Agent Runs into a Multiple-Run Excel Template
client.agent_run.download_runs_templated_output(
    agent_id=...,
    output_template_id=...,
    filename="all_runs.xlsx",
)

# download all Agent Runs as the default Excel table (no Template required)
client.agent_run.download_runs_templated_output(
    agent_id=...,
    filename="all_runs.xlsx",
)
```

### Query Access Logs

> [!NOTE]
>
> This is available on the Enterprise Plan. [Contact Kolena](mailto:support@kolena.com) if you’re not on an Enterprise plan but would like to try this feature.

```py theme={null}
time_range = {"start_time": "2025-09-09T00:00:00Z", "end_time": "2025-09-10T23:59:59Z"}

# initial query
response = client.access_logs.query(
    time_range=time_range,
    page_size=100
)
all_events = response.events

# fetch remaining pages
while response.next_cursor:
    response = client.access_logs.query(
        time_range=time_range,
        page_size=100,
        cursor=response.next_cursor
    )
    all_events.extend(response.events)
```

### View Credit History

Pull credit history to get insights on usage. See the [API reference](https://docs.agents.kolena.com/api-reference/list-usage-records.md) for more details.

```python theme={null}
# list usage records
usage = client.usage.list(page_size=50)

# filter by date range
import datetime
now = datetime.datetime.now(datetime.timezone.utc)
usage = client.usage.list(
    created_gte=now - datetime.timedelta(days=30),
    created_lte=now,
)

# filter by agent or user
usage = client.usage.list(agent_id=1)
usage = client.usage.list(user="user@example.com")
```

### Manage API Keys

Programmatically manage API keys for automated rotation and monitoring. See the [API reference](https://docs.agents.kolena.com/api-reference/create-api-key.md) reference for more details.

```python theme={null}
from datetime import datetime, timezone

new_key = client.api_key.create(name="New Key", expiration_days=10)
print(f"New key: {new_key.api_key}")  # save this immediately!

# monitor keys for expiration
utc_now = datetime.now(timezone.utc)
response = client.api_key.list(page_number=0, page_size=50)
for key in response.api_keys:
    if key.status == "active" and key.expires_at:
        days_until_expiry = (key.expires_at - utc_now).days
        if days_until_expiry < 30:
            print(f"Warning: {key.name} expires in {days_until_expiry} days")

key = client.api_key.get(key_id=new_key.id)
print(f"Key status: {key.status}")

# delete an API key
client.api_key.delete(key_id="old-key-id")
```

### Serializing to JSON

All `kolena-agents` objects are standard [`Pydantic`](https://docs.pydantic.dev/latest/) data objects and can be easily
converted to and from JSON:

```python theme={null}
from kolena_agents import Client
from kolena_agents.types.agent_run import AgentRun

client = Client()
run = client.agent_run.get(agent_id=1, run_id=2)

run_dict = run.model_dump(mode="json")  # get the AgentRun as a dictionary
run = AgentRun.model_validate(run_dict)  # deserialize an AgentRun
```

## Timeouts and Retries

By default the client waits up to 10 minutes for a response, and retries failed requests up to
3 times with exponential backoff. Connection errors, dropped connections and transient HTTP
statuses (`408`, `429`, `500`, `502`, `503`, `504`) are retried automatically for idempotent
requests. Connections that cannot be established normally fail after 5 seconds so they are retried
promptly rather than hanging.

The timeout applies to each network operation rather than to the request as a whole, so a large
upload that is still making progress will not time out. Streaming uploads use the operation timeout
while connecting and sending so the shorter connection timeout cannot interrupt the request body.

```python theme={null}
from kolena_agents import Client

# wait up to 30 seconds for a response
client = Client(timeout=30)

# wait indefinitely
client = Client(timeout=None)

# override the timeout for a single call
run = client.with_options(timeout=5).agent_run.get(agent_id=1, run_id=2)
```

[`add_wait`](#synchronous-usage) is the one exception: the server holds the connection open for
the poll window you request, so the client never gives up before that deadline even if you set a
shorter `timeout`.

> [!NOTE]
>
> Requests that create or modify data, such as `agent_run.add`, are retried only when it is certain
> the server did not act on them: failures before the request reaches the server, and responses
> (`408`, `429`) where the server rejected the request without processing it. They are not retried
> if the connection drops after the request was sent, or on `500`/`502`/`503`/`504`, since the
> server may have already applied the request.

## Webhook

Kolena provides a helper function to handle signature verification and parsing. See [Webhook Integration](https://docs.agents.kolena.com/connections.md#webhook) for more information.

```python theme={null}
from kolena_agents import webhook

result = webhook.construct_event(request_body, secret, request_headers)
```

## Supported Python Versions

Python versions 3.10 and later are supported.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.