Developer Guide

Client Libraries

Official clients of the SLAtech API for JavaScript/TypeScript and for Python: typed requests and results, streamed answers, errors you can branch on, and webhook signature verification.

What they are

Two libraries that call the same public API the API reference describes. Each one covers all 19 of its operations, with a method per operation, so you write client.ask(...) instead of building the HTTP request yourself. They do not add anything the API does not do: the same key, the same scopes, the same limits and the same errors apply.

LanguagePackageRuns on
JavaScript, TypeScript@slatech/bot-sdkNode.js 18 and later, and browsers (it uses the standard fetch, FormData and Blob). ES module and CommonJS builds, with type declarations.
PythonslatechPython 3.10 and later. One dependency, httpx. A synchronous client, SLAtech, and an asynchronous one, AsyncSLAtech, with the same methods.

Neither library retries a failed request on its own: what to do after an error is your decision, and the errors carry what you need to make it.

Install

npm
npm install @slatech/bot-sdk
pip
pip install slatech

You also need an API key: the getting started guide explains how to create one and which scopes it needs.

Quick start

TypeScript
import { SLAtechClient } from "@slatech/bot-sdk";

const client = new SLAtechClient({ apiKey: process.env.SLATECH_API_KEY! });

const result = await client.ask({ question: "Do you open on Saturdays?" });
console.log(result.answer);
for (const source of result.sources ?? []) console.log(source.title, source.sourceUrl);
Python
from slatech import SLAtech

with SLAtech() as client:  # the key comes from SLATECH_API_KEY, or pass api_key="..."
    result = client.ask("Do you open on Saturdays?")
    print(result["answer"])
    for source in result.get("sources") or []:
        print("-", source.get("title") or source.get("sourceUrl"))

In JavaScript the results are typed objects with the API's own field names. In Python they are plain dictionaries with the same field names (camelCase), typed for editors and type checkers.

Keep write and data keys on your server. The JavaScript library runs in a browser, but only the ask methods belong there. A key with ingest can change what your assistant answers, and a key with data:read reads leads with their contact details.

Client options

  • JavaScript: new SLAtechClient({ apiKey, baseUrl, timeoutMs, fetch, headers }). Only apiKey is required, and it is sent in the X-Api-Key header. There is no timeout unless you set timeoutMs. Every method also takes an optional last argument { signal, timeoutMs } to cancel one call or give it its own timeout; for a streamed answer the timeout covers the wait for the stream to start, not the whole stream.
  • Python: SLAtech(api_key, base_url=..., timeout=..., transport=..., http_client=..., default_headers=...). Without api_key the key is read from the SLATECH_API_KEY environment variable. The default timeout is 60 seconds. Use the client in a with block, or call client.close() when you are done; AsyncSLAtech works with async with and aclose(). A client you pass in as http_client is not closed by the library.

Both send requests to https://api.slatech.ai unless you set another base URL.

Streaming an answer

The streaming method returns the answer while it is being written, as a sequence of events. The first event carries the id you need to rate the answer later.

TypeScript
let queryLogId: string | undefined;
for await (const event of client.askStream({ question: "What does a cleaning cost?" })) {
  switch (event.type) {
    case "meta":
      queryLogId = event.queryLogId; // the id for client.feedback()
      break;
    case "text":
      process.stdout.write(event.text);
      break;
    case "done":
      console.log("\nSources:", event.sources.map((s) => s.sourceUrl));
      break;
    case "error":
      console.error("\nThe answer failed:", event.reason);
      break;
  }
}

if (queryLogId) await client.feedback(queryLogId, { isHelpful: true });
Python
query_log_id = None
for event in client.ask_stream("What does a cleaning cost?"):
    if event.type == "meta":
        query_log_id = event.query_log_id  # the id for client.feedback()
    elif event.type == "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)

if query_log_id:
    client.feedback(query_log_id, is_helpful=True)
Python (async)
import asyncio
from slatech import AsyncSLAtech

async def main() -> None:
    async with AsyncSLAtech() as client:
        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())
Event typeJavaScript fieldsPython fieldsWhen
metaqueryLogIdquery_log_idAlways first. The id for the feedback method.
sources-earlysourcessourcesOptional, before the first text.
texttexttextFragments of the answer, in order. Join them.
donehasSufficientContext, escalateLead, sources, department, departmentIdhas_sufficient_context, escalate_lead, sources, department, department_idLast event.
errorreasonreasonThe answer failed after the stream had opened (provider_unavailable or stream_error). Last event.

