שאילת שאלות
שולחים שאלה ומקבלים תשובה שמבוססת על התוכן של האתר, יחד עם המקורות שלה: בבת אחת, או בהזרמה תוך כדי כתיבה.
כל נקודות הקצה בעמוד הזה מקבלות כל מפתח פעיל של האתר, כולל מפתח הווידג'ט. כל שאלה שנענתה נספרת כתשובה אחת מתוך המכסה החודשית של האתר.
שאלה ותשובה מלאה
/v1/query| שדה | תיאור |
|---|---|
question | חובה. עד 2,000 תווים. |
sessionId | מזהה של השיחה, עד 100 תווים. השתמשו ב-UUID, אחד לכל שיחה: כל תור בשיחה נשמר איתו, נקודות הקצה של הנתונים מחזירות שיחה לפיו, והניתוח שרץ ברקע ומפיק סיכומי שיחה, תגיות ו-webhooks של סנטימנט בודק רק שיחות שהמזהה שלהן הוא UUID. מזהים שמתחילים ב-voice_, ב-sms_, ב-tg_ או ב-wa_ שייכים לערוצים אחרים ומתעלמים מהם. |
conversationHistory | התורות הקודמים בשיחה בתור {"role", "content"}, כאשר role הוא user או assistant ו-content עד 4,000 תווים. נעשה שימוש בשש ההודעות האחרונות. |
visitorId | המזהה שלכם לאדם ששואל, עד 100 תווים. נשמר עם התור. |
pageUrl | הדף שבו נשאלה השאלה. נשמר עם התור. |
utmSource, utmMedium, utmCampaign | תגיות קמפיין, עד 50 תווים כל אחת. נשמרות עם התור לטובת האנליטיקה. |
topK, scoreThreshold | הגדרות שליפה: 1 עד 20 (ברירת מחדל 5) ו-0 עד 1 (ברירת מחדל 0.35). ההגדרות של האתר עצמו קודמות; הערכים שלכם חלים רק אם האתר מתיר לעקוף אותן או שאין לו ערך משלו. |
additionalSiteIds | אתרים נוספים של אותו חשבון שבהם יתבצע חיפוש. אתר של חשבון אחר נדחה בקוד 403; אתר שהמכסה שלו נוצלה מושמט. |
ה-API לא זוכר את השיחה בשבילכם. כדי לשאול שאלת המשך כמו "ובשבת?", שולחים את
התורות הקודמים ב-conversationHistory. ה-sessionId מקבץ את התורות לטובת
הרישום והאנליטיקה שלכם; הוא לא מחזיר את התורות הקודמים לתוך התשובה.
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;
}
התשובה
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: טקסט התשובה.sources: הקטעים שעליהם התשובה מבוססת, עם כתובת הדף, הכותרת שלו, קטע קצר וציון ההתאמה.titleו-snippetיכולים להיות ריקים.hasSufficientContext:falseכשבבסיס הידע לא היה מספיק מידע כדי לענות.escalateLead:trueכשהשאלה מראה כוונת רכישה והתשובה לא פתרה אותה. וידג'ט הצ'אט פותח את טופס יצירת הקשר לפי הסימן הזה, והאינטגרציה שלכם יכולה לעשות אותו דבר.latencyMs: כמה זמן לקחה התשובה.department,departmentId: המחלקה שאליה נותבה השאלה, כשהאתר עובד עם מחלקות; אחרתnull.
תשובה בהזרמה
/v1/query/streamאותו גוף בקשה. התשובה היא text/event-stream, וכל אירוע הוא שורת
data: אחת עם JSON, בלי שמות אירועים. לפי הסדר:
- קודם
{"type":"meta","queryLogId":"..."}. שמרו את המזהה אם תרצו לשלוח משוב. - לפעמים
{"type":"sources-early","sources":[...]}, כדי שאפשר יהיה להציג את המקורות עוד לפני שהטקסט מגיע. - חלקי התשובה בתור
{"text":"..."}. מחברים אותם לפי הסדר. {"done":true, ...}עםhasSufficientContext,escalateLead,sources,departmentו-departmentId.[DONE]בשורה האחרונה ממש.
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]
מקורות בזרם כוללים sourceUrl, snippet ו-title. בקשה
שנדחתה (400, 401, 403, 429) מקבלת שגיאת JSON
רגילה עם הקוד שלה, עוד לפני שהזרם מתחיל. אם משהו נכשל אחרי שהזרם כבר התחיל, מגיע
{"type":"error","reason":"stream_error"} (או "provider_unavailable")
ואחריו [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);
דירוג תשובה
/v1/query/{id}/feedbackרושם אגודל למעלה או למטה לתשובה אחת: {"isHelpful": true} או false.
שלחו {"sourceClicked": true} כשהמבקר פתח אחד מהמקורות. ה-id הוא
ה-queryLogId מאירוע ה-meta של הזרם; התשובה הרגילה (שלא בהזרמה) לא מחזירה
מזהה, ולכן משוב זמין לתשובות בהזרמה. שלחו אותו אחרי אירוע ה-done. התשובה צריכה
להיות שייכת לאתר של המפתח: הצלחה היא 204, מזהה לא מוכר הוא 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 }),
});
שאלה על תמונה
/v1/query/ask-multimodalבקשת multipart/form-data עם שני חלקים: question (עד 2,000 תווים)
ו-image (JPEG, PNG, WebP או GIF, עד 10 MB; הסוג נקבע לפי ה-content type של החלק).
התשובה היא {"answer": "..."}.
התשובה מבוססת על התמונה ועל השאלה. נקודת הקצה הזאת לא מחפשת בבסיס הידע של האתר ולא מחזירה
מקורות. היא נספרת כתשובה אחת, כמו שאלת טקסט. בקשת GET לאותה כתובת מתארת את השדות
שמתקבלים.
שגיאות: 400 כשחסרה שאלה או תמונה, כשהסוג לא נתמך או כשהקובץ גדול מ-10 MB;
401; 429 כשהמכסה נוצלה; 502 כשלא ניתן היה לעבד את התמונה,
ואפשר לנסות שוב.
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());
קשור
- תחילת עבודה: מפתחות, שגיאות ומגבלות קצב
- ניהול בסיס הידע שממנו מגיעות התשובות
- קריאת שיחות לפי ה-
sessionIdשלהן - ספריות לקוח: הקריאות האלה מתוך JavaScript/TypeScript ו-Python
- הפניית ה-API