Class XAIService
public class XAIService : OpenAICompatibleService, IAIService, IAIRunService, IAIRequestFeatureService, IFunctionRegisterable, IAIProcessingInfoService, IImageGenerationService
- Inheritance
-
XAIService
- Implements
- Inherited Members
- Extension Methods
Constructors
XAIService(string, HttpClient)
public XAIService(string apiKey, HttpClient httpClient)
Parameters
apiKeystringhttpClientHttpClient
XAIService(string, string, HttpClient)
Creates a XAIService with a specific model.
public XAIService(string apiKey, string model, HttpClient httpClient)
Parameters
apiKeystringmodelstringhttpClientHttpClient
Properties
DefaultImageModel
The image model used when a request does not specify one explicitly. This is independent from the chat model exposed by Model.
public string DefaultImageModel { get; }
Property Value
Provider
The AI provider for this service
public override string Provider { get; }
Property Value
ReasoningEffort
Reasoning effort for configurable Grok models. Auto leaves the provider default intact. Grok 4.3 accepts None, Low, Medium, and High; Grok 4.5 accepts Low, Medium, and High. Grok 4.6 and 4.7 also accept XHigh and default to High when Auto is selected.
public GrokReasoning ReasoningEffort { get; set; }
Property Value
Methods
ApplyCapabilityRequestProfile(AIRequestProfile)
Applies only execution-local profile settings needed to describe capabilities.
protected override void ApplyCapabilityRequestProfile(AIRequestProfile profile)
Parameters
profileAIRequestProfile
Remarks
Common builder overrides are already captured. Custom providers may override this hook with SetExecutionSetting calls for native mode flags. Do not prepare execution, reserve token budgets, invoke callbacks, validate requests, or modify service/caller-owned state. Execution profile hooks are intentionally not called during inspection.
ApplyProviderSpecificRequestProfile(AIRequestProfile)
protected override Action ApplyProviderSpecificRequestProfile(AIRequestProfile profile)
Parameters
profileAIRequestProfile
Returns
CaptureRequestSettings(IDictionary<string, object?>)
Captures provider and common defaults. Overrides copy native mutable option values.
protected override void CaptureRequestSettings(IDictionary<string, object?> settings)
Parameters
settingsIDictionary<string, object>
CreateFunctionMessageRequest()
Creates HTTP request with function definitions
protected override HttpRequestMessage CreateFunctionMessageRequest()
Returns
CreateMessageRequest()
Creates the HTTP request message for the AI service
protected override HttpRequestMessage CreateMessageRequest()
Returns
CreateStreamParseFailure(string, Exception, StreamDiagnostics)
Lets providers turn a malformed SSE data event into an explicit terminal error. Returning null preserves the tolerant behavior used by legacy compatible providers.
protected override StreamingContent? CreateStreamParseFailure(string jsonData, Exception exception, StreamDiagnostics diagnostics)
Parameters
jsonDatastringexceptionExceptiondiagnosticsStreamDiagnostics
Returns
EditImagesAsync(ImageEditRequest, CancellationToken)
Generates one or more images using existing images as references.
public Task<ImageGenerationResult> EditImagesAsync(ImageEditRequest request, CancellationToken cancellationToken = default)
Parameters
requestImageEditRequestcancellationTokenCancellationToken
Returns
ExtractFunctionCalls(string)
Extracts every function call from one API response.
protected override (string content, FunctionCallBatch functionCalls) ExtractFunctionCalls(string response)
Parameters
responsestring
Returns
ExtractResponseContent(string)
Extracts the response content from the API response
protected override string ExtractResponseContent(string responseContent)
Parameters
responseContentstring
Returns
GenerateImagesAsync(ImageGenerationRequest, CancellationToken)
Generates one or more images from a text prompt.
public Task<ImageGenerationResult> GenerateImagesAsync(ImageGenerationRequest request, CancellationToken cancellationToken = default)
Parameters
requestImageGenerationRequestcancellationTokenCancellationToken
Returns
GetCompletionAsync(Message)
public override Task<string> GetCompletionAsync(Message message)
Parameters
messageMessage
Returns
GetCompletionWithCoTAsync(string, CancellationToken)
Gets completion with Chain of Thought prompting
public Task<string> GetCompletionWithCoTAsync(string prompt, CancellationToken cancellationToken = default)
Parameters
promptstringcancellationTokenCancellationToken
Returns
GetCompletionWithImageAsync(string, string, CancellationToken)
xAI Grok supports vision (image inputs)
public override Task<string> GetCompletionWithImageAsync(string prompt, string imagePath, CancellationToken cancellationToken = default)
Parameters
promptstringimagePathstringcancellationTokenCancellationToken
Returns
GetImageCapabilities(string?)
Inspects an image generation model independently of the selected chat model, without HTTP.
public override ImageModelCapabilities GetImageCapabilities(string? model = null)
Parameters
modelstring
Returns
Remarks
A null model uses the provider's image default. Unknown does not mean unsupported.
GetInputTokenCountAsync()
Gets the token count for the current conversation
public override Task<uint> GetInputTokenCountAsync()
Returns
GetInputTokenCountAsync(string)
Gets the token count for a specific prompt
public override Task<uint> GetInputTokenCountAsync(string prompt)
Parameters
promptstring
Returns
GetModelMaxOutputTokens()
Returns the maximum output tokens allowed for the current model. Override in each service to provide model-specific limits.
protected override uint GetModelMaxOutputTokens()
Returns
OnStreamRoundStarting()
Allows a provider to reset state scoped to a single streaming round.
protected override void OnStreamRoundStarting()
ParseStreamChunk(string, StreamOptions)
Parses a single SSE JSON chunk into a provider-neutral stream chunk. Each provider overrides this to handle its specific JSON format.
protected override OpenAICompatibleService.OpenAIStreamChunk ParseStreamChunk(string jsonData, StreamOptions options)
Parameters
jsonDatastringoptionsStreamOptions
Returns
ResolveRequestCapabilities()
Resolves adapter support using RequestSetting and CurrentRequestFeatures without side effects.
protected override AIModelCapabilities ResolveRequestCapabilities()
Returns
Remarks
Custom providers may override this hook. The default preserves compatibility by returning Unknown. Overrides must not send requests, consume options, change history or invoke user callbacks.
ResolveSpeedSupport(InferenceSpeed)
Locally resolves processing-mode support without checking account entitlement or live capacity.
protected override CapabilitySupport ResolveSpeedSupport(InferenceSpeed speed)
Parameters
speedInferenceSpeed
Returns
SendStreamingRequestAsync(HttpRequestMessage, CancellationToken)
Opens a provider streaming round using the request's transport.
protected override Task<HttpResponseMessage> SendStreamingRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
Parameters
requestHttpRequestMessagecancellationTokenCancellationToken
Returns
StreamParseJson(string)
Parses streaming JSON data
protected override string StreamParseJson(string jsonData)
Parameters
jsonDatastring
Returns
UseGrok4FastModel()
Switches to Grok 4.3 for fast general-purpose workloads.
public XAIService UseGrok4FastModel()
Returns
UseGrok4Model()
Switches to Grok 4.5 for compatibility. To use Grok 4.7, select AIModels.xAI.Grok4_7.
public XAIService UseGrok4Model()
Returns
ValidateRequestFeatures(AIRequestFeatures)
Reject unsupported features before any network request or history mutation.
protected override void ValidateRequestFeatures(AIRequestFeatures features)
Parameters
featuresAIRequestFeatures
ValidateStreamTermination(bool, bool, StreamDiagnostics)
Lets providers require an explicit successful terminal event before committing a streamed assistant message or executing a collected function call.
protected override StreamingContent? ValidateStreamTermination(bool doneMarkerReceived, bool completionEventReceived, StreamDiagnostics diagnostics)
Parameters
doneMarkerReceivedboolcompletionEventReceivedbooldiagnosticsStreamDiagnostics
Returns
WithCodeGenerationMode(string)
Sets Grok-specific parameters for code generation
public XAIService WithCodeGenerationMode(string language = "python")
Parameters
languagestring
Returns
WithGrokParameters(GrokReasoning)
Sets the model-specific Grok reasoning effort.
public XAIService WithGrokParameters(GrokReasoning reasoningEffort = GrokReasoning.High)
Parameters
reasoningEffortGrokReasoning
Returns
WithGrokReasoning(GrokReasoning)
Sets the model-specific Grok reasoning effort and returns this service.
public XAIService WithGrokReasoning(GrokReasoning reasoningEffort = GrokReasoning.High)
Parameters
reasoningEffortGrokReasoning