Tungo.Sdk 0.3.1

dotnet add package Tungo.Sdk --version 0.3.1
                    
NuGet\Install-Package Tungo.Sdk -Version 0.3.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Tungo.Sdk" Version="0.3.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tungo.Sdk" Version="0.3.1" />
                    
Directory.Packages.props
<PackageReference Include="Tungo.Sdk" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Tungo.Sdk --version 0.3.1
                    
#r "nuget: Tungo.Sdk, 0.3.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Tungo.Sdk@0.3.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Tungo.Sdk&version=0.3.1
                    
Install as a Cake Addin
#tool nuget:?package=Tungo.Sdk&version=0.3.1
                    
Install as a Cake Tool

<div align="center">

<picture> <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo02.svg" /> <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo03.svg" /> <img alt="Tungo AI" src="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo03.svg" width="240" /> </picture>

Tungo SDK for .NET

The official .NET library for the Tungo Platform API

NuGet CI License: MIT

English · Русский · Қазақша

tungo.kz · Quick start · API reference · Changelog · Issues

</div>


The official .NET library for the Tungo Platform API (https://api.tungo.kz): the AI accountant, 1C integration, bank statements, e-invoices, tax forms and automations of Tungo AI.

It is generated from the API's OpenAPI contract, so its methods and models always match the contract it was built from.

Requirements

.NET 8 or later, or any runtime that implements .NET Standard 2.0 (.NET Framework 4.6.2+, Mono, Unity). The net8.0 build has no dependencies and is trimming and native AOT compatible; the netstandard2.0 build depends on System.Text.Json and Microsoft.Bcl.AsyncInterfaces.

Installation

dotnet add package Tungo.Sdk

Quick start

using Tungo.Sdk;

// The API key is read from TUNGO_API_KEY when it is not set here.
using var client = new TungoClient(new TungoClientOptions { CompanyId = "co_123" });

var companies = await client.Companies.ListAsync();
foreach (var company in companies.Data)
{
    Console.WriteLine($"{company.Id}: {company.Name}");
}

var turn = await client.AskAsync("Which taxes are due this month?");
Console.WriteLine(turn.Answer);

Authentication and configuration

Create one client and share it: it is immutable and safe to use from several threads or tasks. Every option can be passed explicitly; five of them fall back to environment variables.

Option Environment variable Default
API key TUNGO_API_KEY none
Base URL TUNGO_BASE_URL https://api.tungo.kz
Webhook secret TUNGO_WEBHOOK_SECRET none
Default company TUNGO_COMPANY_ID none
Default workspace TUNGO_WORKSPACE_ID none
Timeout 60 s (600 s for non-streaming chat turns)
Maximum retries 2
Default headers, HTTP client none, built-in

The API key is sent only to operations that require it; public endpoints and incoming hooks never receive it, and it never appears in error messages or debug output. Calling an authenticated operation without a key fails locally, before any request is made.

Every method also accepts per-request options: timeout, maximum retries, extra headers, an idempotency key and cancellation.

using Tungo.Sdk;

using var client = new TungoClient(new TungoClientOptions
{
    ApiKey = "tg_...",                              // default: TUNGO_API_KEY
    BaseUrl = new Uri("https://api.tungo.kz"),      // default: TUNGO_BASE_URL, then https://api.tungo.kz
    WorkspaceId = "ws_123",                         // default: TUNGO_WORKSPACE_ID
    CompanyId = "co_123",                           // default: TUNGO_COMPANY_ID
    WebhookSecret = "whsec_...",                    // default: TUNGO_WEBHOOK_SECRET
    Timeout = TimeSpan.FromSeconds(60),             // one attempt of an ordinary request
    ChatTimeout = TimeSpan.FromMinutes(10),         // one attempt of a chat turn
    StreamIdleTimeout = TimeSpan.FromMinutes(2),    // silence allowed between stream events
    MaxRetries = 2,
    HttpClient = null,                              // bring your own HttpClient (IHttpClientFactory, proxy, ...)
    HttpMessageHandler = null,                      // ... or only the handler
});

// Per request: every method takes RequestOptions and a CancellationToken.
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var company = await client.Companies.GetAsync(
    new RequestOptions
    {
        CompanyId = "co_456",
        Timeout = TimeSpan.FromSeconds(10),
        MaxRetries = 0,
        Headers = new Dictionary<string, string> { ["X-Trace"] = "abc" },
        OnResponse = response => Console.WriteLine($"{response.StatusCode} {response.RequestId} {response.RateLimit?.Remaining}"),
    },
    cancellation.Token);
Console.WriteLine(company.Name);

TungoClient is thread-safe; create one and reuse it. RequestOptions.OnResponse receives the status, the headers, the request id and the rate-limit headers of the final response of a call.

Bringing your own HttpClient (TungoClientOptions.HttpClient): set httpClient.Timeout = Timeout.InfiniteTimeSpan and AllowAutoRedirect = false on its handler. The SDK enforces its own time limit on every request; a client whose Timeout is shorter than Timeout/ChatTimeout of the options (the default of 100 s is) would cut chat turns, so it is refused with TungoConfigurationException when the TungoClient is created. A redirect that the client follows would carry the API key to another host: the SDK compares the origin that answered with the one it called and raises TungoConfigurationException instead of returning such a response.

Errors

Every failure is a subtype of the SDK's base error. An HTTP error response becomes an API error chosen by the error.type field of the response body, falling back to the HTTP status when the body is not the API's error envelope:

error.type Status
invalid_request_error 400
authentication_error 401
payment_required_error 402
permission_error 403
not_found_error 404
conflict_error 409
gone_error 410
limit_error 429
api_error 500
unavailable_error 503

An API error carries the status, type, code, message, request id, field errors, the parsed retry-after delay, the response headers and the raw body. Problems that happen without a response have their own types: connection error, timeout, decode error (a successful response whose body is not valid), and configuration or validation error (raised before any request).

using Tungo.Sdk;

using var client = new TungoClient();
try
{
    await client.Proposals.ApproveAsync("pr_123", new ApproveRequest());
}
catch (TungoLimitException e)
{
    // 429: e.RetryAfter is the delay the API asked for.
    Console.WriteLine($"Rate limited, retry after {e.RetryAfter}");
}
catch (TungoInvalidRequestException e)
{
    foreach (var field in e.Fields)
    {
        Console.WriteLine($"{field.Path}: {field.Message}");
    }
}
catch (TungoApiException e)
{
    // Any other error status: type and code from the API, the request id for support.
    Console.WriteLine($"{e.StatusCode} {e.Type} {e.Code} {e.RequestId}: {e.ApiMessage}");
}
catch (TungoTimeoutException)
{
    Console.WriteLine("The request timed out.");
}
catch (TungoConnectionException e)
{
    Console.WriteLine($"Network problem: {e.Message}");
}
catch (OperationCanceledException)
{
    // Only when the CancellationToken you passed was cancelled.
    Console.WriteLine("Cancelled by the caller.");
}

All SDK exceptions derive from TungoException. TungoApiException has one subclass per error.type (TungoAuthenticationException, TungoPermissionException, TungoNotFoundException, TungoLimitException, ...). A missing API key or company id raises TungoConfigurationException before any request is sent.

TungoDecodeException means the server accepted and carried out the request (a 2xx status) but its response could not be read: the body is not valid JSON, is cut short, lacks a property the contract requires, or a streaming call was answered with something other than text/event-stream. It is never retried. StatusCode, RequestId and Body (the raw response) tell what the server did; check the effect of a write before sending it again.

Retries and timeouts

A request is retried up to 2 times (3 attempts) on connection errors, timeouts and the statuses 408, 429, 500, 502, 503 and 504, but only when repeating it is safe: GET, HEAD, PUT and DELETE requests, and POST or PATCH requests of the operations whose contract declares an Idempotency-Key. For those the SDK generates a random key and reuses it for every attempt; you can pass your own. Other operations send no key, not even one you pass, because the API would ignore it.

The delay between attempts is min(0.5 s × 2^attempt, 8 s) with random jitter. A positive retry-after-ms or Retry-After response header overrides it; if the server asks for more than 60 s the SDK does not wait and raises the error with the delay filled in.

The timeout covers the whole request including reading the body. Streaming calls have no total timeout, only a connect timeout and an idle timeout of 120 s. Cancellation supplied by the caller is combined with the timeout.

using Tungo.Sdk;

// For the whole client ...
using var client = new TungoClient(new TungoClientOptions
{
    MaxRetries = 5,
    Timeout = TimeSpan.FromSeconds(20),
});

// ... or for one call. A POST is retried only when it carries an idempotency key;
// the SDK generates one for the operations that accept it, or you can set your own.
var job = await client.Batches.CreateEsfPurchasesAsync(
    new EsfPurchasesJobRequest(),
    new RequestOptions { MaxRetries = 0, Timeout = TimeSpan.FromSeconds(5), IdempotencyKey = "import-2025-01" });
Console.WriteLine(job.Id);

Pagination

List operations use cursor pagination ({ data, next_cursor }). The plain method returns one typed page that knows whether there is a next page and can fetch it. The auto-paging variant is a lazy iterator: it requests the next page only when needed, carries your filters over, and stops fetching as soon as you stop iterating.

using Tungo.Sdk;

using var client = new TungoClient();

// One page at a time.
var page = await client.Proposals.ListAsync(new ProposalsListParams { Limit = 50 });
foreach (var proposal in page.Data)
{
    Console.WriteLine(proposal.Title);
}

if (page.HasNextPage)
{
    page = await page.GetNextPageAsync();
}

// Or every item of every page; pages are fetched as the loop needs them.
await foreach (var proposal in client.Proposals.ListAllAsync(new ProposalsListParams { Limit = 50 }))
{
    Console.WriteLine($"{proposal.Id} {TungoMoney.FormatTiyn(proposal.Total.AmountTiyn)}");
}

Streaming

Streaming operations use server-sent events and deliver typed events as they arrive. Leaving the loop early or closing the stream closes the connection. A stream request is retried only before its first byte; an error response is raised as the same typed API error as for ordinary calls. A chat stream that ends before its final event is reported as an error, never as a finished answer.

using Tungo.Sdk;

using var client = new TungoClient();

// Events arrive as the model produces them; leaving the loop closes the connection.
await using var stream = client.Chat.CreateStreamAsync(new ChatMessageRequest { Message = "Summarise January" });
await foreach (var chatEvent in stream)
{
    switch (chatEvent.Value)
    {
        case ChatEventText text:
            Console.Write(text.Delta);
            break;
        case ChatEventError error:
            Console.WriteLine($"error: {error.Error.Message}");
            break;
        case ChatEventDone done:
            Console.WriteLine($"\nstop reason: {done.StopReason}");
            break;
    }
}

// Or let the SDK assemble the turn (an error event is thrown as a TungoApiException).
var turn = await client.Chat.CreateStreamAsync(new ChatMessageRequest { Message = "And February?" }).ToChatTurnAsync();
Console.WriteLine($"{turn.DialogId}: {turn.Text}");

Chat.ListEventsAsync, Feed.ListEventsAsync and Batches.ListEventsAsync return the same TungoStream<T>. TungoStream<T>.GetResponseAsync() gives the response headers (for example X-Dialog-Id) before the first event, and TungoStream<T>.LastEventId the id of the last server-sent event read so far. ToChatTurnAsync() raises TungoDecodeException when the stream ends without its final done event, so a cut connection never looks like a finished answer; the plain await foreach simply ends. A successful response that is not text/event-stream is a TungoDecodeException. The exception is a finished chat turn that the API replays for a repeated Idempotency-Key (application/json with Idempotent-Replayed: true): its stored result arrives as the events of that turn, ending with next (follow-ups and the next action, when it has them) and done.

Webhooks

Outgoing webhooks are signed according to the Standard Webhooks specification (Svix). The verify helper takes the raw request body and the headers (webhook-* or svix-*), checks the HMAC-SHA256 signature in constant time and the timestamp within 300 s of the system clock, and returns the typed event. Any problem is reported as a webhook verification error. If no secret is passed, the client's webhook secret is used.

The send-hook helper posts an event to an incoming hook (/hooks/{token}) and, when given a secret, signs the exact bytes it sends in the X-Signature: sha256=<hex> header. The API key is never sent to hooks.

using Tungo.Sdk;

using var client = new TungoClient(new TungoClientOptions { WebhookSecret = "whsec_..." });

// In your HTTP handler: pass the raw body and the request headers
// (ASP.NET Core: Request.Headers works as it is).
string body = "{...}";
var headers = new Dictionary<string, string>
{
    ["webhook-id"] = "msg_1",
    ["webhook-timestamp"] = "1700000000",
    ["webhook-signature"] = "v1,...",
};
try
{
    var webhookEvent = client.VerifyWebhook(body, headers);
    if (webhookEvent.Value is WebhookEventProposalWritten written)
    {
        Console.WriteLine($"proposal written: {written.Id}");
    }
}
catch (TungoWebhookVerificationException e)
{
    Console.WriteLine($"rejected: {e.Reason}"); // answer 400
}

// Sending an event to an incoming hook: the body is signed with the hook's secret;
// the API key is never sent to hook URLs.
var accepted = await client.SendHookAsync("th_...", "{\"invoice\":\"A-1\"}", secret: "hook-secret");
Console.WriteLine(accepted.EventId);

TungoWebhooks.Verify is the static form; it accepts IEnumerable<KeyValuePair<string, string>>, multi-valued header collections (ASP.NET Core IHeaderDictionary) and HttpHeaders, without a dependency on ASP.NET Core. Signatures are compared in constant time. A hook created with its own signature_header takes the signature in that header: pass signatureHeader: "x-my-signature" to SendHookAsync (or SignatureHeader in AutomationsPostHookParams).

Money

The API expresses amounts in tiyn (1/100 of a tenge) as 64-bit integers. The money helper converts decimal strings and exact decimal values to tiyn without floating-point error, rounding half away from zero ("1.005" → 101), and formats tiyn for display (4500000 → 45 000,00 ₸). Invalid input raises a typed error.

using Tungo.Sdk;

long tiyn = TungoMoney.ToTiyn("1234.56");          // 123456, exact
long fromDecimal = TungoMoney.ToTiyn(1234.56m);    // 123456
decimal tenge = TungoMoney.ToTenge(tiyn);          // 1234.56
string text = TungoMoney.FormatTiyn(4_500_000);    // "45 000,00 ₸"
bool valid = TungoMoney.IsValidBinIin("123456789012");
Console.WriteLine($"{tiyn} {fromDecimal} {tenge} {text} {valid}");

Amounts in models are long tiyn. ToTiyn(double) exists for convenience and goes through the shortest round-trip decimal form of the value.

Models

Every schema of the contract is a sealed record with init properties; properties the contract requires are C# required members. A response body that lacks a required property or holds a value of the wrong type fails with TungoDecodeException. Stream events, webhook events and error details are read tolerantly: there a required property the server did not send is left at its default value (null for a reference type) instead of ending the stream. Unknown JSON properties are kept in AdditionalProperties. Enumerations are string-backed structs: a value this SDK version does not know is preserved (IsKnown is false) instead of failing. Unions expose Value for pattern matching and keep an unknown variant as raw JSON (IsUnknown, Json).

A PATCH body can tell "leave unchanged" from "set to null":

using Tungo.Sdk;

using var client = new TungoClient();

// Optional<T> tells "leave unchanged" (not set) from "clear" (explicit null).
var endpoint = await client.Webhooks.UpdateEndpointAsync("ep_123", new WebhookEndpointPatch
{
    Description = "Orders",                               // change
    EventTypes = null,                                    // send "event_types": null
    // Channels is not set: the property is not sent at all
});
Console.WriteLine(endpoint.Id);

Waiting for long operations

using Tungo.Sdk;

using var client = new TungoClient();

var run = await client.RunScenarioAndWaitAsync(
    "sc_123",
    wait: new TungoWaitOptions { Timeout = TimeSpan.FromMinutes(5) });
Console.WriteLine(run.State.IsKnown ? run.State.Value : $"new state: {run.State.Value}");

var batch = await client.WaitForBatchAsync("bt_123");
Console.WriteLine(batch.Running);

The helpers poll with a growing interval and raise TungoTimeoutException when TungoWaitOptions.Timeout passes.

API reference

Generated from the Tungo Platform API contract: 13 resources, 90 methods, 22 webhook event types.

Resource Description Methods
client.Workspaces Organisations (workspaces) the API key can access ListAsync
client.Companies Companies of an organisation and their profiles ListAsync · GetAsync
client.Platform Platform balance, ledger, usage reports, limits, audit log and model rates ListUsageRatesAsync · GetAccountAsync · GetAuditAsync / GetAuditAllAsync · GetLedgerAsync / GetLedgerAllAsync · ListLimitsAsync · ListRequestsAsync / ListRequestsAllAsync · GetUsageAsync
client.ApiKeys The current API key and its usage statistics GetCurrentAsync · GetCurrentUsageAsync · GetUsageAsync
client.Webhooks Outgoing webhooks of an organisation (Svix): endpoints, event catalogue, deliveries and signature check ListEndpointsAsync / ListEndpointsAllAsync · CreateEndpointAsync · GetEndpointAsync · UpdateEndpointAsync · DeleteEndpointAsync · ListEndpointAttemptsAsync / ListEndpointAttemptsAllAsync · RotateEndpointSecretAsync · TestEndpointAsync · ListEventTypesAsync · ListMessagesAsync / ListMessagesAllAsync · ListMessageAttemptsAsync / ListMessageAttemptsAllAsync · ResendMessageAsync · GetUsageAsync
client.Chat Conversations with the AI accountant: questions, streaming chat (SSE), token counting and history ListAsync / ListAllAsync · CreateAsync / CreateStreamAsync · CountTokensAsync · ListMentionsAsync · GetRatingOptionsAsync · ListSuggestionsAsync · GetAsync · UpdateAsync · DeleteAsync · AnswerAsync / AnswerStreamAsync · ListEventsAsync · RateMessageAsync · DeleteMessageRatingAsync · RateAsync · DismissRatingAsync · StopAsync
client.Proposals Documents proposed by the AI accountant: review, approval for posting to 1C, and rejection ListAsync / ListAllAsync · ApproveBatchAsync · GetAsync · ApproveAsync · RejectAsync · RequestApprovalAsync
client.Feed The company's feed of events and proposals (pages and a live SSE stream) GetAsync / GetAllAsync · ListEventsAsync
client.Batches Processing batches for bank statements, incoming e-invoices and DirectBank ListAsync / ListAllAsync · CreateBankStatementAsync · CreateEsfPurchasesAsync · GetAsync · ListEventsAsync · StopAsync · GetSummaryAsync · ListStatementsAsync / ListStatementsAllAsync · PollDirectbankAsync
client.Esf Incoming and outgoing electronic invoices (the ESF system) GetIncomingAsync / GetIncomingAllAsync · GetOutgoingAsync / GetOutgoingAllAsync
client.Forms Tax forms (FNO 100.00 and others): building, ISNA checks and data gaps ListAsync · BuildAsync · ListDataGapsAsync · GetIsnaAsync · ListNotesAsync
client.Onec Status of the company's connection to its 1C database GetStatusAsync
client.Automations Company automations: incoming hooks, scenarios, step chains, runs and the AI autonomy level PostHookAsync · ListHooksAsync · CreateHookAsync · GetHookAsync · UpdateHookAsync · DeleteHookAsync · RotateHookAsync · TestHookAsync · ListRunsAsync / ListRunsAllAsync · GetRunAsync · CancelRunAsync · RetryRunAsync · ListScenariosAsync · CreateScenarioAsync · GetScenarioAsync · PutScenarioAsync · UpdateScenarioAsync · DeleteScenarioAsync · RunScenarioAsync · GetStateAsync · PutStateAsync · GetAutonomyAsync · PutAutonomyAsync

Other SDKs

The same API is available in ten languages. All SDKs are generated from one contract and behave the same way.

Language Repository Package
TypeScript tungo-sdk-typescript @tungoai/sdk
Python tungo-sdk-python tungoai
Go tungo-sdk-go github.com/TungoAI/tungo-sdk-go
Rust tungo-sdk-rust tungo-sdk
PHP tungo-sdk-php tungo/sdk
Java tungo-sdk-java kz.tungo:tungo-sdk
Kotlin tungo-sdk-kotlin kz.tungo:tungo-sdk-kotlin
Swift tungo-sdk-swift TungoSDK
Ruby tungo-sdk-ruby tungo-sdk
.NET tungo-sdk-dotnet Tungo.Sdk

Versioning and support

This library follows Semantic Versioning. While the major version is 0, a minor release may contain breaking changes; they are always listed in the changelog. This README describes version 0.3.1.

The code is generated: please report problems and ideas in the issue tracker rather than opening pull requests against generated files. To report a vulnerability, follow the security policy.

License

MIT

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.3.1 79 11/13/2026
0.2.0 84 11/11/2026