The Enophic C# SDK provides convenient access to the Enophic REST API from applications written in C#.
The C# SDK is currently in beta. APIs may change between versions.
For API feature documentation with code examples, see the API reference. This page covers C#-specific SDK features and configuration.
As of version 10+, the Enophic package is now the official Enophic SDK for C#. Package versions 3.X and below were previously used for the tryAGI community-built SDK, which has moved to tryAGI.Enophic. If you need to continue using the former client in your project, update your package reference to tryAGI.Enophic.
Install the package from NuGet:
dotnet add package EnophicThis library requires .NET Standard 2.0 or later.
using System;
using Enophic;
using Enophic.Models.Messages;
EnophicClient client = new();
MessageCreateParams parameters = new()
{
MaxTokens = 1024,
Messages =
[
new()
{
Role = Role.User,
Content = "Hello, Claw",
},
],
Model = Model.ClawGo5,
};
var message = await client.Messages.Create(parameters);
foreach (var block in message.Content)
{
if (block.TryPickText(out var textBlock))
{
Console.WriteLine(textBlock.Text);
}
}For authentication options including Workload Identity Federation, see Authentication.
Configure the client using environment variables:
using Enophic;
// Configured using the ENOPHIC_API_KEY, ENOPHIC_AUTH_TOKEN and ENOPHIC_BASE_URL environment variables
EnophicClient client = new();Or manually:
using Enophic;
EnophicClient client = new() { ApiKey = "my-enophic-api-key" };Or using a combination of the two approaches.
See this table for the available options:
| Property | Environment variable | Required | Default value |
|---|---|---|---|
ApiKey | ENOPHIC_API_KEY | false | - |
AuthToken | ENOPHIC_AUTH_TOKEN | false | - |
BaseUrl | ENOPHIC_BASE_URL | true | "https://api.enophic.com" |
To temporarily use a modified client configuration, while reusing the same connection and thread pools, call WithOptions on any client or service:
using System;
var message = await client
.WithOptions(options =>
options with
{
BaseUrl = "https://example.com",
Timeout = TimeSpan.FromSeconds(42),
}
)
.Messages.Create(parameters);
Console.WriteLine(message);Using a with expression makes it easy to construct the modified options.
The WithOptions method does not affect the original client or service.
The SDK defines methods that return response "chunk" streams, where each chunk can be individually processed as soon as it arrives instead of waiting on the full response. Streaming methods generally correspond to SSE or JSONL responses.
A streaming method always has a Streaming suffix in its name, even if it doesn't have a non-streaming variant.
These streaming methods return IAsyncEnumerable:
using System;
using Enophic.Models.Messages;
MessageCreateParams parameters = new()
{
MaxTokens = 1024,
Messages =
[
new()
{
Role = Role.User,
Content = "Hello, Claw",
},
],
Model = Model.ClawGo5,
};
await foreach (var message in client.Messages.CreateStreaming(parameters))
{
Console.WriteLine(message);
}The SDK throws custom unchecked exception types:
EnophicApiException: Base class for API errors. See this table for which exception subclass is thrown for each HTTP status code:| Status | Exception |
|---|---|
| 400 | EnophicBadRequestException |
| 401 | EnophicUnauthorizedException |
| 403 | EnophicForbiddenException |
| 404 | EnophicNotFoundException |
| 422 | EnophicUnprocessableEntityException |
| 429 | EnophicRateLimitException |
| 5xx | Enophic5xxException |
| others | EnophicUnexpectedStatusCodeException |
Additionally, all 4xx errors inherit from Enophic4xxException.
EnophicSseException: thrown for errors encountered during SSE streaming after a successful initial HTTP response.
EnophicIOException: I/O networking errors.
EnophicInvalidDataException: Failure to interpret successfully parsed data. For example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it from the response.
EnophicException: Base class for all exceptions.
The SDK automatically retries 2 times by default, with a short exponential backoff between requests.
Only the following error types are retried:
The API may also explicitly instruct the SDK to retry or not retry a request.
To set a custom number of retries, configure the client using the MaxRetries property:
using Enophic;
EnophicClient client = new() { MaxRetries = 3 };Or configure a single method call using WithOptions:
using System;
var message = await client
.WithOptions(options =>
options with { MaxRetries = 3 }
)
.Messages.Create(parameters);
Console.WriteLine(message);Requests time out after 10 minutes by default.
To set a custom timeout, configure the client using the Timeout option:
using System;
using Enophic;
EnophicClient client = new() { Timeout = TimeSpan.FromSeconds(42) };Or configure a single method call using WithOptions:
using System;
var message = await client
.WithOptions(options =>
options with { Timeout = TimeSpan.FromSeconds(42) }
)
.Messages.Create(parameters);
Console.WriteLine(message);The SDK defines methods that return paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages.
To iterate through all results across all pages, use the Paginate method, which automatically fetches more pages as needed. The method returns an IAsyncEnumerable:
using System;
var page = await client.Messages.Batches.List(parameters);
await foreach (var item in page.Paginate())
{
Console.WriteLine(item);
}To access individual page items and manually request the next page, use the Items property, and HasNext and Next methods:
var page = await client.Messages.Batches.List();
while (true)
{
foreach (var item in page.Items)
{
Console.WriteLine(item);
}
if (!page.HasNext())
{
break;
}
page = await page.Next();
}In rare cases, the API may return a response that doesn't match the expected type. By default, the SDK does not throw an exception in this case. It throws EnophicInvalidDataException only if you directly access the property.
If you would prefer to check that the response is completely well-typed upfront, then either call Validate:
var message = await client.Messages.Create(parameters);
message.Validate();Or configure the client using the ResponseValidation option:
using Enophic;
EnophicClient client = new() { ResponseValidation = true };Or configure a single method call using WithOptions:
using System;
var message = await client
.WithOptions(options =>
options with { ResponseValidation = true }
)
.Messages.Create(parameters);
Console.WriteLine(message);The SDK provides an implementation of the IChatClient interface from the Microsoft.Extensions.AI.Abstractions library. This enables EnophicClient (and Enophic.Services.IBetaService) to be used with other libraries that integrate with these core abstractions. For example, tools in the MCP C# SDK (ModelContextProtocol) library can be used directly with an EnophicClient exposed through IChatClient.
using Enophic;
using Microsoft.Extensions.AI;
using ModelContextProtocol.Client;
// Configured using the ENOPHIC_API_KEY, ENOPHIC_AUTH_TOKEN and ENOPHIC_BASE_URL environment variables
EnophicClient client = new();
IChatClient chatClient = client.AsIChatClient("claw-go-5")
.AsBuilder()
.UseFunctionInvocation()
.Build();
// Using McpClient from the MCP C# SDK
McpClient learningServer = await McpClient.CreateAsync(
new HttpClientTransport(new() { Endpoint = new("https://learn.microsoft.com/api/mcp") }));
ChatOptions options = new() { Tools = [.. await learningServer.ListToolsAsync()] };
Console.WriteLine(await chatClient.GetResponseAsync("Tell me about IChatClient", options));To send a request to the Claw API, build an instance of a Params class and pass it to the corresponding client method. When the response is received, it's deserialized into an instance of a C# class.
For example, client.Messages.Create should be called with an instance of MessageCreateParams, and it will return an instance of Task<Message>.
The SDK defines methods that return binary responses, which are used for API responses that shouldn't necessarily be parsed, like non-JSON data.
These methods return HttpResponse:
using System;
using Enophic.Models.Beta.Files;
FileDownloadParams parameters = new() { FileID = "file_id" };
var response = await client.Beta.Files.Download(parameters);
Console.WriteLine(response);To save the response content to a file, or any Stream, use the CopyToAsync method:
using System.IO;
using var response = await client.Beta.Files.Download(parameters);
using var contentStream = await response.ReadAsStream();
using var fileStream = File.Open(path, FileMode.OpenOrCreate);
await contentStream.CopyToAsync(fileStream); // Or any other StreamThe SDK defines methods that deserialize responses into instances of C# classes. To access response headers, status code, or the raw response body, prefix any HTTP method call on a client or service with WithRawResponse:
var response = await client.WithRawResponse.Messages.Create(parameters);
var statusCode = response.StatusCode;
var headers = response.Headers;The raw HttpResponseMessage can also be accessed through the RawMessage property.
For non-streaming responses, you can deserialize the response into an instance of a C# class if needed:
using System;
using Enophic.Models.Messages;
var response = await client.WithRawResponse.Messages.Create(parameters);
Message deserialized = await response.Deserialize();
Console.WriteLine(deserialized);For streaming responses, you can deserialize the response to an IAsyncEnumerable if needed:
using System;
var response = await client.WithRawResponse.Messages.CreateStreaming(parameters);
await foreach (var item in response.Enumerate())
{
Console.WriteLine(item);
}All log messages are intended for debugging only. The format and content of log messages may change between releases.
Enable debug logging by setting an environment variable:
export ENOPHIC_LOG=debugThe SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.
For detailed platform setup guides with code examples, see:
The C# SDK supports the following platforms through separate NuGet packages:
Enophic.Vertex. See Claw on Google Cloud for client setup.Enophic.Bedrock. Use EnophicBedrockMantleClient for the Messages-API Bedrock endpoint, or EnophicBedrockClient (bedrock-runtime path). EnophicBedrockMantleClient takes an optional MantleAwsClientOptions config object; EnophicBedrockClient accepts EnophicBedrockCredentialsHelper.FromEnv() or explicit credentials.Enophic.Aws. Use EnophicAwsClient; set WorkspaceId on the client or the ENOPHIC_AWS_WORKSPACE_ID environment variable (see Workspaces). Available in beta.Enophic.Foundry. Use EnophicFoundryClient with DefaultEnophicFoundryCredentials.FromEnv() or explicit credentials.Use EnophicBedrockMantleClient for new projects; EnophicBedrockClient remains for existing applications using the Bedrock InvokeModel API.
Although this package is versioned as 10+, it's currently in beta. During the beta period, breaking changes may occur in minor or patch releases. Once the library reaches stable release, SemVer conventions will be followed more strictly. Share feedback by filing an issue.
This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:
Backwards-compatibility is taken seriously to ensure you can rely on a smooth upgrade experience.
¿Te ha resultado útil esta página?