Metadata-Version: 2.4
Name: slatech
Version: 0.1.0
Summary: Python client for the SLAtech API: ask questions against a site's knowledge base, keep it up to date, read conversations, leads and analytics, and verify webhooks.
Author-email: SLAtech LTD <info@slatech.ai>
License-Expression: Apache-2.0
Project-URL: Homepage, https://www.slatech.ai/en/docs/api-overview/
Project-URL: Documentation, https://www.slatech.ai/en/api-docs/
Keywords: slatech,chatbot,knowledge-base,api-client,sse,webhooks
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx<1,>=0.27
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Dynamic: license-file

# slatech

Python client for the SLAtech API. Ask questions against a site's knowledge base, whole or
streamed, keep that knowledge base up to date, read the site's conversations, leads and usage
numbers, and verify the webhooks SLAtech sends you.

- Sync and async clients with the same methods
- Streamed answers as typed events
- Typed results and a clear exception hierarchy
- One dependency: `httpx`

Full API reference: <https://www.slatech.ai/en/api-docs/>. Guides: <https://www.slatech.ai/en/docs/api-overview/>.

## Install

```bash
pip install slatech
```

Requires Python 3.10 or newer.

## API keys

Keys are issued per site in the dashboard: app.slatech.ai, then **API Keys**. A key carries one or
more scopes, and each method needs one:

| Scope | Methods |
|-------|---------|
| any active key of the site (the widget key included) | `ask`, `ask_stream`, `ask_with_image`, `feedback` |
| none | `get_multimodal_contract` |
| `ingest` | `client.knowledge.*` |
| `data:read` | `client.data.*`, `client.analytics.*` |

Pass the key as `api_key=...`, or set the `SLATECH_API_KEY` environment variable. Keys with
`ingest` or `data:read` belong on a server, never in a web page.

## Quick start

```python
from slatech import SLAtech

with SLAtech(api_key="YOUR_API_KEY") as client:
    result = client.ask("What are your opening hours?")
    print(result["answer"])
    for source in result["sources"] or []:
        print("-", source["title"] or source["sourceUrl"])
```

Async:

```python
import asyncio
from slatech import AsyncSLAtech

async def main() -> None:
    async with AsyncSLAtech(api_key="YOUR_API_KEY") as client:
        result = await client.ask("What are your opening hours?")
        print(result["answer"])

        async for event in client.ask_stream("Do you work on Fridays?"):
            if event.type == "text":
                print(event.text, end="", flush=True)

asyncio.run(main())
```

Results are plain dictionaries with the API's own field names (`camelCase`), typed with
`TypedDict` classes for editors and type checkers. Timestamps are ISO 8601 strings in UTC; some
arrive without a `Z` suffix, so read them as UTC.

## Client options

```python
client = SLAtech(
    api_key="YOUR_API_KEY",            # default: SLATECH_API_KEY
    base_url="https://api.slatech.ai",  # the default
    timeout=60.0,                       # seconds, or an httpx.Timeout
    default_headers={"X-Request-Source": "nightly-sync"},
)
```

For tests or custom networking, pass `transport=` (an `httpx` transport such as
`httpx.MockTransport`) or your own `http_client=` (`httpx.Client` / `httpx.AsyncClient`). A client
you pass in is not closed by the SDK.

## Asking questions

### `ask` - the whole answer at once

`POST /v1/query`

```python
result = client.ask(
    "And on Friday?",
    conversation_history=[
        {"role": "user", "content": "What are your opening hours?"},
        {"role": "assistant", "content": "Sunday to Thursday, 9:00 to 18:00."},
    ],
    session_id="chat-42",       # groups questions into one conversation
    visitor_id="visitor-7",
    page_url="https://example.com/contact",
)
print(result["answer"], result["hasSufficientContext"], result["escalateLead"])
```

The answer is grounded in the site's knowledge base and `sources` lists the passages it used.
`hasSufficientContext` is false when the knowledge base held nothing relevant; `escalateLead` is
true when the question showed buying intent the answer did not resolve, a cue to offer a contact
form. Optional arguments: `conversation_history` (roles `user` and `assistant`), `session_id`,
`visitor_id`, `page_url`, `top_k` (1-20) and `score_threshold` (0-1) - these two take effect only
when the site allows clients to override its search settings - `additional_site_ids` (other sites
of the same account), `attachment_ids`, `utm_source`, `utm_medium`, `utm_campaign`. Arguments you
leave out are not sent. The question is at most 2000 characters. Every call counts toward the
site's monthly question quota.

### `ask_stream` - the answer as it is written

`POST /v1/query/stream`

```python
answer = []
query_log_id = None
for event in client.ask_stream("What are your opening hours?"):
    if event.type == "meta":
        query_log_id = event.query_log_id      # for client.feedback(...)
    elif event.type == "sources-early":
        print("sources:", [s["sourceUrl"] for s in event.sources])
    elif event.type == "text":
        answer.append(event.text)
        print(event.text, end="", flush=True)
    elif event.type == "done":
        print("\nresolved from the knowledge base:", event.has_sufficient_context)
    elif event.type == "error":
        print("\nthe answer failed:", event.reason)  # provider_unavailable or stream_error
```

