Skip to content

SDK Examples JavaScript

Marcello Marchetti edited this page Jun 4, 2026 · 2 revisions

JavaScript SDK — Examples

Package: xrcopilotlab.client.public.js (Browser / Node.js, CommonJS) · See SDK-Overview for installation and configuration.

The JavaScript SDK exposes a single flat client — every operation is a method directly on XRCopilotLabClient (no service grouping). Methods return null (or false/[], depending on the call) and log to the console on error rather than throwing.

Prompt object keys are PascalCase. The chat methods read CompanyId, TopicId, AgentId, EndpointId, and Message off the prompt object to build the request route — use those exact casings.

1. Client setup

Require the package (it is published as a CommonJS module that exports the class) and construct the client with your subscription key. The API version defaults to the current production version.

const XRCopilotLabClient = require('xrcopilotlab.client.public.js');

const client = new XRCopilotLabClient("<YOUR_API_KEY>");

// Or pin a specific API version:
// const client = new XRCopilotLabClient("<YOUR_API_KEY>", "2025-05-01");

2. Chat with an agent

chatAsync sends the prompt and resolves with the assistant response object (which may take several seconds for deep-reasoning agents). The response carries Message and ConversationId; reuse ConversationId to continue the same conversation.

const XRCopilotLabClient = require('xrcopilotlab.client.public.js');

const client = new XRCopilotLabClient("<YOUR_API_KEY>");

async function chat() {
    const prompt = {
        CompanyId: "company-id",
        TopicId: "topic-id",
        AgentId: "agent-id",
        EndpointId: "endpoint-id",
        Message: "Hello, how can you help me?"
        // ConversationId omitted — the SDK generates one.
    };

    const response = await client.chatAsync(prompt);
    if (response === null) {
        console.error("Chat request failed.");
        return;
    }
    console.log(response.Message);

    // Continue the conversation by reusing the returned ConversationId.
    const followUp = {
        CompanyId: "company-id",
        TopicId: "topic-id",
        AgentId: "agent-id",
        EndpointId: "endpoint-id",
        Message: "Tell me more.",
        ConversationId: response.ConversationId
    };
    const second = await client.chatAsync(followUp);
    console.log(second?.Message);
}

chat();

Async variant (fire-and-forget + history polling)

startChatAsync dispatches the prompt and returns immediately (HTTP 202 Accepted) with the identifiers needed to poll. Poll getConversationHistoryAsync until an assistant message appears.

const XRCopilotLabClient = require('xrcopilotlab.client.public.js');
const crypto = require('crypto');

const client = new XRCopilotLabClient("<YOUR_API_KEY>");

async function asyncChat() {
    const conversationId = crypto.randomUUID();
    const prompt = {
        CompanyId: "company-id",
        TopicId: "topic-id",
        AgentId: "agent-id",
        EndpointId: "endpoint-id",
        Message: "Analyze this data in detail.",
        ConversationId: conversationId
    };

    const accepted = await client.startChatAsync(prompt);
    if (accepted === null) {
        console.error("Dispatch failed.");
        return;
    }

    // Poll history until the assistant replies (up to ~4 minutes).
    for (let i = 0; i < 120; i++) {
        await new Promise(r => setTimeout(r, 2000));
        const history = await client.getConversationHistoryAsync(
            accepted.companyId, accepted.topicId, accepted.agentId, conversationId, 2);
        const messages = history?.Messages ?? history?.messages ?? [];
        const reply = messages.filter(m => m.role === "assistant" && m.content).pop();
        if (reply) {
            console.log(reply.content);
            return;
        }
    }
    console.error("Timed out waiting for a response.");
}

asyncChat();

3. Upload a file to a topic and check indexing status

uploadFileAsync accepts a File, Blob, or ArrayBuffer, the topic identifiers, the target file name, and the scope (0 = Profile, 1 = Agent). Indexing runs server-side after upload — poll getIndexingStatus, passing a profile object whose CompanyId, TopicId, and ProfileId keys identify the index.

const XRCopilotLabClient = require('xrcopilotlab.client.public.js');
const fs = require('fs');

const client = new XRCopilotLabClient("<YOUR_API_KEY>");

async function uploadAndCheck() {
    // In Node.js, read the file into an ArrayBuffer; in the browser, pass a File/Blob.
    const buffer = fs.readFileSync("document.pdf");
    const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);

    const uploaded = await client.uploadFileAsync(
        arrayBuffer,
        "company-id",
        "topic-id",
        "document.pdf",
        0);   // 0 = Profile scope, 1 = Agent scope
    console.log(uploaded ? "Upload accepted." : "Upload failed.");

    // Check indexing status of the owning profile.
    const profile = await client.getProfileAsync("company-id", "topic-id", "profile-id");
    if (profile) {
        const status = await client.getIndexingStatus(profile);
        console.log("Indexing status:", status);
    }
}

uploadAndCheck();

4. Run an orchestrator and read the result/events

executeOrchestrationAndWaitAsync starts the orchestration, streams its SSE events, calls onUserInteractionRequired whenever the workflow pauses for input, and resolves with the final OrchestrationResult. onProgress fires for every event as the run advances.

const XRCopilotLabClient = require('xrcopilotlab.client.public.js');
const crypto = require('crypto');

const client = new XRCopilotLabClient("<YOUR_API_KEY>");

async function runOrchestrator() {
    const request = {
        Message: "Analyze Q3 sales.",
        ExecutionId: crypto.randomUUID().toUpperCase(),
        ConversationId: crypto.randomUUID(),
        AnswerLanguage: "en"
    };

    const result = await client.executeOrchestrationAndWaitAsync(
        "company-id",
        "orchestrator-id",
        request,
        {
            onProgress: (evt) => {
                console.log(`[${evt.seq}] ${evt.eventType}`);
            },
            onUserInteractionRequired: async (interaction) => {
                // The workflow paused to ask the user something.
                console.log("Interaction required:", interaction.message);
                return {
                    requestId: interaction.interactionId,
                    responseValue: "yes",
                    wasSkipped: false,
                    answerLanguage: "en"
                };
            }
        });

    console.log("Final output:", result?.finalOutput);
}

runOrchestrator();

For finer control, use startOrchestrationExecutionAsync to dispatch and the streamOrchestrationExecution async generator (or the callback-style subscribeToOrchestration) to consume events yourself; getOrchestrationStatusAsync polls the terminal result after a disconnect.

5. Error handling

JavaScript SDK methods do not throw for HTTP errors — they log to the console and return null (read methods that return collections return [], and boolean operations return false). Always check the return value before using it.

const XRCopilotLabClient = require('xrcopilotlab.client.public.js');

const client = new XRCopilotLabClient("<YOUR_API_KEY>");

async function safeChat() {
    const prompt = {
        CompanyId: "company-id",
        TopicId: "topic-id",
        AgentId: "agent-id",
        EndpointId: "endpoint-id",
        Message: "Hello!"
    };

    const response = await client.chatAsync(prompt);
    if (response === null) {
        console.error("Chat request failed — check the API key, identifiers, and network.");
        return;
    }
    console.log(response.Message);
}

safeChat();

Note: a few methods (e.g. uploadTempFileAsync, getTempFilesStatusAsync, and the orchestrator start/resume helpers) do throw on failure. Wrap those in try/catch in addition to checking return values.


More examples are added with each release. Have a use case you'd like covered? Open an issue on xrcopilot-docs.

Clone this wiki locally