@aiqa/sdk
v1.5.0
Published
TypeScript/JavaScript SDK for interacting with the AIQA.
Readme
AIQA SDK
A TypeScript/JavaScript SDK for interacting with the AIQA WebSocket service. This SDK provides methods for managing applications, recording audio, and tracking facts during conversations.
Table of Contents
- Installation
- Getting Started
- Configuration
- API Reference
- Verification lifecycle
- Types
- Examples
- Error Handling
- Semantic Versioning
Installation
npm install @aiqa/sdkGetting Started
Basic Setup
import AiQaSdk from "@aiqa/sdk";
// Initialize the SDK
const sdk = new AiQaSdk(
"app-id-123",
"app-secret-xyz",
"https://api.solutionson.ai/",
);
// Connect to the service, then attach listeners
sdk.connect();
sdk.on("connect", () => {
console.log("Connected to AIQA service");
});
sdk.on("error", (error) => {
console.error("Connection error:", error);
});Configuration
SDK Initialization
new AiQaSdk(applicationId, applicationSecret, url?)API Reference
Connection Management
connect()
Establishes a WebSocket connection to the AIQA service.
sdk.connect();disconnect()
Closes the WebSocket connection.
sdk.disconnect();Application Management
getApplication()
Returns the cached application loaded during authentication.
If authentication hasn't completed yet, this throws. Use the authenticated event to know when it's ready.
const application = await sdk.getApplication();setConversationProduct(product)
Sets the conversation product using a valid product code.
Parameters:
product: string- product code (from theservice.codecatalog)
Returns:
Promise<{ success: boolean; product: string }>
const result = await sdk.setConversationProduct("life_insurance");
console.log(result.success, result.product);setConversationLanguage(language)
Sets the conversation language.
Parameters:
language: ConversationLanguage- only valid enum values are accepted
Returns:
Promise<{ success: boolean; language: string }>
import { ConversationLanguage } from "@aiqa/sdk";
const result = await sdk.setConversationLanguage(ConversationLanguage.EN);
console.log(result.success, result.language);Fact Management
addFact(fact)
Adds a fact to the active application and waits for the terminal
verification verdict (Promise-based). The Promise resolves with an
AddFactResult; subscribe to the
FACT_VERIFIED broadcast event to render progress
(awaiting_question, awaiting_answer, partial,
pending_confirmation_matched, pending_confirmation_unmatched)
while you wait.
addFact() does not throw on verification failure — an unmatched
fact resolves with is_valid_answer: false and (where the backend
provides it) verification_status: "unmatched" or "contradicted".
Reject paths are reserved for transport / protocol errors.
Parameters:
fact: ApplicationFactInput{ id: string; /** * Optional. Stable identifier for the underlying question, shared across * applications and conversations. When provided it is used to look up (or * create) the matching question row in the database instead of `id`. When * omitted, `id` is used (legacy behavior). * * Keep this consistent across calls for the "same" question — see * "Question identity and questionId" below. */ questionId?: string; question: string; expected_answer: any; answer_format: { type: "STRING" } /** * Optional. Use this to attach your own identifiers to a fact so your UI * can map the server response back to the right field or component. * For example, store a form field ID, a section name, or any internal * reference you need — the server stores it as-is and returns it unchanged * in getFacts(). * * Constraints: all keys and values must be strings; each value is limited * to 1024 characters. Payloads that exceed this limit are rejected. */ metadata?: Record<string, string> }
const result = await sdk.addFact({
id: "fact-123",
questionId: "agreement-q",
question: "Do you agree?",
expected_answer: "Yes",
answer_format: { type: "STRING" },
metadata: { uiFieldId: "policy-agreement", section: "consent" },
});
if (result.is_valid_answer) {
// verification_status will be "matched" (or "contradicted" if the
// customer explicitly contradicted the expected answer).
console.log("matched:", result.ai_answer);
} else {
// verification_status will be "unmatched". matched_components /
// missing_components describe what the partial-match heuristics
// were able to extract.
console.log("unmatched:", result.missing_components);
}Question identity and questionId
id identifies an instance of a fact within a single conversation. questionId
is an optional field that identifies the underlying question across every
application and conversation that asks it. They're separated so you can give
each fact instance its own id (e.g. a per-call uuid) while still pointing at a
stable question identity.
Two server-side features are scoped per question identity:
- Accuracy improvements. Per-question signals (flags, model tweaks, fuzzy matches) accumulate against the question row. Splitting the same logical question across multiple identities splits these signals and resets the accuracy gains you've already earned.
- Remaps from the management dashboard. When an operator remaps a question in the dashboard, the remap is stored on the question row. A subsequent call with a different identity won't pick up the remap.
The "question identity" the server uses is questionId if you sent one,
otherwise id. So:
- If your
idis already stable across calls for the same logical question, omittingquestionIdis fine — both features above still work, just keyed offid. - If your
idvaries per call (per-call uuid, ephemeral instance id, etc.), send a stablequestionId. Otherwise each call looks like a new question and you lose the features above. - Once you've picked an identity for a question, don't change it. If you must rename, coordinate with the team owning the dashboard so remaps and historical signals can be migrated.
getFacts()
Retrieves all facts for the application (Promise-based). Each fact includes a metadata field containing whatever was passed to addFact(). Facts added without metadata return {}.
const facts = await sdk.getFacts();
facts.forEach((fact) => {
console.log(fact.id, fact.metadata); // e.g. { uiFieldId: "policy-agreement" } or {}
});flagFact(factId)
Flags a fact for human review. Creates a signal that allow AIQA to improve review quality.
Parameters:
factId: string- theidof the fact to flag (must match theidused inaddFact())
Returns:
Promise<FlagFactResult>—{ success: boolean }
const result = await sdk.flagFact("fact-123");
console.log(result.success); // trueRecording Management
startRecording()
Starts audio recording (Promise-based).
const started = await sdk.startRecording();stopRecording()
Stops audio recording (Promise-based).
const stopped = await sdk.stopRecording();isRecordingNow()
Checks if recording is currently active (Promise-based).
const isRecording = await sdk.isRecordingNow();Event Handling
on(eventName, callback)
Registers an event listener. Call connect() before on().
Available Events:
connect- Socket.IO connection establisheddisconnect- Socket.IO connection closedclose- Socket.IO connection closederror- Connection or socket errorreconnect_attempt- Socket.IO reconnection attemptreconnect_error- Socket.IO reconnection errorreconnect_failed- Socket.IO reconnection failedauthenticated- Local event fired after successful authentication (provides Application object)app_version- Server event with version requirements{ min, max }FACT_VERIFIED- Broadcast event fired on every verification state transition (both non-terminal progress and terminal verdicts) for every fact in the active conversation. Payload shape:FactVerifiedPayload. Use this to render live verification progress in your UI;addFact()'s Promise only resolves on the terminal state.
sdk.connect();
sdk.on("connect", () => {
console.log("Connected");
});
sdk.on("authenticated", (application) => {
console.log("Authenticated:", application);
});
sdk.on("FACT_VERIFIED", (payload) => {
// Renders progress for every fact in the conversation.
console.log(payload.factId, payload.verification_status);
});Verification lifecycle
A single addFact() call walks through a sequence of states emitted
on the FACT_VERIFIED broadcast event before the Promise resolves:
processing
└─> awaiting_question (agent hasn't asked yet)
└─> awaiting_answer (asked, customer hasn't answered yet)
└─> partial (partial evidence — e.g. "305" of "30521")
└─> pending_confirmation_matched
(backend has a match but is holding a settling
window for mid-answer clarifications like
spellings or "I mean…" corrections)
└─> pending_confirmation_unmatched
(same, but for a held unmatched verdict)
│
▼
matched | unmatched | contradicted ← terminalRules for consumers:
addFact()resolves only on a terminal state (matched,unmatched,contradicted). Render progress from theFACT_VERIFIEDevent, render the final verdict from the Promise result.- Treat unknown
verification_statusstrings asprocessing. The enum is additive — older SDK builds must fall through gracefully when the backend ships a new state. pending_confirmation_*is never terminal. The wire-visible latency penalty is bounded bysettling_window_mson the server (default 2000 ms). The held verdict can flip — that's the whole point — so don't treat it as a commit.
off(eventName, callback?)
Removes an event listener.
sdk.off("connect");Types
Application
type Application = {
application_id: string;
client_name: string;
client_phone_number: string;
agent_id: string;
agent_first_name: string;
agent_last_name: string;
};ApplicationFact
Returned by getFacts(). Extends ApplicationFactInput and adds server-side fields.
type ApplicationFact = ApplicationFactInput & {
ai_answer?: any;
question_status: "searching" | "asked" | "not_asked";
verification_status: VerificationStatus;
flagged: boolean; // true once flagFact() has been called for this fact
metadata: Record<string, string>; // always present; {} when not set on addFact
};AddFactResult
Resolved value of addFact(). Only emitted at the terminal verification
state — see Verification lifecycle.
interface AddFactResult {
/** Conversation the fact was attached to. */
conversation_id?: string;
/** Echo of the original question text from the fact input. */
question?: string;
/** Echo of the resolved answer_format.type (e.g. "STRING", "NUMBER"). */
answer_type?: string;
agent_answer?: string;
ai_answer?: string;
is_valid_answer: boolean;
question_asked?: boolean;
/**
* 0–1 (or 0–100 — scale matches the configured similarity method).
* Similarity between the agent's utterance and the expected question.
*/
question_match_score?: number;
/**
* 0–1 score derived from how well the customer's answer matched expected.
* Populated by the verification queue from partial-match heuristics
* (numeric-prefix ratio, matched-components ratio).
*/
answer_match_score?: number;
/**
* Top-level state at terminal resolution. Always one of `matched`,
* `unmatched`, or `contradicted` because the `addFact()` Promise only
* resolves on terminals. Optional during the rollout window for
* backwards compatibility with older backends.
*/
verification_status?: VerificationStatus;
/**
* Per-fact partial-match breakdown carried through from the
* verification queue's component-wise comparators. For numeric-prefix
* facts these are `["prefix"]` / `["suffix"]`; future work will
* generalise to addresses, names, dates, etc.
*/
matched_components?: string[];
missing_components?: string[];
metadata?: Record<string, string>;
}VerificationStatus
type VerificationStatus =
| "processing"
| "awaiting_question"
| "awaiting_answer"
| "partial"
| "pending_confirmation_matched"
| "pending_confirmation_unmatched"
| "matched"
| "unmatched"
| "contradicted";The enum is additive: consumers that switch on this value MUST
treat unknown strings as "processing" so older SDK builds keep
working after the backend ships a new state. See the
Verification lifecycle for the transitions
and which states are terminal.
FactVerifiedPayload
Payload of the FACT_VERIFIED broadcast event. Same shape as
AddFactResult plus the factId / success / error envelope.
interface FactVerifiedPayload {
factId: string;
success: boolean;
verification_status?: VerificationStatus;
question_match_score?: number;
answer_match_score?: number;
matched_components?: string[];
missing_components?: string[];
/** Same shape as AddFactResult so the same renderer handles both. */
data?: AddFactResult;
error?: string;
}ApplicationFactInput
type ApplicationFactInput = {
id: string;
/**
* Optional. Stable identifier for the underlying question, shared across
* applications and conversations. Used to look up (or create) the matching
* question row in the database when provided. When omitted, `id` is used.
*
* Keep this consistent across calls — accuracy improvements and remaps
* configured in the management dashboard are scoped per `questionId`. See
* "Question identity and questionId" under `addFact()`.
*/
questionId?: string;
question: string;
expected_answer: any;
answer_format: {
type:
| "STRING"
| "NUMBER"
| "INT"
| "FLOAT"
| "BOOL"
| "LIST"
| "STRICT"
| "SINGLE_CHOICE"
| "MULTIPLE_CHOICES";
choices?: { key: string; text: string }[];
};
category_id?: string;
category_name?: string;
language?: string;
critical?: boolean;
is_skipped?: boolean;
/**
* Optional. Attach your own identifiers to a fact so your UI can map the
* server response back to the right field or component — for example a form
* field ID, a section name, or any internal reference you need.
*
* The server stores this value encrypted alongside the fact and returns it
* unchanged in getFacts(). It is never inspected, indexed, or used for
* verification logic.
*
* Constraints:
* - All keys and values must be strings.
* - Each individual value is limited to 1024 characters.
* - Payloads that violate either constraint are rejected by the server.
*/
metadata?: Record<string, string>;
};FlagFactResult
Returned by flagFact().
type FlagFactResult = {
success: boolean;
};ConversationLanguage
enum ConversationLanguage {
EN = "en",
ES = "es",
FR = "fr",
}FactUpdateEvent
type FactUpdateEvent = {
fact_id: string;
question_id?: string;
status:
| "asked"
| "answered_detected"
| "agent_answered"
| "verification_pending"
| "verified"
| "failed";
detectedAnswer?: any;
agentAnswer?: any;
verifiedAnswer?: any;
};Semantic Versioning
Version bumps are automated with semantic commits and semantic-release in Bitbucket Pipelines:
mastercreates stable releases.developcreates prereleases on thedevelopchannel (for example1.2.3-develop.1).
Commit types and version bump
fix: ...-> patch bump (0.0.6->0.0.7)feat: ...-> minor bump (0.0.6->0.1.0)feat!: ...or commit body withBREAKING CHANGE:-> major bump (0.0.6->1.0.0)chore: ...- Other commit types (for example
docs:,chore:) do not trigger a release by default.
Examples
fix: handle socket timeout error
feat: add isRecordingNow helper
feat!: change addFact response contractPipeline requirements
Set these repository variables so the release step can push tags/commits and publish to npm:
BB_TOKEN_BASIC_AUTHwith valueuser:tokenNPM_TOKENwith publish access to@aiqa/sdk
Examples
Complete Example: Recording Session
import AiQaSdk from "@aiqa/sdk";
// Initialize SDK
const sdk = new AiQaSdk(
"application-id-123",
"application-secret-xyz",
"https://api.solutionson.ai/",
);
sdk.connect();
sdk.on("connect", async () => {
console.log("Connected!");
try {
const application = await sdk.getApplication();
console.log("Application loaded:", application.application_id);
// Start recording
await sdk.startRecording();
console.log("Recording started");
// Optional: render live verification progress for every fact
// in the conversation while the addFact() Promise is in flight.
sdk.on("FACT_VERIFIED", (payload) => {
console.log(
`[${payload.factId}] ${payload.verification_status ?? "processing"}`,
);
});
// Add a fact (Promise resolves at the terminal verdict)
const result = await sdk.addFact({
id: "q1",
question: "What is your name?",
expected_answer: "",
answer_format: {
type: "STRING",
},
});
console.log(
"Terminal verdict:",
result.verification_status,
"is_valid_answer:",
result.is_valid_answer,
"ai_answer:",
result.ai_answer,
);
// Stop recording
await sdk.stopRecording();
console.log("Recording stopped");
} catch (error) {
console.error("Error:", error);
}
});
sdk.on("error", (error) => {
console.error("SDK Error:", error);
});Error Handling
All methods are Promise-based. Use try/catch for errors.
try {
const application = await sdk.getApplication();
console.log("Success:", application);
} catch (error) {
console.error("Error:", error);
}Common Error Scenarios
- Connection Errors: Fired through the
errorevent - Version Mismatch: Thrown when the server version is incompatible
- Invalid Data: Returned as rejected promises
- Network Issues: Handled through reconnection events
Version Requirements
The server emits an app_version payload with { min, max } supported SDK versions. If the current SDK version is outside that range, the SDK disconnects and emits an error event.
License
MIT
