DEVSAIO

Call AI models from C# / .NET

Use HttpClient and System.Net.Http.Json to talk to any DEVSAIO model from .NET.

DEVSAIO team · 1 min read
Share on X
csharp
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json.Serialization;

var http = new HttpClient { BaseAddress = new Uri("https://devsaio.lol/v1/"), Timeout = TimeSpan.FromSeconds(120) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("DEVSAIO_API_KEY"));

var req = new ChatRequest("claude-sonnet-4-6", new[] { new Msg("user", "Explain async/await in C# simply.") }, 800);
var res = await http.PostAsJsonAsync("chat/completions", req);
var body = await res.Content.ReadFromJsonAsync<ChatResponse>();

if (!res.IsSuccessStatusCode) throw new Exception(body?.Error?.Message ?? $"AI error {(int)res.StatusCode}");
Console.WriteLine(body!.Choices[0].Message.Content);

record Msg(string Role, string Content)
{
    [JsonPropertyName("role")] public string Role { get; init; } = Role;
    [JsonPropertyName("content")] public string Content { get; init; } = Content;
}
record ChatRequest(
    [property: JsonPropertyName("model")] string Model,
    [property: JsonPropertyName("messages")] Msg[] Messages,
    [property: JsonPropertyName("max_tokens")] int MaxTokens);
record Choice([property: JsonPropertyName("message")] Msg Message);
record ApiError([property: JsonPropertyName("message")] string Message);
record ChatResponse(
    [property: JsonPropertyName("choices")] Choice[] Choices,
    [property: JsonPropertyName("error")] ApiError? Error);

Tips

  • In ASP.NET Core, register the client with IHttpClientFactory instead of creating it per request.
  • The official OpenAI .NET library also lets you set a custom endpoint through its client options if you'd rather use an SDK.
Try it with one API key

Claude, GPT, Gemini, DeepSeek, image and video models through one OpenAI- and Anthropic-compatible endpoint. Prepaid, pay only for what you use.

Keep reading