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
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
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:
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
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
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
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
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
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
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
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
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
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
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}
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=...
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}
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
info = client.data.test()
print(info["siteId"], info["siteName"])
Confirms that the key works and names its site.
leads
GET /v1/zapier/leads
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
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}
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
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
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
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:
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:
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.
Metadata
Release files for slatech 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| slatech-0.1.0.tar.gz | 32.9 kB | Without provenance | Details for slatech-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| slatech-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for slatech-0.1.0-py3-none-any.whl |
Total release size: 63.1 kB
Release files / slatech-0.1.0.tar.gz
| Download URL | slatech-0.1.0.tar.gz |
|---|---|
| Size | 32.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
547962024b48045b90b3b9567e1abc9bbb4224f1eaf133e1995c9f1f20b96d34
|
|
BLAKE2b-256 checksum How to use checksums |
4f1694ec920b0a45449848f0dc03839b2b3c846f0fbcf36efa495ffb23bcd53d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.12
|
Release files / slatech-0.1.0-py3-none-any.whl
| Download URL | slatech-0.1.0-py3-none-any.whl |
|---|---|
| Size | 30.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1056b438c5ebad25da93de171a74378df1de5007926a5b0966312688a6ed5db8
|
|
BLAKE2b-256 checksum How to use checksums |
66b4629ab5fbf0f035b1e064acd58275f2a638e6d0107b4c0c01b2bd3971e036
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.12
|
Security for slatech 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.