xAI .NET SDK based on the official gRPC API reference from xAI with integration for Microsoft.Extensions.AI and Microsoft.Agents.AI.
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.
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");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.
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.
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 interpreterLearn more about the code execution tool.
If you maintain a collection, Grok can perform semantic search on it:
var options = new ChatOptions
{
Tools = [new HostedFileSearchTool {
Inputs = [new HostedVectorStoreContent("[collection_id]")]
}]
};Learn more about collection search.
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.
The xAI.Protocol package provides a .NET client for the gRPC API from xAI with full support for all services documented in the official API reference and corresponding proto files.
var builder = Host.CreateApplicationBuilder(args); // or WebApplication.CreateBuilder(args);
builder.Services.AddGrokClient(Environment.GetEnvironmentVariable("XAI_API_KEY")!);
var app = builder.Build();This package leverages the gRPC client factory integration for seamless dependency injection:
class MyService(Chat.ChatClient chat, Documents.DocumentsClient docs, Embedder.EmbedderClient embed)
{
// use clients
}This project contains an automated mechanism to always fetch the latest version of the official .proto files from XAI, ensuring it remains up-to-date with any changes or additions made to the API as soon as they are published.
See for example the introduction of tool output and citations.