Same arguments, checks and quota as `ask`. Events arrive in this order:

| Event | Fields |
|-------|--------|
| `MetaEvent` (`"meta"`) | `query_log_id` - always first |
| `SourcesEarlyEvent` (`"sources-early"`) | `sources` - optional, before the first text |
| `TextEvent` (`"text"`) | `text` - answer fragments, in order; concatenate them |
| `DoneEvent` (`"done"`) | `has_sufficient_context`, `escalate_lead`, `sources`, `department`, `department_id` |
| `ErrorEvent` (`"error"`) | `reason` - the answer failed after the stream opened |

Each event also keeps the original JSON in `raw`. The request is sent when iteration starts, so
errors before the stream opens (401, 429 and so on) are raised from the loop. Leaving the loop
early closes the connection. With `AsyncSLAtech`, use `async for` without `await`.

### `ask_with_image` - a question about an image

`POST /v1/query/ask-multimodal`

```python
result = client.ask_with_image("What is on this label?", "photo.jpg")
print(result["answer"])
```

`image` is a path, raw bytes or a binary file object: JPEG, PNG, WebP or GIF, at most 10 MB. The
type comes from `content_type=` if you pass it, else from the file name, else from the image's
first bytes. The answer is about the image itself: it is not grounded in the knowledge base and
carries no sources. Counts toward the monthly question quota.

### `get_multimodal_contract` - check the image endpoint

`GET /v1/query/ask-multimodal`

```python
contract = client.get_multimodal_contract()
print(contract["supported"], [f["name"] for f in contract["fields"] or []])
```

Returns the form `ask_with_image` sends. Needs no key scope.

### `feedback` - rate an answer

`PATCH /v1/query/{id}/feedback`

```python
client.feedback(query_log_id, is_helpful=True)
client.feedback(query_log_id, source_clicked=True)
```

The id is `query_log_id` from the `meta` event of `ask_stream`; `ask` returns no id. A later rating
overwrites an earlier one. Only answers given on the key's own site can be rated.

## Knowledge base - `client.knowledge`

All of these need a key with the `ingest` scope. Adding content runs in the background: the call
returns a `jobId` to poll with `get_job`. Each add counts toward the site's monthly ingestion quota.

### `upload_file`

`POST /v1/ingest/file`

```python
job = client.knowledge.upload_file("price-list.pdf")
job = client.knowledge.upload_file(pdf_bytes, filename="price-list.pdf")
```

PDF, DOCX, TXT or MD, at most 10 MB. The API tells the type by the file name's extension, so
`filename=` is required with raw bytes. The result's `status` is the word `"Pending"`.

### `add_url`

`POST /v1/ingest/url`

```python
job = client.knowledge.add_url("https://example.com/prices")
```

One web page: an absolute http(s) URL on a public host, at most 2048 characters.

### `add_sitemap`

`POST /v1/ingest/sitemap`

```python
job = client.knowledge.add_sitemap("https://example.com/sitemap.xml")
```

Crawls every page listed in the sitemap XML: an absolute http(s) URL on a public host, at most
2048 characters.

### `add_text`

`POST /v1/ingest/text`

```python
job = client.knowledge.add_text(
    "We are open Sunday to Thursday, 9:00 to 18:00.",
    source_url="https://example.com/kb/opening-hours",
)
```

At most 500,000 characters. `source_url` names the document the text is written to: sending text
again with the same `source_url` updates that document, and `delete_by_source_url` removes it. It
is shown to visitors as the source link, so it must be an absolute http(s) URL of at most 2000
characters. Text sent without it all goes to one shared document of the site.

### `get_job`

`GET /v1/ingest/jobs/{jobId}`

```python
import time
from slatech import JobStatus

status = client.knowledge.get_job(job["jobId"])
while status["status"] in (JobStatus.PENDING, JobStatus.PROCESSING):
    time.sleep(5)
    status = client.knowledge.get_job(job["jobId"])
if status["status"] == JobStatus.FAILED:
    print(status["errorCode"], status["errorMessage"])
```

`status` is a number: 0 Pending, 1 Processing, 2 Completed, 3 Failed, 4 Cancelled.

### `delete_by_source_url`

`DELETE /v1/ingest/document?sourceUrl=...`

```python
result = client.knowledge.delete_by_source_url("https://example.com/kb/opening-hours")
print(result["deleted"])  # 0 when there was nothing to delete
```

Deletes the document text sent with this `source_url` was written to, and withdraws queued text
jobs for it. Deleting what is not there is not an error, so a sync can safely retry.

### `delete_document`

`DELETE /v1/documents/{documentId}`

```python
client.knowledge.delete_document("0b8f2a51-77c4-4f0e-a2f1-0c0ffee00001")
```

Deletes a document of the key's site and everything indexed from it.

## Conversations and leads - `client.data`

These need a key with the `data:read` scope, and the plan feature they belong to: without it they
raise `PermissionDeniedError` with `error == "feature_disabled"`. The key reads leads with their
contact details, so keep it on a server.