A request the API refuses before the stream opens (a bad key, a rate limit) raises an error instead of producing events. In Python the request is sent when the loop starts, so the error comes from the loop; leaving the loop early closes the connection. Python events also keep the original JSON in raw.

Every method

Each row is one API operation. The guide linked in each section explains the request and the response in full.

Ask

Any active key of the site, the widget key included. Guide: Ask questions.

JavaScriptPythonOperationWhat it does
client.ask(request)client.ask(question, ...)POST /v1/queryThe whole answer at once, with the sources it was grounded in. Counts toward the site's monthly question quota.
client.askStream(request)client.ask_stream(question, ...)POST /v1/query/streamThe answer as it is written, as the events above. Counts toward the same quota.
client.feedback(queryLogId, rating)client.feedback(query_log_id, is_helpful=..., source_clicked=...)PATCH /v1/query/{id}/feedbackRecords whether an answer helped and/or that a source was opened. The id comes from the meta event; the whole-answer method returns no id. A later rating overwrites an earlier one.
client.askWithImage(request)client.ask_with_image(question, image)POST /v1/query/ask-multimodalA question about a JPEG, PNG, WebP or GIF image of at most 10 MB. The answer is about the image itself, not the knowledge base, and has no sources. Counts toward the question quota.
client.getMultimodalContract()client.get_multimodal_contract()GET /v1/query/ask-multimodalDescribes the form the image method sends, so you can check the endpoint is available. The endpoint needs no key.

Knowledge base

A key with the ingest scope. Adding content runs in the background: each add returns a jobId to check with the job method, and counts toward the site's monthly ingestion quota. Guide: Manage the knowledge base.

JavaScriptPythonOperationWhat it does
client.knowledge.uploadFile(request)client.knowledge.upload_file(file, filename=...)POST /v1/ingest/fileAdds a PDF, DOCX, TXT or MD file of at most 10 MB. The type is told by the file name's extension, so raw bytes need a file name.
client.knowledge.addUrl(request)client.knowledge.add_url(url)POST /v1/ingest/urlQueues one web page.
client.knowledge.addSitemap(request)client.knowledge.add_sitemap(sitemap_url)POST /v1/ingest/sitemapQueues every page listed in a sitemap.
client.knowledge.addText(request)client.knowledge.add_text(text, source_url=...)POST /v1/ingest/textAdds raw text of at most 500,000 characters. Text sent again with the same source URL updates that one document.
client.knowledge.getJob(jobId)client.knowledge.get_job(job_id)GET /v1/ingest/jobs/{jobId}The state of a job: 0 pending, 1 processing, 2 completed, 3 failed, 4 cancelled (IngestJobStatus in JavaScript, JobStatus in Python).
client.knowledge.deleteBySourceUrl(sourceUrl)client.knowledge.delete_by_source_url(source_url)DELETE /v1/ingest/documentDeletes the document that text with this source URL was written to. Nothing to delete is not an error, so a sync can retry safely.
client.knowledge.deleteDocument(documentId)client.knowledge.delete_document(document_id)DELETE /v1/documents/{documentId}Deletes a document of the key's site and everything indexed from it.

Data

A key with the data:read scope. These operations belong to a plan feature; when the plan does not include it, the API answers 403 with feature_disabled. Lists hold at most 50 items, newest first. since is a date or an ISO 8601 string; without it the API uses one hour ago. Guide: Read leads, conversations and analytics.

JavaScriptPythonOperationWhat it does
client.data.test()client.data.test()GET /v1/zapier/testConfirms that the key works and names its site.
client.data.leads({ since })client.data.leads(since=...)GET /v1/zapier/leadsLeads captured at or after since.
client.data.conversations({ since })client.data.conversations(since=...)GET /v1/zapier/conversationsAnswered questions asked at or after since.
client.data.conversation(sessionId)client.data.conversation(session_id)GET /v1/zapier/conversations/{sessionId}Every question and answer of one chat session, oldest first.

Analytics

A key with the data:read scope. Aggregates only: no question text and no visitor details. days is the length of the window, today included, from 1 to 90 (default 30). Guide: Read leads, conversations and analytics.

JavaScriptPythonOperationWhat it does
client.analytics.queriesSummary({ days })client.analytics.queries_summary(days=...)GET /v1/embed/analytics/queries-summaryTotals for the window.
client.analytics.queriesByDay({ days })client.analytics.queries_by_day(days=...)GET /v1/embed/analytics/queries-by-dayQuestions asked and resolved on each day.
client.analytics.qualityTrend({ days })client.analytics.quality_trend(days=...)GET /v1/embed/analytics/quality-trendAverage confidence and factuality scores on each day.

