Skip to content

SDK Examples DotNet

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

.NET SDK — Examples

Package: Hevolus.XRCopilotLab.Client.Public (.NET 8.0+) · See SDK-Overview for installation and configuration.

Every snippet below is self-contained. Replace the placeholder identifiers (<YOUR_API_KEY>, company-id, topic-id, agent-id, endpoint-id, profile-id, orchestrator-id) with your own values. All service methods hang off the five service properties on AppClient: Topics, Profiles, Agents, Orchestrators, Common.

1. Client setup

Construct an AppClient with your subscription key. The API version defaults to the current production version; pass it explicitly only if you need a specific one. A single AppClient is safe to reuse for the lifetime of your app.

using XRCopilotLab.Client;

var client = new AppClient("<YOUR_API_KEY>");

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

2. Chat with an agent

ChatAsync is synchronous from the caller's perspective: it sends the prompt and returns the assistant's AssistantResponse in the same call (which may take several seconds for deep-reasoning agents). Reuse the returned ConversationId to continue the same conversation.

using XRCopilotLab.Client;
using XRCopilotLab.Core.Models;

var client = new AppClient("<YOUR_API_KEY>");

var prompt = new UserPrompt
{
    CompanyId = "company-id",
    TopicId = "topic-id",
    AgentId = "agent-id",
    EndpointId = "endpoint-id",
    Message = "Hello, how can you help me?"
    // ConversationId left unset — the SDK generates a new one.
};

AssistantResponse response = await client.Agents.ChatAsync(prompt);
Console.WriteLine(response.Message);

// Continue the same conversation by reusing the returned ConversationId.
var followUp = new UserPrompt
{
    CompanyId = "company-id",
    TopicId = "topic-id",
    AgentId = "agent-id",
    EndpointId = "endpoint-id",
    Message = "Tell me more.",
    ConversationId = response.ConversationId
};
AssistantResponse second = await client.Agents.ChatAsync(followUp);
Console.WriteLine(second.Message);

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

For long-running prompts, StartChatAsync dispatches the work and returns immediately (HTTP 202 Accepted) with a ChatAsyncResponse carrying the identifiers you need to poll. Poll GetConversationHistoryAsync until an assistant message appears.

using System.Linq;
using XRCopilotLab.Client;
using XRCopilotLab.Core.Models;

var client = new AppClient("<YOUR_API_KEY>");

var conversationId = Guid.NewGuid().ToString();
var prompt = new UserPrompt
{
    CompanyId = "company-id",
    TopicId = "topic-id",
    AgentId = "agent-id",
    EndpointId = "endpoint-id",
    Message = "Analyze this data in detail.",
    ConversationId = conversationId
};

ChatAsyncResponse accepted = await client.Agents.StartChatAsync(prompt);

// Poll the conversation history until the assistant has replied.
HistoryMessage? reply = null;
for (int i = 0; i < 120 && reply is null; i++)
{
    await Task.Delay(2000);
    History history = await client.Agents.GetConversationHistoryAsync(
        accepted.CompanyId, accepted.TopicId, accepted.AgentId, conversationId, 2);
    reply = history.Messages
        .Where(m => m.role == "assistant" && !string.IsNullOrEmpty(m.content))
        .LastOrDefault();
}

Console.WriteLine(reply?.content ?? "Timed out waiting for a response.");

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

Upload a document into a topic, then poll the owning profile's indexing status. UploadFileAsync takes a Stream, the topic identifiers, the target file name, and a FileScope. Indexing runs server-side after upload, so check the current indexing status with GetIndexingStatusAsync.

using XRCopilotLab.Client;
using XRCopilotLab.Core.Enums;
using XRCopilotLab.Core.Models;

var client = new AppClient("<YOUR_API_KEY>");

using var stream = File.OpenRead("document.pdf");
bool uploaded = await client.Topics.UploadFileAsync(
    stream,
    "company-id",
    "topic-id",
    "document.pdf",
    FileScope.None);      // FileScope.None — profile-scoped upload (the API receives the raw int value)

Console.WriteLine(uploaded ? "Upload accepted." : "Upload failed.");

// Check the indexing status of the profile that owns the file.
var profile = await client.Profiles.GetProfileAsync("company-id", "topic-id", "profile-id");
if (profile is not null)
{
    IndexingStatus status = await client.Profiles.GetIndexingStatusAsync(profile);
    Console.WriteLine($"Indexing status: {System.Text.Json.JsonSerializer.Serialize(status)}");
}

4. Run an orchestrator and read the result/events

ExecuteAndWaitAsync is the high-level helper: it starts the orchestration, streams its SSE events, invokes your interactionHandler whenever the workflow pauses for user input, and returns the final OrchestrationResult. Pre-allocating the ExecutionId lets the stream attach before any early events are emitted.

The .NET SDK maps each interaction onto a typed UserInteractionRequest; read its RequestId to echo back into the response. (The JS and Python SDKs expose the same identifier as interactionId / interaction_id respectively.)

using XRCopilotLab.Client;
using XRCopilotLab.Core.Models.Orchestration;

var client = new AppClient("<YOUR_API_KEY>");

var request = new OrchestrationRequest
{
    Message = "Analyze Q3 sales.",
    ExecutionId = Guid.NewGuid().ToString().ToUpperInvariant(),
    ConversationId = Guid.NewGuid().ToString(),
    AnswerLanguage = "en"
};

using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(15));

OrchestrationResult result = await client.Orchestrators.ExecuteAndWaitAsync(
    "company-id",
    "orchestrator-id",
    request,
    interactionHandler: async (interaction, ct) =>
    {
        // The workflow paused to ask the user something.
        Console.WriteLine($"Interaction required: {interaction.Message}");
        return new UserInteractionResponse
        {
            RequestId = interaction.RequestId,
            ResponseValue = "yes",
            WasSkipped = false,
            ResponseTimestamp = DateTime.UtcNow,
            AnswerLanguage = "en"
        };
    },
    progressHandler: evt =>
    {
        // Called for every SSE event as the run progresses.
        Console.WriteLine($"[{evt.Seq:D5}] {evt.EventType}");
    },
    ct: cts.Token);

Console.WriteLine($"Status={result.Status} Success={result.Success}");
// FinalOutput, or the last SendMessage text when the orchestrator ends with one.
Console.WriteLine(result.GetEffectiveFinalOutput());

For finer control you can drive the lifecycle yourself — StartExecutionAsync to dispatch, then StreamExecutionAsync (an IAsyncEnumerable<OrchestrationEvent>) to consume events, or GetExecutionStatusAsync to poll the terminal result after a disconnect.

5. Error handling

The .NET SDK throws on error. Wrap calls in try/catch and handle HttpRequestException (transport / non-success status) distinctly from other failures.

using XRCopilotLab.Client;
using XRCopilotLab.Core.Models;

var client = new AppClient("<YOUR_API_KEY>");

var prompt = new UserPrompt
{
    CompanyId = "company-id",
    TopicId = "topic-id",
    AgentId = "agent-id",
    EndpointId = "endpoint-id",
    Message = "Hello!"
};

try
{
    AssistantResponse response = await client.Agents.ChatAsync(prompt);
    Console.WriteLine(response.Message);
}
catch (HttpRequestException ex)
{
    Console.WriteLine($"HTTP error: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Unexpected error: {ex.Message}");
}

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