### `test`

`GET /v1/zapier/test`

```python
info = client.data.test()
print(info["siteId"], info["siteName"])
```

Confirms that the key works and names its site.

### `leads`

`GET /v1/zapier/leads`

```python
from datetime import datetime, timedelta, timezone

since = datetime.now(timezone.utc) - timedelta(minutes=15)
for lead in client.data.leads(since=since):
    print(lead["timestamp"], lead["email"], lead["status"])
```

Leads captured at or after `since`, newest first, at most 50. `since` is a `datetime` (a naive
one is taken as UTC) or an ISO 8601 string; without it the API uses one hour ago. For polling,
pass the time of the previous poll.

### `conversations`

`GET /v1/zapier/conversations`

```python
for turn in client.data.conversations(since=since):
    print(turn["sessionId"], turn["question"], ":", turn["answer"])
```

Answered questions asked at or after `since`, newest first, at most 50.

### `conversation`

`GET /v1/zapier/conversations/{sessionId}`

```python
for message in client.data.conversation(turn["sessionId"]):
    print(message["question"], message["answer"])
```

Every question and answer of one chat session, oldest first. A session the site does not have
gives an empty list.

## Analytics - `client.analytics`

These need a key with the `data:read` scope. `days` is the window length, today included: 1-90
(values outside are clamped by the API), default 30. Aggregates only: no question text, no visitor
details.

### `queries_summary`

`GET /v1/embed/analytics/queries-summary`

```python
s = client.analytics.queries_summary(days=30)
print(s["totalQueries"], s["resolved"], s["resolutionRate"], s["avgConfidence"])
```

Totals for the window, and `topIntents`: the five most frequent `utm_source` values of the pages
questions were asked on.

### `queries_by_day`

`GET /v1/embed/analytics/queries-by-day`

```python
for day in client.analytics.queries_by_day(days=14)["series"] or []:
    print(day["date"], day["count"], day["resolved"])
```

### `quality_trend`

`GET /v1/embed/analytics/quality-trend`

```python
for day in client.analytics.quality_trend(days=14)["series"] or []:
    print(day["date"], day["avgConfidence"], day["avgFactuality"], day["samples"])
```

Days without scored answers are present with `null` scores and `samples: 0`.

## Errors

Every error is a `SLAtechError`. A response with an error status raises a subclass of
`APIStatusError`:

| Exception | Status | When |
|-----------|--------|------|
| `BadRequestError` | 400 | Invalid request; `details` lists invalid fields when the API sent them |
| `AuthenticationError` | 401 | The key is missing, invalid, expired or revoked |
| `PermissionDeniedError` | 403 | The key lacks the scope, or the plan lacks the feature (`is_feature_disabled`) |
| `NotFoundError` | 404 | No such object on the key's site |
| `PayloadTooLargeError` | 413 | The upload is over the size limit |
| `UnsupportedMediaTypeError` | 415 | The body is not in the expected content type |
| `RateLimitError` | 429 | Over a rate limit, or the monthly quota is used up |
| `ServiceUnavailableError` | 503 | The assistant is temporarily unavailable |
| `InternalServerError` | other 5xx | Server-side failure |

Each error carries `status_code`, `error` (the API's message), `body` (the parsed response) and
`response`. Network failures raise `APIConnectionError`, and timeouts `APITimeoutError`, with
`status_code` set to `None`.

A 429 means one of two things, and `RateLimitError` tells you which:

```python
import time
from slatech import RateLimitError

try:
    result = client.ask("What are your opening hours?")
except RateLimitError as e:
    if e.is_quota_exceeded:
        # The plan's monthly quota is used up: waiting does not help.
        print("quota used:", e.current_usage, "of", e.max_allowed)
    else:
        time.sleep(e.retry_after or 1)  # seconds, from the Retry-After header
        result = client.ask("What are your opening hours?")
```

The SDK does not retry on its own.

## Verifying webhooks

SLAtech signs each webhook it sends. The `X-SLAtech-Signature` header is `sha256=` followed by the
lowercase hex HMAC-SHA256 of the raw request body, keyed with your signing secret. Check it against
the body bytes exactly as received, before any JSON parsing:

```python
from flask import Flask, abort, request
from slatech import verify_webhook_signature

app = Flask(__name__)
SECRET = "your signing secret, as the dashboard shows it"

@app.post("/slatech-webhook")
def slatech_webhook():
    if not verify_webhook_signature(request.get_data(), request.headers.get("X-SLAtech-Signature"), SECRET):
        abort(401)
    event = request.get_json()
    if request.headers.get("X-SLAtech-Event") == "new_lead":
        print(event["lead"]["email"])
    return "", 204
```

`verify_webhook_signature(raw_body, signature_header, secret)` compares in constant time and
returns `False` for a missing, malformed or wrong signature. Use the secret text as shown, as UTF-8;
do not base64-decode it. The event name is in the `X-SLAtech-Event` header and in the body's
`event` field. The same event can arrive more than once, so make your handling safe to repeat.

## License

Apache-2.0. See `LICENSE`.