Webhooks

Functions, not API calls: they check the requests SLAtech sends to your server. In JavaScript they come from a separate entry point, @slatech/bot-sdk/webhooks, which uses node:crypto and is meant for server code; in Python, from slatech. Guide: Webhooks.

JavaScriptPythonWhat it does
verifyWebhookSignature(rawBody, signatureHeader, secret)verify_webhook_signature(raw_body, signature_header, secret)Checks the X-SLAtech-Signature header against the raw body in constant time. Returns false for a missing, malformed or wrong signature.
computeWebhookSignature(rawBody, secret)compute_webhook_signature(raw_body, secret)Returns the header value expected for a body.

Errors

A response with an error status becomes an exception. In JavaScript it is one class, SLAtechApiError; in Python, a class per status under APIStatusError, and every error of the library is a SLAtechError.

JavaScriptPythonMeaning
statusstatus_codeThe HTTP status code.
errorerrorThe API's error message, when the response had one.
retryAfterretry_afterSeconds to wait, from the Retry-After header. Set on rate-limit refusals (429).
currentUsage, maxAllowedcurrent_usage, max_allowedSet when the site's monthly quota is used up (429). Waiting does not help then.
isRateLimited, isQuotaExceededRateLimitError.is_quota_exceededWhich kind of 429 it was.
detailsdetailsThe invalid fields, when request validation failed (400).
featurefeature, PermissionDeniedError.is_feature_disabledThe plan feature that is not enabled (403 feature_disabled).
reasonreasonA machine-readable reason, for example provider_unavailable (503).
body, method, pathbody, responseThe raw response body, and the request (JavaScript) or the whole response (Python).

Python error classes by status: BadRequestError (400), AuthenticationError (401), PermissionDeniedError (403), NotFoundError (404), PayloadTooLargeError (413), UnsupportedMediaTypeError (415), RateLimitError (429), ServiceUnavailableError (503) and InternalServerError (other 5xx). When no response arrives within the timeout, JavaScript throws SLAtechTimeoutError (with timeoutMs) and Python raises APITimeoutError; Python raises APIConnectionError for other network failures.

TypeScript
import { SLAtechApiError, SLAtechTimeoutError } from "@slatech/bot-sdk";

try {
  await client.ask({ question: "Hello" });
} catch (err) {
  if (err instanceof SLAtechApiError && err.isRateLimited) {
    await new Promise((r) => setTimeout(r, (err.retryAfter ?? 1) * 1000));
    // retry
  } else if (err instanceof SLAtechApiError && err.isQuotaExceeded) {
    // retrying will not help until the allowance resets or the plan changes
    console.error(err.currentUsage, "of", err.maxAllowed);
  } else if (err instanceof SLAtechTimeoutError) {
    // no response within timeoutMs
  } else {
    throw err;
  }
}
Python
import time
from slatech import APITimeoutError, RateLimitError

try:
    result = client.ask("Hello")
except RateLimitError as e:
    if e.is_quota_exceeded:
        # retrying will not help until the allowance resets or the plan changes
        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("Hello")
except APITimeoutError:
    pass  # no response within the timeout

What each status means is in the getting started guide.

Verifying webhooks

Pass the body exactly as it arrived, before any JSON parsing, with the X-SLAtech-Signature header and your signing secret as the dashboard shows it. Reject the request when the check fails.

TypeScript
import express from "express";
import { verifyWebhookSignature } from "@slatech/bot-sdk/webhooks";

const app = express();
const SECRET = process.env.SLATECH_WEBHOOK_SECRET!; // the text exactly as shown in the dashboard

app.post("/slatech-webhook", express.raw({ type: "application/json" }), (req, res) => {
  if (!verifyWebhookSignature(req.body, req.get("X-SLAtech-Signature"), SECRET)) {
    return res.sendStatus(401);
  }
  const event = JSON.parse(req.body.toString("utf8"));
  switch (req.get("X-SLAtech-Event")) {
    case "new_lead": /* event.lead.email ... */ break;
    default: break; // ignore events you do not handle
  }
  res.sendStatus(204);
});
Python
import os

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

app = Flask(__name__)
SECRET = os.environ["SLATECH_WEBHOOK_SECRET"]  # the text exactly as shown in the dashboard

@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

The webhooks guide lists the events, their payloads and how delivery is retried.

License

Both libraries are open source under the Apache License 2.0; the license text ships in each package. Packages: @slatech/bot-sdk on npm and slatech on PyPI.

Related