Class OpenAIService
public class OpenAIService : OpenAICompatibleService, IAIService, IAIRunService, IAIRequestFeatureService, IFunctionRegisterable, IAIProcessingInfoService, IImageGenerationService
- Inheritance
-
OpenAIService
- Implements
- Inherited Members
- Extension Methods
Constructors
OpenAIService(string, HttpClient)
public OpenAIService(string apiKey, HttpClient httpClient)
Parameters
apiKeystringhttpClientHttpClient
OpenAIService(string, string, HttpClient)
Creates a OpenAIService with a specific model.
public OpenAIService(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
FunctionResultsRequireContinuation
Whether observed tool results still require a separate provider round.
protected override bool FunctionResultsRequireContinuation { get; }
Property Value
Gpt5ReasoningEffort
GPT-5 reasoning effort level. GPT-5 defaults to Medium.
public Gpt5Reasoning Gpt5ReasoningEffort { get; set; }
Property Value
Gpt5ReasoningSummary
GPT-5 reasoning summary mode. Defaults to Auto. Set to null to disable reasoning summaries.
public ReasoningSummary? Gpt5ReasoningSummary { get; set; }
Property Value
Gpt5_1ReasoningEffort
GPT-5.1 reasoning effort level. GPT-5.1 defaults to None.
public Gpt5_1Reasoning Gpt5_1ReasoningEffort { get; set; }
Property Value
Gpt5_1ReasoningSummary
GPT-5.1 reasoning summary mode. Defaults to Auto. Set to null to disable reasoning summaries.
public ReasoningSummary? Gpt5_1ReasoningSummary { get; set; }
Property Value
Gpt5_1Verbosity
GPT-5.1 verbosity level. GPT-5.1 defaults to Medium.
public Verbosity? Gpt5_1Verbosity { get; set; }
Property Value
Gpt5_2ReasoningEffort
GPT-5.2 reasoning effort level. GPT-5.2 defaults to None. GPT-5.2 Pro defaults to Medium.
public Gpt5_2Reasoning Gpt5_2ReasoningEffort { get; set; }
Property Value
Gpt5_2ReasoningSummary
GPT-5.2 reasoning summary mode. Defaults to Auto. Set to null to disable reasoning summaries.
public ReasoningSummary? Gpt5_2ReasoningSummary { get; set; }
Property Value
Gpt5_2Verbosity
GPT-5.2 verbosity level. GPT-5.2 defaults to Medium.
public Verbosity? Gpt5_2Verbosity { get; set; }
Property Value
Gpt5_3ReasoningEffort
GPT-5.3 reasoning effort level. GPT-5.3 Codex defaults to Medium.
public Gpt5_3Reasoning Gpt5_3ReasoningEffort { get; set; }
Property Value
Gpt5_3ReasoningSummary
GPT-5.3 reasoning summary mode. Defaults to Auto. Set to null to disable reasoning summaries.
public ReasoningSummary? Gpt5_3ReasoningSummary { get; set; }
Property Value
Gpt5_3Verbosity
GPT-5.3 verbosity level. GPT-5.3 defaults to Medium.
public Verbosity? Gpt5_3Verbosity { get; set; }
Property Value
Gpt5_4ReasoningEffort
GPT-5.4 reasoning effort level. GPT-5.4 defaults to None. GPT-5.4 Pro defaults to Medium.
public Gpt5_4Reasoning Gpt5_4ReasoningEffort { get; set; }
Property Value
Gpt5_4ReasoningSummary
GPT-5.4 reasoning summary mode. Defaults to Auto. Set to null to disable reasoning summaries.
public ReasoningSummary? Gpt5_4ReasoningSummary { get; set; }
Property Value
Gpt5_4Verbosity
GPT-5.4 verbosity level. GPT-5.4 defaults to Medium.
public Verbosity? Gpt5_4Verbosity { get; set; }
Property Value
Gpt5_5ReasoningEffort
GPT-5.5 reasoning effort level. GPT-5.5 defaults to Medium. GPT-5.5 Pro defaults to High.
public Gpt5_5Reasoning Gpt5_5ReasoningEffort { get; set; }
Property Value
Gpt5_5ReasoningSummary
GPT-5.5 reasoning summary mode. Defaults to Auto. Set to null to disable reasoning summaries.
public ReasoningSummary? Gpt5_5ReasoningSummary { get; set; }
Property Value
Gpt5_5Verbosity
GPT-5.5 verbosity level. GPT-5.5 defaults to Medium.
public Verbosity? Gpt5_5Verbosity { get; set; }
Property Value
Gpt5_6ReasoningEffort
GPT-5.6 reasoning effort level. The model default is Medium.
public Gpt5_6Reasoning Gpt5_6ReasoningEffort { get; set; }
Property Value
Gpt5_6ReasoningMode
GPT-5.6 reasoning execution mode. Pro mode is an API parameter, not a separate model ID.
public Gpt5_6ReasoningMode Gpt5_6ReasoningMode { get; set; }
Property Value
Gpt5_6ReasoningSummary
GPT-5.6 reasoning summary mode. Defaults to Auto. Set to null to disable reasoning summaries.
public ReasoningSummary? Gpt5_6ReasoningSummary { get; set; }
Property Value
Gpt5_6Verbosity
GPT-5.6 verbosity level. The model default is Medium.
public Verbosity? Gpt5_6Verbosity { get; set; }
Property Value
Gpt6ReasoningEffort
GPT-6 reasoning effort level. Auto uses the library default of Medium. GPT-6 Sol and Luna also support None. GPT-6 Astra and GPT-6.1 Sol require at least Low.
public Gpt6Reasoning Gpt6ReasoningEffort { get; set; }
Property Value
Gpt6ReasoningMode
GPT-6 reasoning execution mode. Pro is an API parameter, not a separate model ID.
public Gpt6ReasoningMode Gpt6ReasoningMode { get; set; }
Property Value
Gpt6ReasoningSummary
GPT-6 reasoning summary mode. Defaults to Auto. Set to null to omit summaries. Summaries are also omitted when reasoning is None.
public ReasoningSummary? Gpt6ReasoningSummary { get; set; }
Property Value
Gpt6Verbosity
GPT-6 verbosity level. Null uses Medium.
public Verbosity? Gpt6Verbosity { get; set; }
Property Value
HasPendingRunContinuation
Whether the transport will continue this run without a new user request.
protected override bool HasPendingRunContinuation { get; }
Property Value
LastReasoningSummary
Contains the reasoning summary from the last non-streaming API call when the provider returns a reasoning output item. Remains null when summaries are disabled or the provider omits the optional summary output despite accepting reasoning.summary.
public string? LastReasoningSummary { get; }
Property Value
O3ReasoningSummary
o3 reasoning summary mode. This is opt-in because OpenAI requires a verified organization for reasoning summaries. Leave null to request ordinary o3 reasoning without a summary.
public ReasoningSummary? O3ReasoningSummary { get; set; }
Property Value
Provider
The AI provider for this service
public override string Provider { get; }
Property Value
SupportsAsyncFunctionCalls
Whether this provider and model accept native asynchronous function calls.
protected override bool SupportsAsyncFunctionCalls { get; }
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
ApplyRequestProfile(AIRequestProfile)
protected override Action ApplyRequestProfile(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>
CollectPendingStreamingFunctionResultsAsync(CancellationToken)
Waits for pending results unless a duplex transport needs another model turn.
protected override Task<IReadOnlyList<FunctionCallResultBatch>> CollectPendingStreamingFunctionResultsAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationToken
Returns
ConnectRunWebSocketAsync(CancellationToken)
Connects one Responses WebSocket at the configured HTTP API base address. Override for a custom transport.
protected virtual Task<WebSocket> ConnectRunWebSocketAsync(CancellationToken cancellationToken)
Parameters
cancellationTokenCancellationToken
Returns
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
CreateRunSessionAsync(Message, StreamOptions, AIRequestContext?, CancellationToken)
Creates a provider session for a run without changing legacy request transports.
protected override Task<AIService.RunSession> CreateRunSessionAsync(Message message, StreamOptions executionOptions, AIRequestContext? context, CancellationToken cancellationToken)
Parameters
messageMessageexecutionOptionsStreamOptionscontextAIRequestContextcancellationTokenCancellationToken
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
EnrichStreamAssistantMessage(Message)
Allows a provider to attach state collected while streaming before the assistant message is added to the conversation history.
protected override void EnrichStreamAssistantMessage(Message assistantMessage)
Parameters
assistantMessageMessage
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
GetCompletionWithImageAsync(string, string, CancellationToken)
public override Task<string> GetCompletionWithImageAsync(string prompt, string imagePath, CancellationToken cancellationToken = default)
Parameters
promptstringimagePathstringcancellationTokenCancellationToken
Returns
GetConversationCompactionBlockReason()
Returns a reason when protocol state requires retaining the original conversation prefix.
protected override string? GetConversationCompactionBlockReason()
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
GetSpeechAsync(string, string, string)
Generates speech audio from text using OpenAI's TTS model
public Task<byte[]> GetSpeechAsync(string inputText, string voice = "alloy", string model = "tts-1")
Parameters
Returns
OnStreamRoundFailed()
Lets providers discard state collected during a failed streaming round.
protected override void OnStreamRoundFailed()
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
ReadStreamingResponseLinesAsync(HttpResponseMessage, StreamDiagnostics, CancellationToken)
Reads transport events in the line format consumed by the common parser.
protected override IAsyncEnumerable<string> ReadStreamingResponseLinesAsync(HttpResponseMessage response, StreamDiagnostics diagnostics, CancellationToken cancellationToken)
Parameters
responseHttpResponseMessagediagnosticsStreamDiagnosticscancellationTokenCancellationToken
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.
ResolveRequestTimeoutSeconds(FunctionCallingPolicy)
OpenAI timeout policy. GPT-5, GPT-6, and slow pro reasoning workloads (legacy *-pro model IDs and reasoning.mode=pro) can take longer than the 100s default, so when the default is in effect they get longer timeouts. Explicit non-default timeouts are respected.
protected override int? ResolveRequestTimeoutSeconds(FunctionCallingPolicy policy)
Parameters
policyFunctionCallingPolicy
Returns
- int?
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
StreamRoundAsync(StreamOptions, bool, FunctionCallingPolicy, CancellationToken)
Executes a single streaming round: sends an HTTP request, reads the SSE stream, yields chunks, and handles function execution if detected. Yield a FunctionResult to signal the template to continue to the next round. Pending native asynchronous calls also keep the round loop active until their results have been delivered and the model finishes.
protected override IAsyncEnumerable<StreamingContent> StreamRoundAsync(StreamOptions options, bool useFunctions, FunctionCallingPolicy policy, CancellationToken cancellationToken)
Parameters
optionsStreamOptionsuseFunctionsboolpolicyFunctionCallingPolicycancellationTokenCancellationToken
Returns
TranscribeAudioAsync(byte[], string, string?)
Transcribes a completed audio recording to text using OpenAI's GPT-Transcribe model.
public Task<string> TranscribeAudioAsync(byte[] audioData, string fileName, string? language = null)
Parameters
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
WithGpt5Parameters(Gpt5Reasoning, ReasoningSummary?)
Sets GPT-5 specific parameters. Reasoning effort: Minimal, Low, Medium (default), High. Reasoning summary: Auto (default), Concise, Detailed, or null to disable.
public OpenAIService WithGpt5Parameters(Gpt5Reasoning reasoningEffort = Gpt5Reasoning.Medium, ReasoningSummary? reasoningSummary = ReasoningSummary.Auto)
Parameters
reasoningEffortGpt5ReasoningreasoningSummaryReasoningSummary?
Returns
WithGpt5_1Parameters(Gpt5_1Reasoning, Verbosity, ReasoningSummary?)
Sets GPT-5.1 specific parameters. Reasoning effort: None (default), Low, Medium, High. Verbosity: Low, Medium (default), High. Reasoning summary: Auto (default), Concise, Detailed, or null to disable.
public OpenAIService WithGpt5_1Parameters(Gpt5_1Reasoning reasoningEffort = Gpt5_1Reasoning.None, Verbosity verbosity = Verbosity.Medium, ReasoningSummary? reasoningSummary = ReasoningSummary.Auto)
Parameters
reasoningEffortGpt5_1ReasoningverbosityVerbosityreasoningSummaryReasoningSummary?
Returns
WithGpt5_2Parameters(Gpt5_2Reasoning, Verbosity, ReasoningSummary?)
Sets GPT-5.2 specific parameters. Reasoning effort: None (default), Low, Medium, High, XHigh. GPT-5.2 Pro supports Medium, High, XHigh. GPT-5.2 Codex supports Low, Medium (default), High, XHigh. Verbosity: Low, Medium (default), High. Reasoning summary: Auto (default), Concise, Detailed, or null to disable.
public OpenAIService WithGpt5_2Parameters(Gpt5_2Reasoning reasoningEffort = Gpt5_2Reasoning.None, Verbosity verbosity = Verbosity.Medium, ReasoningSummary? reasoningSummary = ReasoningSummary.Auto)
Parameters
reasoningEffortGpt5_2ReasoningverbosityVerbosityreasoningSummaryReasoningSummary?
Returns
WithGpt5_3Parameters(Gpt5_3Reasoning, Verbosity, ReasoningSummary?)
Sets GPT-5.3 specific parameters. Reasoning effort: None (default for Instant), Low, Medium (default for Codex), High, XHigh. GPT-5.3 Codex supports Low, Medium (default), High, XHigh. Verbosity: Low, Medium (default), High. Reasoning summary: Auto (default), Concise, Detailed, or null to disable.
public OpenAIService WithGpt5_3Parameters(Gpt5_3Reasoning reasoningEffort = Gpt5_3Reasoning.None, Verbosity verbosity = Verbosity.Medium, ReasoningSummary? reasoningSummary = ReasoningSummary.Auto)
Parameters
reasoningEffortGpt5_3ReasoningverbosityVerbosityreasoningSummaryReasoningSummary?
Returns
WithGpt5_4Parameters(Gpt5_4Reasoning, Verbosity, ReasoningSummary?)
Sets GPT-5.4 specific parameters. Reasoning effort: None (default), Low, Medium, High, XHigh. GPT-5.4 Pro supports Medium, High, XHigh. Verbosity: Low, Medium (default), High. Reasoning summary: Auto (default), Concise, Detailed, or null to disable.
public OpenAIService WithGpt5_4Parameters(Gpt5_4Reasoning reasoningEffort = Gpt5_4Reasoning.None, Verbosity verbosity = Verbosity.Medium, ReasoningSummary? reasoningSummary = ReasoningSummary.Auto)
Parameters
reasoningEffortGpt5_4ReasoningverbosityVerbosityreasoningSummaryReasoningSummary?
Returns
WithGpt5_5Parameters(Gpt5_5Reasoning, Verbosity, ReasoningSummary?)
Sets GPT-5.5 specific parameters. Reasoning effort: None, Low, Medium (default), High, XHigh. GPT-5.5 Pro defaults to High. Verbosity: Low, Medium (default), High. Reasoning summary: Auto (default), Concise, Detailed, or null to disable.
public OpenAIService WithGpt5_5Parameters(Gpt5_5Reasoning reasoningEffort = Gpt5_5Reasoning.Auto, Verbosity verbosity = Verbosity.Medium, ReasoningSummary? reasoningSummary = ReasoningSummary.Auto)
Parameters
reasoningEffortGpt5_5ReasoningverbosityVerbosityreasoningSummaryReasoningSummary?
Returns
WithGpt5_6Parameters(Gpt5_6Reasoning, Verbosity, ReasoningSummary?, Gpt5_6ReasoningMode)
Sets GPT-5.6 specific parameters. Reasoning effort: None, Low, Medium (default), High, XHigh, Max. Verbosity: Low, Medium (default), High. Pro is a reasoning mode and does not change the selected model ID.
public OpenAIService WithGpt5_6Parameters(Gpt5_6Reasoning reasoningEffort = Gpt5_6Reasoning.Medium, Verbosity verbosity = Verbosity.Medium, ReasoningSummary? reasoningSummary = ReasoningSummary.Auto, Gpt5_6ReasoningMode reasoningMode = Gpt5_6ReasoningMode.Standard)
Parameters
reasoningEffortGpt5_6ReasoningverbosityVerbosityreasoningSummaryReasoningSummary?reasoningModeGpt5_6ReasoningMode
Returns
WithGpt6Parameters(Gpt6Reasoning, Verbosity, ReasoningSummary?, Gpt6ReasoningMode)
Sets GPT-6 specific parameters. Reasoning effort: Low, Medium (library default), High, XHigh, Max; GPT-6 Sol and Luna also support None. GPT-6.1 Sol uses these settings and requires at least Low. Verbosity: Low, Medium (default), High. Pro is a reasoning mode and does not change the selected model ID.
public OpenAIService WithGpt6Parameters(Gpt6Reasoning reasoningEffort = Gpt6Reasoning.Medium, Verbosity verbosity = Verbosity.Medium, ReasoningSummary? reasoningSummary = ReasoningSummary.Auto, Gpt6ReasoningMode reasoningMode = Gpt6ReasoningMode.Standard)
Parameters
reasoningEffortGpt6ReasoningverbosityVerbosityreasoningSummaryReasoningSummary?reasoningModeGpt6ReasoningMode
Returns
WithO3Parameters(Gpt5Reasoning, ReasoningSummary?)
Sets o3 reasoning parameters. Reasoning summaries are disabled by default and require an OpenAI organization that is verified for summary generation.
public OpenAIService WithO3Parameters(Gpt5Reasoning reasoningEffort = Gpt5Reasoning.Medium, ReasoningSummary? reasoningSummary = null)
Parameters
reasoningEffortGpt5ReasoningreasoningSummaryReasoningSummary?
Returns
WithOpenAIParameters(float?, float?, int?)
Fine-tunes the response with specific OpenAI parameters
public OpenAIService WithOpenAIParameters(float? presencePenalty = null, float? frequencyPenalty = null, int? bestOf = null)