xAI 1.0.2
dotnet add package xAI --version 1.0.2
NuGet\Install-Package xAI -Version 1.0.2
<PackageReference Include="xAI" Version="1.0.2" />
<PackageVersion Include="xAI" Version="1.0.2" />
<PackageReference Include="xAI" />
paket add xAI --version 1.0.2
#r "nuget: xAI, 1.0.2"
#:package xAI@1.0.2
#addin nuget:?package=xAI&version=1.0.2
#tool nuget:?package=xAI&version=1.0.2
xAI/Grok integration for Microsoft.Extensions.AI IChatClient with full support for all
agentic tools:
var grok = new GrokClient(Environment.GetEnvironmentVariable("XAI_API_KEY")!)
.AsIChatClient("grok-4.1-fast");
Web Search
var messages = new Chat()
{
{ "system", "You are an AI assistant that knows how to search the web." },
{ "user", "What's Tesla stock worth today? Search X and the news for latest info." },
};
var grok = new GrokClient(Environment.GetEnvironmentVariable("XAI_API_KEY")!).AsIChatClient("grok-4.1-fast");
var options = new ChatOptions
{
Tools = [new HostedWebSearchTool()] // 👈 compatible with OpenAI
};
var response = await grok.GetResponseAsync(messages, options);
In addition to basic web search as shown above, Grok supports more advanced search scenarios, which can be opted-in by using Grok-specific types:
var grok = new GrokChatClient(Environment.GetEnvironmentVariable("XAI_API_KEY")!)
.AsIChatClient("grok-4.1-fast");
var response = await grok.GetResponseAsync(
"What are the latest product news by Tesla?",
new ChatOptions
{
Tools = [new GrokSearchTool()
{
AllowedDomains = [ "ir.tesla.com" ]
}]
});
You can alternatively set ExcludedDomains instead, and enable image
understanding with EnableImageUndestanding. Learn more about these filters
at web search parameters.
X Search
In addition to web search, Grok also supports searching on X (formerly Twitter):
var response = await grok.GetResponseAsync(
"What's the latest on Optimus?",
new ChatOptions
{
Tools = [new GrokXSearchTool
{
// AllowedHandles = [...],
// ExcludedHandles = [...],
// EnableImageUnderstanding = true,
// EnableVideoUnderstanding = true,
// FromDate = ...,
// ToDate = ...,
}]
});
Learn more about available filters at X search parameters.
You can combine both web and X search in the same request by adding both tools.
Code Execution
The code execution tool enables Grok to write and execute Python code in real-time, dramatically expanding its capabilities beyond text generation. This powerful feature allows Grok to perform precise calculations, complex data analysis, statistical computations, and solve mathematical problems that would be impossible through text alone.
This is Grok's equivalent of the OpenAI code interpreter, and is configured the same way:
var grok = new GrokClient(Configuration["XAI_API_KEY"]!).AsIChatClient("grok-4-fast");
var response = await grok.GetResponseAsync(
"Calculate the compound interest for $10,000 at 5% annually for 10 years",
new ChatOptions
{
Tools = [new HostedCodeInterpreterTool()]
});
var text = response.Text;
Assert.Contains("$6,288.95", text);
If you want to access the output from the code execution, you can add that as an include in the options:
var grok = new GrokClient(Configuration["XAI_API_KEY"]!).AsIChatClient("grok-4-fast");
var options = new GrokChatOptions
{
Include = { IncludeOption.CodeExecutionCallOutput },
Tools = [new HostedCodeInterpreterTool()]
};
var response = await grok.GetResponseAsync(
"Calculate the compound interest for $10,000 at 5% annually for 10 years",
options);
var content = response.Messages
.SelectMany(x => x.Contents)
.OfType<CodeInterpreterToolResultContent>()
.First();
foreach (AIContent output in content.Outputs)
// process outputs from code interpreter
Learn more about the code execution tool.
Collection Search
If you maintain a collection, Grok can perform semantic search on it:
var options = new ChatOptions
{
Tools = [new HostedFileSearchTool {
Inputs = [new HostedVectorStoreContent("[collection_id]")]
}]
};
To receive the actual search results and file references, include CollectionsSearchCallOutput in the options:
var options = new GrokChatOptions
{
Include = [IncludeOption.CollectionsSearchCallOutput],
Tools = [new HostedFileSearchTool {
Inputs = [new HostedVectorStoreContent("[collection_id]")]
}]
};
var response = await grok.GetResponseAsync(messages, options);
// Access the search results with file references
var results = response.Messages
.SelectMany(x => x.Contents)
.OfType<CollectionSearchToolResultContent>();
foreach (var result in results)
{
// Each result contains files that were found and referenced
var files = result.Outputs?.OfType<HostedFileContent>();
foreach (var file in files ?? [])
{
Console.WriteLine($"File: {file.Name} (ID: {file.FileId})");
// Files include citation annotations with snippets
foreach (var citation in file.Annotations?.OfType<CitationAnnotation>() ?? [])
{
Console.WriteLine($" Title: {citation.Title}");
Console.WriteLine($" Snippet: {citation.Snippet}");
Console.WriteLine($" URL: {citation.Url}"); // collections://[collection_id]/files/[file_id]
}
}
}
Citations from collection search include:
- Title: Extracted from the first line of the chunk content (if available), typically the file name or heading
- Snippet: The relevant text excerpt from the document
- FileId: Identifier of the source file in the collection
- Url: A
collections://URI pointing to the specific file within the collection - ToolName: Always set to
"collections_search"
Learn more about collection search.
Remote MCP
Remote MCP Tools allow Grok to connect to external MCP (Model Context Protocol) servers. This example sets up the GitHub MCP server so queries about releases (limited specifically in this case):
var options = new ChatOptions
{
Tools = [new HostedMcpServerTool("GitHub", "https://api.githubcopilot.com/mcp/") {
AuthorizationToken = Configuration["GITHUB_TOKEN"]!,
AllowedTools = ["list_releases"],
}]
};
Just like with code execution, you can opt-in to surfacing the MCP outputs in the response:
var options = new GrokChatOptions
{
// Exposes McpServerToolResultContent in responses
Include = { IncludeOption.McpCallOutput },
Tools = [new HostedMcpServerTool("GitHub", "https://api.githubcopilot.com/mcp/") {
AuthorizationToken = Configuration["GITHUB_TOKEN"]!,
AllowedTools = ["list_releases"],
}]
};
Learn more about Remote MCP tools.
Image Generation
Grok also supports image generation using the IImageGenerator abstraction from
Microsoft.Extensions.AI. Use the AsIImageGenerator extension method to get an
image generator client:
var imageGenerator = new GrokClient(Environment.GetEnvironmentVariable("XAI_API_KEY")!)
.AsIImageGenerator("grok-imagine-image-beta");
var request = new ImageGenerationRequest("A cat sitting on a tree branch");
var options = new ImageGenerationOptions
{
ResponseFormat = ImageGenerationResponseFormat.Uri,
Count = 1
};
var response = await imageGenerator.GenerateAsync(request, options);
var image = (UriContent)response.Contents.First();
Console.WriteLine($"Generated image URL: {image.Uri}");
Editing Images
You can also edit previously generated images by passing them as input to a new generation request:
var imageGenerator = new GrokClient(Environment.GetEnvironmentVariable("XAI_API_KEY")!)
.AsIImageGenerator("grok-imagine-image-beta");
// First, generate the original image
var request = new ImageGenerationRequest("A cat sitting on a tree branch");
var options = new ImageGenerationOptions
{
ResponseFormat = ImageGenerationResponseFormat.Uri,
Count = 1
};
var response = await imageGenerator.GenerateAsync(request, options);
var image = (UriContent)response.Contents.First();
// Now edit the image by providing it as input along with the edit instructions
var edit = await imageGenerator.GenerateAsync(
new ImageGenerationRequest("Edit provided image by adding a batman mask", [image]),
options);
var editedImage = (UriContent)edit.Contents.First();
Console.WriteLine($"Edited image URL: {editedImage.Uri}");
Open Source Maintenance Fee
To ensure the long-term sustainability of this project, users of this package who generate revenue must pay an Open Source Maintenance Fee. While the source code is freely available under the terms of the License, this package and other aspects of the project require adherence to the Maintenance Fee.
To pay the Maintenance Fee, become a Sponsor at the proper OSMF tier. A single fee covers all of Devlooped packages.
Sponsors
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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 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. |
-
net10.0
- Google.Protobuf (>= 3.33.2)
- Grpc.Net.Client (>= 2.76.0)
- Microsoft.Extensions.AI.Abstractions (>= 10.1.1)
- System.ClientModel (>= 1.8.1)
- xAI.Protocol (>= 1.0.2)
-
net8.0
- Google.Protobuf (>= 3.33.2)
- Grpc.Net.Client (>= 2.76.0)
- Microsoft.Extensions.AI.Abstractions (>= 10.1.1)
- System.ClientModel (>= 1.8.1)
- xAI.Protocol (>= 1.0.2)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on xAI:
| Package | Downloads |
|---|---|
|
grok
Sample Grok CLI using xAI and xAI.Protocol packages |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.2 | 39 | 1/9/2026 |
| 1.0.1 | 70 | 1/6/2026 |
| 1.0.0 | 77 | 1/5/2026 |
| 1.0.0-preview.1 | 40 | 1/2/2026 |