Let visitors ask
ask sends one question to the edge’s POST /ask and resolves with the
answer, written from your workspace’s live campaigns. useAsk keeps a
conversation in React. Both are headless: they give you text and state, and
render nothing. The form, the answer’s space and its look are yours.
import { useAsk } from "@sparkletree/react";import { useState } from "react";
function AskBox({ campaignId }: { campaignId: string }) { const { ask, answer, status, links, followUps, error } = useAsk({ campaignId }); const [question, setQuestion] = useState("");
return ( <section className="ask"> <form onSubmit={(event) => { event.preventDefault(); void ask(question); }}> <input value={question} onChange={(event) => setQuestion(event.target.value)} maxLength={1000} /> <button disabled={status === "asking" || status === "streaming"}>Ask</button> </form> {/* The answer grows as it is written: give it a space of its own. */} <div className="ask-answer" aria-live="polite"> {status === "error" ? <p>No answer right now ({error?.reason}).</p> : <p>{answer}</p>} {links.map((link) => <a key={link.url} href={link.url}>{link.label}</a>)} {followUps.map((next) => <button key={next} onClick={() => void ask(next)}>{next}</button>)} </div> </section> );}useAsk
Section titled “useAsk”| Option | |
|---|---|
campaignId |
Answer about this campaign. It must be public on the edge. |
organizationId |
Answer from the workspace’s whole live roster. Defaults to the provider’s workspace when no campaignId is given. |
It returns:
| Member | |
|---|---|
ask(question) |
Ask. A question still running is stopped first. Resolves with core’s AskResult and never rejects. |
answer |
The answer so far while it streams, the whole answer when done. After an error, the text received before it stopped. |
status |
idle before the first question and after reset(); asking until the first piece arrives; streaming while it is written; done; error when no answer could be written. |
links |
Links the answer points to: { label, url }. |
followUps |
Suggested next questions. |
error |
{ reason, status?, message? } when status is error, else null. |
reset() |
Stop a running question, forget the conversation and go back to idle. |
The answer always streams with useAsk. The conversation’s session is kept
between questions, so a follow-up continues the thread; reset() starts a
new one. A question stopped by a newer one, by reset() or by unmount
resolves with reason: "aborted" and changes no state.
Where you render the answer, give it a space of its own, a panel or a dialog, below everything it could push. It grows as it is written.
ask without React
Section titled “ask without React”<form id="ask-form"> <input name="question" maxlength="1000" required /> <button>Ask</button></form><div id="ask-answer" aria-live="polite"></div>
<script type="module"> import { ask } from "@sparkletree/core";
const form = document.getElementById("ask-form"); const output = document.getElementById("ask-answer"); let session = ""; let running = null;
form.addEventListener("submit", async (event) => { event.preventDefault(); running?.abort(); running = new AbortController(); output.textContent = ""; const result = await ask({ apiBase: "https://p.qrtree.ai", campaignId: "CAMPAIGN_ID", question: new FormData(form).get("question"), session: session || undefined, signal: running.signal, onChunk: (_piece, soFar) => { output.textContent = soFar; }, }); if (result.reason === "aborted") return; if (result.session) session = result.session; output.textContent = result.ok ? result.answer : "No answer right now."; });</script>| Option | |
|---|---|
apiBase |
Required. The edge, for example https://p.qrtree.ai. |
question |
Required. Trimmed; at most 1,000 characters, counted in code points (an emoji counts as one). Fallback limits elsewhere in the SDK count UTF-16 code units instead. |
campaignId |
Answer about this public campaign. |
organizationId |
Without a campaign: the workspace whose live roster answers. |
publishableKey |
Your live key, sent as Authorization: Bearer. Needed for a workspace-wide question from your own site. |
session |
The session from an earlier answer, to continue that conversation. |
onChunk(piece, soFar) |
Called with each piece as it is written. Giving it makes the request a stream. |
signal |
Stops the question. |
idleTimeoutMs |
Default 30000. The call stops when no bytes arrive from the edge for this long; each piece starts it again. With text received the result is ok with truncated: true; with none, reason: "timeout". 0 or Infinity turns it off. |
createClient({ publishableKey }).ask({ question, campaignId, session, onChunk })
does the same with the client’s API base, workspace and key.
AskResult is:
| Member | |
|---|---|
ok |
An answer was written. |
answer |
The answer, or the text received before the call stopped. |
links |
{ label, url }[]. |
followUps |
Suggested next questions; empty when there are none. |
session |
Send it back as session to continue. Empty when there is none. |
campaign |
{ id, name, url }, the campaign the answer is about, when there is one. |
homeCampaignId |
The campaign the conversation is grounded in. |
truncated |
The answer was cut off upstream: usable, but it may be incomplete. |
reason, status, error |
Why ok is false, the HTTP status, and the edge’s message. |
ask never rejects. Every failure resolves with ok: false and a reason.
Streaming
Section titled “Streaming”Without onChunk, the edge answers with one JSON document. With it, the
request asks for text/event-stream and the answer arrives in pieces:
| Event | |
|---|---|
chunk |
{ text }, a piece of the answer while it is written. onChunk gets it with the text so far. |
done |
The whole response. Its answer replaces the pieces. |
followups |
{ questions }, suggested next questions, after done. |
error |
No answer was written. |
A stream that ends before done with text received resolves ok: true
with that text and truncated: true. An answer the edge had ready may come
back as one done event, or as JSON; ask reads whichever was sent.
Sessions and follow-ups
Section titled “Sessions and follow-ups”Each answer carries a session. Send it with the next question and the
edge answers with the conversation’s history. Only values the edge handed
out are accepted. An answer the edge served from its store of first answers
comes without a session, and the next question then starts a new
conversation.
With a campaign, the answer may recommend another campaign of the same
workspace. campaign and links then describe the recommended campaign,
and homeCampaignId keeps naming the campaign the conversation is grounded
in. To continue the thread, keep asking with the same campaignId and the
session, never the recommended campaign’s id. useAsk does this for you.
Without a campaign, the question runs against the workspace’s whole live
roster. campaign and links are there only when the answer recommends a
campaign, and there is no homeCampaignId.
When the edge refuses a question
Section titled “When the edge refuses a question”| What | Status | reason |
|---|---|---|
| An empty question. No request is made. | none | invalid_request |
| A question over 1,000 characters (counted in code points, as the edge counts them). No request is made. | none | question_too_long |
A malformed request: a campaign or workspace id that is not a UUID, a session the edge did not hand out, neither a campaign nor a workspace. |
400 | bad_request |
| A campaign that does not exist, is not being served, or is not public on the edge; a workspace-wide question for a workspace with no live public campaigns. | 404 | not_found |
| A campaign whose conversations are not switched on. | 403 | forbidden |
| A workspace-wide question without proof of the workspace (see below). | 403 | forbidden |
Too many questions. The edge sends Retry-After: 60. |
429 | rate_limited |
| No answer could be written. | 502, or an error event |
conversation_failed |
| Any other status. | other | http_error |
A question about one campaign needs no other proof: the campaign must be public on the edge. A workspace-wide question spends the workspace’s answers, so the edge answers it only when the request proves the workspace:
- it is sent to the workspace’s own verified brand host, or
- it carries the workspace’s live publishable key (
st_pk_live_) from an origin registered for the workspace.
Test keys are not accepted for workspace-wide questions. From your own site,
pass your live key (useAsk sends the provider’s) and register the origin;
see Origins, CSP and privacy.
Limits
Section titled “Limits”- A question is at most 1,000 characters; a request body at most 8 KB.
- The edge limits requests per visitor IP address and answers 429 with
Retry-After: 60when the limit is reached. - Every answer is written by the workspace’s assistant from its live campaigns. A campaign that is not public on the edge cannot be asked about.