tryAGI.Xai 0.0.0-dev.14

Prefix Reserved
This is a prerelease version of tryAGI.Xai.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package tryAGI.Xai --version 0.0.0-dev.14
                    
NuGet\Install-Package tryAGI.Xai -Version 0.0.0-dev.14
                    
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="tryAGI.Xai" Version="0.0.0-dev.14" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="tryAGI.Xai" Version="0.0.0-dev.14" />
                    
Directory.Packages.props
<PackageReference Include="tryAGI.Xai" />
                    
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 tryAGI.Xai --version 0.0.0-dev.14
                    
#r "nuget: tryAGI.Xai, 0.0.0-dev.14"
                    
#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 tryAGI.Xai@0.0.0-dev.14
                    
#: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=tryAGI.Xai&version=0.0.0-dev.14&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=tryAGI.Xai&version=0.0.0-dev.14&prerelease
                    
Install as a Cake Tool

Xai

Nuget package dotnet License: MIT Discord

Disclaimer: This package is not affiliated with, endorsed by, or sponsored by xAI. xAI and Grok are trademarks of xAI Corp.

Features 🔥

  • Fully generated C# SDK based on a hand-curated xAI OpenAPI specification using AutoSDK
  • Same day update to support new features
  • All modern .NET features - nullability, trimming, NativeAOT, etc.
  • Comprehensive API coverage:
    • Chat completions (streaming, tool calling, reasoning, structured output, deferred)
    • Vision (image input with Grok Vision models)
    • Image generation & editing (Grok Imagine)
    • Video generation with polling helper
    • Text-to-speech (multiple voices)
    • Realtime voice WebSocket client (bidirectional audio/text, VAD, tools)
    • Embeddings, Batches, Files, Collections

Usage

using Xai;

using var client = new XaiClient(apiKey);

Chat Completion

var response = await client.Chat.CreateChatCompletionAsync(
    model: "grok-3-mini",
    messages: [
        new ChatCompletionMessage
        {
            Role = ChatCompletionMessageRole.User,
            Content = "What is the meaning of life?",
        },
    ]);

Console.WriteLine(response.Choices![0].Message?.Content);

Streaming

await foreach (var chunk in client.Chat.CreateChatCompletionAsStreamAsync(
    model: "grok-3-mini",
    messages: [
        new ChatCompletionMessage
        {
            Role = ChatCompletionMessageRole.User,
            Content = "Tell me a short story.",
        },
    ]))
{
    Console.Write(chunk.Choices?[0].Delta?.Content);
}

Tool Calling

using System.Text.Json;

var tools = new List<ChatCompletionTool>
{
    new ChatCompletionTool
    {
        Type = ChatCompletionToolType.Function,
        Function = new FunctionDefinition
        {
            Name = "get_weather",
            Description = "Get the current weather for a location.",
            Parameters = JsonSerializer.Deserialize<JsonElement>("""
                {
                    "type": "object",
                    "properties": {
                        "location": { "type": "string", "description": "The city name." }
                    },
                    "required": ["location"]
                }
                """),
        },
    },
};

var response = await client.Chat.CreateChatCompletionAsync(
    model: "grok-3-mini",
    messages: [
        new ChatCompletionMessage
        {
            Role = ChatCompletionMessageRole.User,
            Content = "What is the weather in San Francisco?",
        },
    ],
    tools: tools,
    toolChoice: new OneOf<CreateChatCompletionRequestToolChoice?, ChatCompletionNamedToolChoice>(
        CreateChatCompletionRequestToolChoice.Auto));

var toolCall = response.Choices![0].Message!.ToolCalls![0];
Console.WriteLine($"{toolCall.Function.Name}({toolCall.Function.Arguments})");

Reasoning

var response = await client.Chat.CreateChatCompletionAsync(
    model: "grok-3-mini",
    messages: [
        new ChatCompletionMessage
        {
            Role = ChatCompletionMessageRole.User,
            Content = "What is 15 * 37? Think step by step.",
        },
    ],
    reasoningEffort: CreateChatCompletionRequestReasoningEffort.High);

Console.WriteLine(response.Choices![0].Message?.ReasoningContent); // reasoning trace
Console.WriteLine(response.Choices![0].Message?.Content);          // final answer

Structured Output (JSON Schema)

var response = await client.Chat.CreateChatCompletionAsync(
    model: "grok-3-mini",
    messages: [
        new ChatCompletionMessage
        {
            Role = ChatCompletionMessageRole.User,
            Content = "Extract the capital of France.",
        },
    ],
    responseFormat: new ResponseFormat
    {
        Type = ResponseFormatType.JsonSchema,
        JsonSchema = new ResponseFormatJsonSchema
        {
            Name = "capital_response",
            Strict = true,
            Schema = new
            {
                type = "object",
                properties = new
                {
                    country = new { type = "string" },
                    capital = new { type = "string" },
                },
                required = new[] { "country", "capital" },
                additionalProperties = false,
            },
        },
    });

Console.WriteLine(response.Choices![0].Message?.Content);
// {"country":"France","capital":"Paris"}

Vision (Image Input)

var response = await client.Chat.CreateChatCompletionAsync(
    model: "grok-2-vision",
    messages: [
        new ChatCompletionMessage
        {
            Role = ChatCompletionMessageRole.User,
            Content = new OneOf<string, IList<ChatCompletionContentPart>>(
                new List<ChatCompletionContentPart>
                {
                    new ChatCompletionContentPart
                    {
                        Type = ChatCompletionContentPartType.Text,
                        Text = "Describe this image in one sentence.",
                    },
                    new ChatCompletionContentPart
                    {
                        Type = ChatCompletionContentPartType.ImageUrl,
                        ImageUrl = new ChatCompletionContentPartImageUrl
                        {
                            Url = "https://example.com/image.png",
                        },
                    },
                }),
        },
    ]);

