> ## Documentation Index
> Fetch the complete documentation index at: https://humain.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# .NET

> async/await .NET SDK for Humain Kiosk — text sessions, streaming, and ASP.NET Core dependency injection.

## Install

```bash theme={null}
dotnet add package Humain.Kiosk
```

Requires .NET 8+. Compatible with .NET 8 and .NET 9. The package targets `net8.0` and above.

> [!TIP]
>
> During development, initialise the client with an `hk_test_…` sandbox credential instead of
> `hk_live_…`. There is no separate sandbox mode or URL — sandbox behavior comes entirely from
> the credential prefix. No AI credits are consumed and no usage is billed. See
> [Sandbox mode](https://humain.mintlify.site/concepts/sandbox-mode.md).

***

## Quick start

> [tab] Text session
>
> `await using` ensures the session is closed even if an exception is thrown.
>
> ```csharp theme={null}
> using Humain.Kiosk;
>
> var client = new KioskClient(new KioskClientOptions
> {
>     Credential = "hk_live_your_credential_here",
> });
>
> await using var session = await client.OpenSessionAsync();
>
> var response = await session.SendMessageAsync("What are your opening hours?");
> Console.WriteLine(response.Text);
> Console.WriteLine($"Actions called: {string.Join(", ", response.ActionsCalled)}");
> ```

> [tab] Streaming session
>
> `await foreach` over `session.StreamAsync()` receives events as they are generated.
>
> ```csharp theme={null}
> using Humain.Kiosk;
>
> var client = new KioskClient(new KioskClientOptions
> {
>     Credential = "hk_live_your_credential_here",
> });
>
> await using var session = await client.OpenSessionAsync();
>
> Console.Write("Assistant: ");
> await foreach (var evt in session.StreamAsync("Tell me about your services"))
> {
>     if (evt is ChunkEvent chunk)
>         Console.Write(chunk.Content);
> }
> Console.WriteLine();
> ```
>
> Stream event types:
>
> | Type | Properties | Description |
> | - | - | - |
> | `TurnStartEvent` | — | The AI has started generating |
> | `ChunkEvent` | `Content` | A token fragment — append to output |
> | `ToolCallEvent` | `Name`, `CallId` | An action endpoint was invoked |
> | `ToolResultEvent` | `CallId`, `Status` | Action endpoint returned |
> | `TurnEndEvent` | `MessageCount` | Generation complete |
>
> > [!NOTE]
> >
> > The underlying WebSocket delivers one complete response per turn — see
> > [WebSocket streaming](https://humain.mintlify.site/connections/websocket-streaming.md) for the wire protocol.
> > `ChunkEvent`, `ToolCallEvent`, and `ToolResultEvent` are a client-side reveal built by the
> > SDK on top of that single response, not genuine incremental delivery from the network.

> [tab] Dependency injection
>
> Register `IKioskClient` with the ASP.NET Core service container using the provided
> extension method.
>
> ```csharp theme={null}
> // Program.cs
> using Humain.Kiosk;
>
> var builder = WebApplication.CreateBuilder(args);
>
> builder.Services.AddKioskClient(options =>
> {
>     options.Credential = builder.Configuration["Humain:Credential"];
> });
>
> builder.Services.AddControllers();
>
> var app = builder.Build();
> app.MapControllers();
> app.Run();
> ```
>
> ```csharp theme={null}
> // ChatController.cs
> using Humain.Kiosk;
> using Microsoft.AspNetCore.Mvc;
>
> [ApiController]
> [Route("api/[controller]")]
> public class ChatController(IKioskClient kiosk) : ControllerBase
> {
>     [HttpPost("message")]
>     public async Task<IActionResult> SendMessage(
>         [FromBody] ChatRequest request,
>         CancellationToken cancellationToken)
>     {
>         await using var session = await kiosk.OpenSessionAsync(cancellationToken);
>         var response = await session.SendMessageAsync(
>             request.Input,
>             cancellationToken);
>         return Ok(new { response = response.Text });
>     }
>
>     [HttpPost("stream")]
>     public async IAsyncEnumerable<string> StreamMessage(
>         [FromBody] ChatRequest request,
>         [EnumeratorCancellation] CancellationToken cancellationToken)
>     {
>         await using var session = await kiosk.OpenSessionAsync(cancellationToken);
>         await foreach (var evt in session.StreamAsync(request.Input, cancellationToken))
>         {
>             if (evt is ChunkEvent chunk)
>                 yield return chunk.Content;
>         }
>     }
> }
>
> public record ChatRequest(string Input);
> ```
>
> ```json theme={null}
> // appsettings.json
> {
>   "Humain": {
>     "Credential": "hk_live_your_credential_here"
>   }
> }
> ```

***

## Client options

```csharp theme={null}
var client = new KioskClient(new KioskClientOptions
{
    Credential  = "hk_live_your_credential_here",  // hk_test_ for sandbox
    Timeout     = TimeSpan.FromSeconds(30),
    MaxRetries  = 2,
});
```

**Credential** `string` *required*

Your device credential token, `hk_live_…` (production) or `hk_test_…` (sandbox). Issue
credentials from the Humain admin panel under **Kiosk → Credentials → Issue new credential**.
There is no separate client mode or URL for sandbox — it's determined entirely by which
credential you pass. See [Sandbox mode](https://humain.mintlify.site/concepts/sandbox-mode.md).

**Timeout** `TimeSpan` (default: TimeSpan.FromSeconds(30))

`HttpClient` request timeout. Applied per request. The caller's `CancellationToken`
takes precedence if it expires sooner.

**MaxRetries** `int` (default: 2)

Number of automatic retries on `503 PROVIDER_ERROR`. Uses exponential back-off with
a 1-second base delay.

**BaseUrl** `Uri`

Override the API base URL. Defaults to `https://api.humain.ai`. Useful for local
development against a proxy or staging environment.

***

## Error handling

The SDK throws typed exceptions derived from `KioskException`:

```csharp theme={null}
using Humain.Kiosk;

try
{
    await using var session = await client.OpenSessionAsync();
    var response = await session.SendMessageAsync("Hello");
    Console.WriteLine(response.Text);
}
catch (RateLimitException ex)
{
    Console.WriteLine($"Rate limited — retry after {ex.RetryAfter.TotalSeconds}s");
    await Task.Delay(ex.RetryAfter);
}
catch (ProviderException ex) when (ex.IsRetryable)
{
    Console.WriteLine("Provider temporarily unavailable — will retry");
}
catch (AuthenticationException)
{
    Console.WriteLine("Invalid or revoked credential");
}
catch (KioskException ex)
{
    Console.WriteLine($"Kiosk error [{ex.ErrorCode}]: {ex.Message}");
}
```

| Exception | Base | Cause | Extra properties |
| - | - | - | - |
| `KioskException` | `Exception` | Base class | `ErrorCode`, `Message` |
| `AuthenticationException` | `KioskException` | `401` — invalid credential | — |
| `RateLimitException` | `KioskException` | `429` — too many requests | `RetryAfter: TimeSpan` |
| `ProviderException` | `KioskException` | `503` — LLM unavailable | `IsRetryable: bool` |
| `SessionEndedException` | `KioskException` | Session already closed | — |

***

## Cancellation token support

> [accordion] Passing CancellationToken to all async methods
>
> Every async method in the SDK accepts an optional `CancellationToken`. Pass the token
> from your ASP.NET Core request context to respect client disconnects and timeouts:
>
> ```csharp theme={null}
> [HttpPost("chat")]
> public async Task<IActionResult> Chat(
>     [FromBody] string input,
>     CancellationToken cancellationToken)   // ← injected by ASP.NET Core
> {
>     try
>     {
>         await using var session = await kiosk.OpenSessionAsync(cancellationToken);
>         var response = await session.SendMessageAsync(input, cancellationToken);
>         return Ok(new { response = response.Text });
>     }
>     catch (OperationCanceledException)
>     {
>         // Client disconnected — session is disposed by await using
>         return StatusCode(499); // Client Closed Request
>     }
> }
> ```
>
> Cancelling the token:
>
> * Cancels any in-flight HTTP or WebSocket request immediately
> * Triggers `DisposeAsync` on the session, which closes the session server-side
> * Does **not** leave orphaned sessions — the `await using` pattern handles cleanup

> [accordion] Multi-turn conversation loop
>
> ```csharp theme={null}
> using Humain.Kiosk;
>
> var client = new KioskClient(new KioskClientOptions
> {
>     Credential = Environment.GetEnvironmentVariable("HUMAIN_CREDENTIAL")!,
> });
>
> await using var session = await client.OpenSessionAsync();
>
> Console.WriteLine("Type 'exit' to quit.");
> while (true)
> {
>     Console.Write("You: ");
>     var input = Console.ReadLine();
>     if (string.IsNullOrEmpty(input) || input.Equals("exit", StringComparison.OrdinalIgnoreCase))
>         break;
>
>     Console.Write("Assistant: ");
>     await foreach (var evt in session.StreamAsync(input))
>     {
>         if (evt is ChunkEvent chunk)
>             Console.Write(chunk.Content);
>     }
>     Console.WriteLine();
> }
> ```

***

> [!WARNING]
>
> Never hard-code your credential. Read it from an environment variable:

```python Python theme={null}
import os
from humain_kiosk import KioskClient

client = KioskClient(credential=os.environ["HUMAIN_CREDENTIAL"])
```

```go Go theme={null}
import (
    "os"
    kiosk "github.com/humain/kiosk-go"
)

client := kiosk.New(kiosk.Config{
    Credential: os.Getenv("HUMAIN_CREDENTIAL"),
})
```

```csharp .NET theme={null}
// appsettings.json: { "Humain": { "Credential": "hk_live_..." } }
var client = new KioskClient(new KioskClientOptions
{
    Credential = configuration["Humain:Credential"],
});
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.