Ask Questions
Send a question, get an answer grounded in the site's content together with its sources: all at once, or streamed while it is being written.
All endpoints on this page accept any active key of the site, the widget key included. Each answered question counts as one answer against the site's monthly allowance.
Ask and get the whole answer
/v1/query| Field | Description |
|---|---|
question | Required. Up to 2,000 characters. |
sessionId | Identifies the conversation, up to 100 characters. Use a UUID, one per conversation: every turn is stored with it, the data endpoints return a conversation by it, and the background analysis behind conversation summaries, tags and the sentiment webhooks only looks at conversations whose id is a UUID. Ids that start with voice_, sms_, tg_ or wa_ belong to other channels and are ignored. |
conversationHistory | Earlier turns as {"role", "content"}, where role is user or assistant and content is up to 4,000 characters. The last six messages are used. |
visitorId | Your id for the person asking, up to 100 characters. Stored with the turn. |
pageUrl | The page the question was asked on. Stored with the turn. |
utmSource, utmMedium, utmCampaign | Campaign tags, up to 50 characters each. Stored with the turn for analytics. |
topK, scoreThreshold | Retrieval settings: 1 to 20 (default 5) and 0 to 1 (default 0.35). The site's own settings take precedence; yours apply only when the site allows overrides or has no value of its own. |
additionalSiteIds | Other sites of the same account to search as well. A site of another account is refused with 403; a site whose allowance is used up is left out. |
The API keeps no conversation memory for you. To ask a follow-up such as
"and on Saturdays?", send the earlier turns in conversationHistory. The
sessionId groups the turns for your records and analytics; it does not bring
earlier turns back into the answer.
cURL
curl -X POST https://api.slatech.ai/v1/query \
-H "X-Api-Key: $SLATECH_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"question": "And on Saturdays?",
"sessionId": "7d0f6a52-3c1e-4b8e-9f0a-2a6c5e1b9d47",
"conversationHistory": [
{ "role": "user", "content": "What are your opening hours?" },
{ "role": "assistant", "content": "We are open Sunday to Thursday, 9:00 to 18:00." }
]
}'
JavaScript
const sessionId = crypto.randomUUID(); // one per conversation
const history = [];
async function ask(question) {
const res = await fetch("https://api.slatech.ai/v1/query", {
method: "POST",
headers: {
"X-Api-Key": process.env.SLATECH_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({ question, sessionId, conversationHistory: history }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const data = await res.json();
history.push({ role: "user", content: question });
history.push({ role: "assistant", content: data.answer });
return data;
}
Python
import os
import uuid
import requests
session_id = str(uuid.uuid4()) # one per conversation
history = []
def ask(question):
resp = requests.post(
"https://api.slatech.ai/v1/query",
headers={"X-Api-Key": os.environ["SLATECH_API_KEY"]},
json={
"question": question,
"sessionId": session_id,
"conversationHistory": history,
},
timeout=60,
)
resp.raise_for_status()
data = resp.json()
history.append({"role": "user", "content": question})
history.append({"role": "assistant", "content": data["answer"]})
return data
C#
using System.Net.Http.Json;
using System.Text.Json;
var sessionId = Guid.NewGuid().ToString(); // one per conversation
var history = new List<object>();
async Task<JsonElement> AskAsync(HttpClient http, string question)
{
var resp = await http.PostAsJsonAsync("v1/query", new
{
question,
sessionId,
conversationHistory = history,
});
resp.EnsureSuccessStatusCode();
var data = await resp.Content.ReadFromJsonAsync<JsonElement>();
history.Add(new { role = "user", content = question });
history.Add(new { role = "assistant", content = data.GetProperty("answer").GetString() });
return data;
}
The response
JSON
{
"answer": "On Saturdays we are open from 10:00 to 14:00.",
"sources": [
{
"chunkId": "0b8f3f9e-6f7a-4f63-9a43-5d2f8c1e7a10",
"sourceUrl": "https://example.com/contact/",
"score": 0.82,
"chunkIndex": 3,
"snippet": "Opening hours: Sunday to Thursday 9:00 to 18:00, Saturday 10:00 to 14:00.",
"title": "Contact us"
}
],
"hasSufficientContext": true,
"escalateLead": false,
"latencyMs": 1840,
"department": null,
"departmentId": null
}
answer: the text of the answer.sources: the passages the answer was grounded in, with the page address, its title, a short snippet and the match score.titleandsnippetcan be empty.hasSufficientContext:falsewhen the knowledge base did not hold enough to answer.escalateLead:truewhen the question shows buying intent and the answer did not resolve it. The chat widget opens its contact form on this signal; your integration can do the same.latencyMs: how long the answer took.department,departmentId: the department the question was routed to, when the site uses departments; otherwisenull.
Stream the answer
/v1/query/streamSame request body. The response is text/event-stream, and every event is a single
data: line with JSON; there are no named events. In order:
{"type":"meta","queryLogId":"..."}first. Keep the id if you want to send feedback.- Optionally
{"type":"sources-early","sources":[...]}, so you can show the sources before the text arrives. {"text":"..."}pieces of the answer. Concatenate them.{"done":true, ...}withhasSufficientContext,escalateLead,sources,departmentanddepartmentId.[DONE]as the very last line.
SSE
data: {"type":"meta","queryLogId":"5c1d2f8e-0a4b-4d0e-8c71-3b9e6f2a1d55"}
data: {"type":"sources-early","sources":[{"sourceUrl":"https://example.com/contact/","snippet":"Opening hours: ...","title":"Contact us"}]}
data: {"text":"On Saturdays"}
data: {"text":" we are open from 10:00 to 14:00."}
data: {"done":true,"hasSufficientContext":true,"escalateLead":false,"sources":[{"sourceUrl":"https://example.com/contact/","snippet":"Opening hours: ...","title":"Contact us"}],"department":null,"departmentId":null}
data: [DONE]
Sources in the stream carry sourceUrl, snippet and title.
A refused request (400, 401, 403, 429) gets an
ordinary JSON error with its status code before any stream starts. If something fails after the
stream has started, you receive {"type":"error","reason":"stream_error"} (or
"provider_unavailable") followed by [DONE].
cURL
curl -N -X POST https://api.slatech.ai/v1/query/stream \
-H "X-Api-Key: $SLATECH_API_KEY" \
-H "Content-Type: application/json" \
-d '{"question": "What are your opening hours?"}'
JavaScript
// EventSource cannot send a POST body or headers, so read the stream with fetch.
const res = await fetch("https://api.slatech.ai/v1/query/stream", {
method: "POST",
headers: {
"X-Api-Key": process.env.SLATECH_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({ question: "What are your opening hours?" }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "", answer = "", queryLogId = null;
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buffer += value;
let i;
while ((i = buffer.indexOf("\n\n")) >= 0) {
const line = buffer.slice(0, i).trim();
buffer = buffer.slice(i + 2);
if (!line.startsWith("data:")) continue;
const payload = line.slice(5).trim();
if (payload === "[DONE]") continue;
const evt = JSON.parse(payload);
if (evt.type === "meta") queryLogId = evt.queryLogId;
else if (evt.type === "error") throw new Error(evt.reason);
else if (evt.text) answer += evt.text;
else if (evt.done) console.log("sources:", evt.sources);
}
}
console.log(answer);
Python
import json
import os
import requests
with requests.post(
"https://api.slatech.ai/v1/query/stream",
headers={"X-Api-Key": os.environ["SLATECH_API_KEY"]},
json={"question": "What are your opening hours?"},
stream=True,
timeout=120,
) as resp:
resp.raise_for_status()
answer, query_log_id = "", None
for line in resp.iter_lines(decode_unicode=True):
if not line or not line.startswith("data:"):
continue
payload = line[5:].strip()
if payload == "[DONE]":
break
evt = json.loads(payload)
if evt.get("type") == "meta":
query_log_id = evt["queryLogId"]
elif evt.get("type") == "error":
raise RuntimeError(evt["reason"])
elif "text" in evt:
answer += evt["text"]
elif evt.get("done"):
sources = evt["sources"]
print(answer)
C#
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using var http = new HttpClient { BaseAddress = new Uri("https://api.slatech.ai/") };
http.DefaultRequestHeaders.Add("X-Api-Key", Environment.GetEnvironmentVariable("SLATECH_API_KEY"));
using var request = new HttpRequestMessage(HttpMethod.Post, "v1/query/stream")
{
Content = JsonContent.Create(new { question = "What are your opening hours?" }),
};
using var resp = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
resp.EnsureSuccessStatusCode();
using var reader = new StreamReader(await resp.Content.ReadAsStreamAsync(), Encoding.UTF8);
var answer = new StringBuilder();
string? line;
while ((line = await reader.ReadLineAsync()) is not null)
{
if (!line.StartsWith("data:")) continue;
var payload = line[5..].Trim();
if (payload == "[DONE]") break;
using var evt = JsonDocument.Parse(payload);
var root = evt.RootElement;
if (root.TryGetProperty("text", out var text)) answer.Append(text.GetString());
else if (root.TryGetProperty("type", out var type) && type.GetString() == "error")
throw new InvalidOperationException(root.GetProperty("reason").GetString());
}
Console.WriteLine(answer);
Rate an answer
/v1/query/{id}/feedbackRecords a thumbs up or down for one answer: {"isHelpful": true} or
false. Send {"sourceClicked": true} when the visitor opened one of the
sources. The id is the queryLogId from the meta event of the
stream; the non-streaming response does not return one, so feedback is available for streamed
answers. Send it after the done event. The answer must belong to the key's site:
success is 204, an unknown id is 404.
cURL
# queryLogId comes from the "meta" event of /v1/query/stream
curl -X PATCH https://api.slatech.ai/v1/query/5c1d2f8e-0a4b-4d0e-8c71-3b9e6f2a1d55/feedback \
-H "X-Api-Key: $SLATECH_API_KEY" \
-H "Content-Type: application/json" \
-d '{"isHelpful": true}'
# 204 No Content on success, 404 if the id is unknown for this site
JavaScript
await fetch(`https://api.slatech.ai/v1/query/${queryLogId}/feedback`, {
method: "PATCH",
headers: {
"X-Api-Key": process.env.SLATECH_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({ isHelpful: false }),
});
Ask about an image
/v1/query/ask-multimodalA multipart/form-data request with two parts: question (up to 2,000
characters) and image (JPEG, PNG, WebP or GIF, up to 10 MB; the type is read from the
part's content type). The response is {"answer": "..."}.
The answer is based on the image and the question. This endpoint does not search the site's
knowledge base and returns no sources. It counts as one answer, like a text question. A
GET on the same address describes the accepted fields.
Errors: 400 for a missing question or image, an unsupported type or a file over
10 MB; 401; 429 when the allowance is used up; 502 when the
image could not be processed, safe to retry.
cURL
curl -X POST https://api.slatech.ai/v1/query/ask-multimodal \
-H "X-Api-Key: $SLATECH_API_KEY" \
-F "question=Which model is this and is it still sold?" \
-F "image=@photo.jpg;type=image/jpeg"
# 200: {"answer": "..."}
JavaScript
import { readFile } from "node:fs/promises";
const form = new FormData();
form.append("question", "Which model is this and is it still sold?");
form.append("image", new Blob([await readFile("photo.jpg")], { type: "image/jpeg" }), "photo.jpg");
const res = await fetch("https://api.slatech.ai/v1/query/ask-multimodal", {
method: "POST",
headers: { "X-Api-Key": process.env.SLATECH_API_KEY },
body: form,
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
console.log((await res.json()).answer);
Python
import os
import requests
with open("photo.jpg", "rb") as image:
resp = requests.post(
"https://api.slatech.ai/v1/query/ask-multimodal",
headers={"X-Api-Key": os.environ["SLATECH_API_KEY"]},
data={"question": "Which model is this and is it still sold?"},
files={"image": ("photo.jpg", image, "image/jpeg")},
timeout=120,
)
resp.raise_for_status()
print(resp.json()["answer"])
C#
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using var http = new HttpClient { BaseAddress = new Uri("https://api.slatech.ai/") };
http.DefaultRequestHeaders.Add("X-Api-Key", Environment.GetEnvironmentVariable("SLATECH_API_KEY"));
using var form = new MultipartFormDataContent();
form.Add(new StringContent("Which model is this and is it still sold?"), "question");
var image = new ByteArrayContent(await File.ReadAllBytesAsync("photo.jpg"));
image.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
form.Add(image, "image", "photo.jpg");
var resp = await http.PostAsync("v1/query/ask-multimodal", form);
resp.EnsureSuccessStatusCode();
var data = await resp.Content.ReadFromJsonAsync<JsonElement>();
Console.WriteLine(data.GetProperty("answer").GetString());
Related
- Getting started: keys, errors and rate limits
- Manage the knowledge base the answers come from
- Read conversations by their
sessionId - Client libraries: these calls from JavaScript/TypeScript and Python
- API reference