Console.WriteLine(response.Choices![0].Message?.Content);

Image Generation

var response = await client.Images.CreateImageAsync(
    model: "grok-imagine-image",
    prompt: "A futuristic cityscape at sunset");

Console.WriteLine(response.Data![0].Url);

Image Editing

var response = await client.Images.CreateImageEditAsync(
    model: "grok-2-image",
    prompt: "Add a red hat to the person in the image",
    image: new ImageInput
    {
        Url = "https://example.com/photo.png",
    });

Console.WriteLine(response.Data![0].Url);

Video Generation

var status = await client.GenerateAndWaitAsync(
    new CreateVideoRequest
    {
        Model = "grok-imagine-video",
        Prompt = "A gentle ocean wave rolling onto a sandy beach at sunset",
        Duration = 3,
        Resolution = CreateVideoRequestResolution.x480p,
    },
    pollingInterval: TimeSpan.FromSeconds(10),
    timeout: TimeSpan.FromMinutes(5));

Console.WriteLine(status.Video?.Url);

Text-to-Speech

byte[] audioBytes = await client.Audio.CreateSpeechAsync(
    model: "tts-1",
    input: "Hello from xAI!",
    voice: CreateSpeechRequestVoice.Eve);

File.WriteAllBytes("output.mp3", audioBytes);

Realtime Voice

using var voiceClient = new RealtimeVoiceClient(apiKey);
await voiceClient.ConnectAsync();

// Configure session
await voiceClient.SendEventAsync(RealtimeClientEvent.SessionUpdate(new RealtimeSessionConfig
{
    Voice = "Eve",
    Instructions = "You are a helpful assistant.",
    Modalities = ["text", "audio"],
    TurnDetection = new RealtimeTurnDetection
    {
        Type = "server_vad",
        Threshold = 0.85,
        SilenceDurationMs = 500,
    },
}));

// Send a text message and request response
await voiceClient.SendEventAsync(RealtimeClientEvent.UserMessage("Say hello!"));
await voiceClient.SendEventAsync(RealtimeClientEvent.CreateResponse(["text"]));

// Receive events
await foreach (var serverEvent in voiceClient.ReceiveUpdatesAsync(cancellationToken))
{
    if (serverEvent.IsAudioTranscriptDelta)
        Console.Write(serverEvent.Delta);
    else if (serverEvent.IsResponseDone)
        break;
}

Deferred Completions

// Submit a deferred request (processed asynchronously)
var response = await client.Chat.CreateChatCompletionAsync(
    model: "grok-3-mini",
    messages: [
        new ChatCompletionMessage
        {
            Role = ChatCompletionMessageRole.User,
            Content = "Explain what a quasar is in two sentences.",
        },
    ],
    deferred: true);

// Poll for the result
var result = await client.Chat.GetDeferredCompletionAsync(response.Id!);
Console.WriteLine(result.Choices![0].Message?.Content);

// Or use the convenience helper that submits + polls automatically:
var completed = await client.CreateDeferredAndWaitAsync(
    new CreateChatCompletionRequest
    {
        Model = "grok-3-mini",
        Messages = [
            new ChatCompletionMessage
            {
                Role = ChatCompletionMessageRole.User,
                Content = "Write a haiku about programming.",
            },
        ],
    },
    pollingInterval: TimeSpan.FromSeconds(5),
    timeout: TimeSpan.FromMinutes(2));

Console.WriteLine(completed.Choices![0].Message?.Content);

Microsoft.Extensions.AI

This SDK covers xAI-specific endpoints (images, video, realtime, etc.). For standard IChatClient/IEmbeddingGenerator support, use CustomProviders.XAi() from the tryAGI.OpenAI package:

using tryAGI.OpenAI;
using Microsoft.Extensions.AI;

using var api = CustomProviders.XAi("API_KEY");
IChatClient chatClient = api;

var response = await chatClient.GetResponseAsync("Hello from Grok!");
Console.WriteLine(response.Text);

Support

Priority place for bugs: https://github.com/tryAGI/Xai/issues Priority place for ideas and general questions: https://github.com/tryAGI/Xai/discussions Discord: https://discord.gg/Ca2xhfBf3v

Acknowledgments

JetBrains logo

This project is supported by JetBrains through the Open Source Support Program.

CodeRabbit logo

This project is supported by CodeRabbit through the Open Source Support Program.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.

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.0.0-dev.58 24 5/4/2026
0.0.0-dev.57 34 5/3/2026
0.0.0-dev.44 59 4/1/2026
0.0.0-dev.43 51 3/29/2026
0.0.0-dev.40 146 3/28/2026
0.0.0-dev.37 51 3/28/2026
0.0.0-dev.36 50 3/28/2026
0.0.0-dev.34 57 3/27/2026
0.0.0-dev.25 47 3/20/2026
0.0.0-dev.23 50 3/20/2026
0.0.0-dev.22 43 3/20/2026
0.0.0-dev.21 45 3/19/2026
0.0.0-dev.20 46 3/19/2026
0.0.0-dev.19 52 3/19/2026
0.0.0-dev.18 51 3/19/2026
0.0.0-dev.17 44 3/19/2026
0.0.0-dev.16 47 3/19/2026
0.0.0-dev.15 46 3/19/2026
0.0.0-dev.14 45 3/19/2026
0.0.0-dev.13 49 3/19/2026
Loading failed