2026-05-25 17:32:54 +02:00
using System.Net ;
2024-05-04 11:11:23 +02:00
using System.Net.Http.Headers ;
using System.Runtime.CompilerServices ;
using System.Text ;
using System.Text.Json ;
using AIStudio.Chat ;
2026-09-13 14:17:25 +02:00
using AIStudio.Models ;
2025-01-02 14:50:54 +01:00
using AIStudio.Settings ;
2026-05-25 17:32:54 +02:00
using AIStudio.Tools.PluginSystem ;
2026-09-04 15:48:07 +02:00
using AIStudio.Tools.Rust ;
using AIStudio.Tools.ToolCallingSystem ;
using AIStudio.Tools.ToolCallingSystem.Harness ;
2024-05-04 11:11:23 +02:00
namespace AIStudio.Provider.OpenAI ;
/// <summary>
/// The OpenAI provider.
/// </summary>
2026-05-31 18:46:54 +02:00
public sealed class ProviderOpenAI () : BaseProvider ( LLMProviders . OPEN_AI , new Uri ( "https://api.openai.com/v1/" ), ExternalHttpTrustPolicy . SYSTEM_TRUST_ONLY , LOGGER )
2024-05-04 11:11:23 +02:00
{
2025-09-03 21:25:17 +02:00
private static readonly ILogger < ProviderOpenAI > LOGGER = Program . LOGGER_FACTORY . CreateLogger < ProviderOpenAI >();
2026-05-25 17:32:54 +02:00
private static string TB ( string fallbackEN ) => I18N . I . T ( fallbackEN , typeof ( ProviderOpenAI ). Namespace , nameof ( ProviderOpenAI ));
2024-05-04 11:11:23 +02:00
#region Implementation of IProvider
/// <inheritdoc />
2026-06-20 15:55:09 +02:00
public override string Id => LLMProviders . OPEN_AI . ToSecretId ();
2024-05-04 11:11:23 +02:00
/// <inheritdoc />
2024-12-03 15:24:40 +01:00
public override string InstanceName { get ; set ; } = "OpenAI" ;
2024-05-04 11:11:23 +02:00
2026-04-16 11:24:22 +02:00
/// <inheritdoc />
public override bool HasModelLoadingCapability => true ;
2026-05-25 17:32:54 +02:00
protected override ProviderRequestFailureReason ClassifyProviderRequestFailure ( HttpStatusCode statusCode , string responseBody )
{
if ( statusCode is HttpStatusCode . TooManyRequests && HasInsufficientQuotaError ( responseBody ))
return ProviderRequestFailureReason . INSUFFICIENT_QUOTA ;
return base . ClassifyProviderRequestFailure ( statusCode , responseBody );
}
protected override ProviderRequestFailureReason ClassifyProviderRequestFailure ( string? errorCode , string? errorType , string? errorMessage , string responseBody )
{
if ( IsInsufficientQuota ( errorCode ) || IsInsufficientQuota ( errorType ) || HasInsufficientQuotaError ( responseBody ))
return ProviderRequestFailureReason . INSUFFICIENT_QUOTA ;
return base . ClassifyProviderRequestFailure ( errorCode , errorType , errorMessage , responseBody );
}
2026-09-13 14:17:25 +02:00
protected override string GetProviderRequestFailureUserMessage ( ProviderRequestFailureReason failureReason , ContextWindow contextWindow = default ) => failureReason switch
2026-05-25 17:32:54 +02:00
{
ProviderRequestFailureReason . INSUFFICIENT_QUOTA => TB ( "It looks like you do not have any API credits left with OpenAI. Please add credits to your account and try again." ),
2026-09-13 14:17:25 +02:00
_ => base . GetProviderRequestFailureUserMessage ( failureReason , contextWindow ),
2026-05-25 17:32:54 +02:00
};
2024-05-04 11:11:23 +02:00
/// <inheritdoc />
2025-08-31 14:27:35 +02:00
public override async IAsyncEnumerable < ContentStreamChunk > StreamChatCompletion ( Model chatModel , ChatThread chatThread , SettingsManager settingsManager , [ EnumeratorCancellation ] CancellationToken token = default )
2024-05-04 11:11:23 +02:00
{
// Get the API key:
2026-06-10 21:01:27 +02:00
var requestedSecret = await Program . RUST_SERVICE . GetAPIKey ( this , SecretStoreType . LLM_PROVIDER );
2024-05-04 11:11:23 +02:00
if (! requestedSecret . Success )
yield break ;
2025-01-01 20:11:42 +01:00
// Unfortunately, OpenAI changed the name of the system prompt based on the model.
2025-09-03 10:08:04 +02:00
// All models that start with "o" (the omni aka reasoning models), all GPT4o models,
// and all newer models have the system prompt named "developer". All other models
// have the system prompt named "system". We need to check this to get the correct
// system prompt.
2025-01-01 20:11:42 +01:00
//
// To complicate it even more: The early versions of reasoning models, which are released
// before the 17th of December 2024, have no system prompt at all. We need to check this
// as well.
// Apply the basic rule first:
2025-09-03 10:08:04 +02:00
var systemPromptRole =
chatModel . Id . StartsWith ( 'o' ) ||
chatModel . Id . StartsWith ( "gpt-5" , StringComparison . Ordinal ) ||
chatModel . Id . Contains ( "4o" ) ? "developer" : "system" ;
2025-01-01 20:11:42 +01:00
// Check if the model is an early version of the reasoning models:
systemPromptRole = chatModel . Id switch
{
"o1-mini" => "user" ,
"o1-mini-2024-09-12" => "user" ,
"o1-preview" => "user" ,
"o1-preview-2024-09-12" => "user" ,
_ => systemPromptRole ,
};
2024-05-04 11:11:23 +02:00
2026-09-04 15:48:07 +02:00
// Read the model capabilities. Through the settings provider, so that the user's expert
// capability overrides apply:
var providerSettings = this . CreateSettingsProvider ( chatModel );
2026-09-13 14:17:25 +02:00
var modelProfile = providerSettings . GetModelProfile ();
2025-09-03 10:08:04 +02:00
// Check if we are using the Responses API or the Chat Completion API:
2026-09-13 14:17:25 +02:00
var usingResponsesAPI = modelProfile . Has ( Capability . RESPONSES_API );
2025-09-03 10:08:04 +02:00
// Prepare the request path based on the API we are using:
var requestPath = usingResponsesAPI ? "responses" : "chat/completions" ;
2025-09-03 21:25:17 +02:00
LOGGER . LogInformation ( "Using the system prompt role '{SystemPromptRole}' and the '{RequestPath}' API for model '{ChatModelId}'." , systemPromptRole , requestPath , chatModel . Id );
2025-09-03 10:08:04 +02:00
//
// Prepare the tools we want to use:
//
2026-09-04 15:48:07 +02:00
var toolRegistry = Program . SERVICE_PROVIDER . GetService < ToolRegistry >();
var providerConfidence = this . Provider . GetConfidence ( settingsManager ). Level ;
//
// The provider-native web search is held to the same confidence the local web search tool
// asks for: to the user it is the same act, whoever performs the search.
//
var minimumWebSearchConfidence = toolRegistry ?. GetMinimumProviderConfidence ( ToolSelectionRules . WEB_SEARCH_TOOL_ID ) ?? ConfidenceLevel . NONE ;
var isWebSearchAllowed = settingsManager . IsToolActive ( ToolSelectionRules . WEB_SEARCH_TOOL_ID ) &&
ToolSelectionRules . IsProviderConfidenceAllowed ( providerConfidence , minimumWebSearchConfidence );
2026-09-13 14:17:25 +02:00
IList < object > providerTools = modelProfile . Has ( Capability . WEB_SEARCH ) && isWebSearchAllowed
2026-09-04 15:48:07 +02:00
? [ ProviderTools . WEB_SEARCH ]
: [];
2024-05-04 11:11:23 +02:00
2025-11-13 18:13:16 +01:00
// Parse the API parameters:
2026-09-04 15:48:07 +02:00
var additionalApiParameters = this . ParseAdditionalApiParameters ( "input" , "store" , "tools" );
if (! usingResponsesAPI )
{
await foreach ( var content in this . StreamOpenAICompatibleChatCompletion < ChatCompletionAPIRequest , ChatCompletionDeltaStreamLine , ChatCompletionAnnotationStreamLine >(
"OpenAI" ,
chatModel ,
chatThread ,
settingsManager ,
async ( systemPrompt , apiParameters , tools ) =>
{
var messages = await chatThread . Blocks . BuildMessagesAsync (
2026-09-13 14:17:25 +02:00
providerSettings ,
2026-09-04 15:48:07 +02:00
role => role switch
{
ChatRole . USER => "user" ,
ChatRole . AI => "assistant" ,
ChatRole . AGENT => "assistant" ,
ChatRole . SYSTEM => systemPromptRole ,
_ => "user" ,
},
text => new SubContentText
{
Text = text ,
},
async attachment => new SubContentImageUrlNested
{
ImageUrl = new SubContentImageUrlData
{
Url = await attachment . TryAsBase64 ( token : token ) is ( true , var base64Content )
? $"data:{attachment.DetermineMimeType()};base64,{base64Content}"
: string . Empty ,
},
});
return new ChatCompletionAPIRequest
{
Model = chatModel . Id ,
Messages = [ systemPrompt , .. messages ],
Stream = true ,
Tools = tools ,
AdditionalApiParameters = apiParameters ,
};
},
systemPromptRole : systemPromptRole ,
requestPath : "chat/completions" ,
token : token ))
yield return content ;
yield break ;
}
var toolExecutor = Program . SERVICE_PROVIDER . GetService < ToolExecutor >();
var currentAssistantContent = chatThread . Blocks . LastOrDefault ( x => x . Role is ChatRole . AI )?. Content as ContentText ;
currentAssistantContent ?. ToolInvocations . Clear ();
IReadOnlyList <( ToolDefinition Definition , IToolImplementation Implementation )> runnableTools = toolRegistry is null
? []
: await toolRegistry . GetRunnableToolsAsync (
providerSettings ,
chatThread . RuntimeComponent ,
chatThread . RuntimeSelectedToolIds ,
providerConfidence ,
chatThread . MayRunTools ( settingsManager ));
var toolAwareDefinitions = toolExecutor is null
? Enumerable . Empty < ToolDefinition >()
: runnableTools . Select ( x => x . Definition );
var systemPrompt = new TextMessage
{
Role = systemPromptRole ,
Content = chatThread . PrepareSystemPrompt ( settingsManager , toolAwareDefinitions ),
};
2025-12-10 13:48:13 +01:00
// Build the list of messages:
2025-12-30 18:30:32 +01:00
var messages = await chatThread . Blocks . BuildMessagesAsync (
2026-09-13 14:17:25 +02:00
providerSettings ,
2025-12-30 18:30:32 +01:00
role => role switch
2025-12-10 13:48:13 +01:00
{
ChatRole . USER => "user" ,
ChatRole . AI => "assistant" ,
ChatRole . AGENT => "assistant" ,
ChatRole . SYSTEM => systemPromptRole ,
_ => "user" ,
},
2026-09-04 15:48:07 +02:00
text => new SubContentInputText
2025-12-10 13:48:13 +01:00
{
2026-09-04 15:48:07 +02:00
Text = text ,
2025-12-30 18:30:32 +01:00
},
2026-09-04 15:48:07 +02:00
async attachment => new SubContentInputImage
2025-12-30 18:30:32 +01:00
{
2026-09-04 15:48:07 +02:00
ImageUrl = await attachment . TryAsBase64 ( token : token ) is ( true , var base64Content )
? $"data:{attachment.DetermineMimeType()};base64,{base64Content}"
: string . Empty ,
2025-12-30 18:30:32 +01:00
});
2026-09-04 15:48:07 +02:00
var baseInput = new List < object > { systemPrompt };
baseInput . AddRange ( messages );
if ( usingResponsesAPI && toolExecutor is not null && runnableTools . Count > 0 )
{
var adapter = new ResponsesToolCallingAdapter (
chatModel ,
baseInput ,
additionalApiParameters ,
providerTools ,
runnableTools ,
( requestDto , requestToken ) => this . ExecuteResponsesRequest ( requestDto , requestedSecret , requestToken ));
var loop = Program . SERVICE_PROVIDER . GetRequiredService < IToolCallingLoop >();
var loopContext = new ToolCallingLoopContext
{
ChatThread = chatThread ,
RunnableTools = runnableTools ,
ToolExecutor = toolExecutor ,
Provider = this ,
CurrentAssistantContent = currentAssistantContent ,
ProviderInstanceName = this . InstanceName ,
ProviderType = this . Provider ,
ModelId = chatModel . Id ,
};
await foreach ( var content in loop . RunAsync ( adapter , loopContext , token ))
yield return content ;
yield break ;
}
if ( runnableTools . Count > 0 )
providerTools = [];
2025-11-13 18:13:16 +01:00
2025-09-03 10:08:04 +02:00
//
// Create the request: either for the Responses API or the Chat Completion API
//
var openAIChatRequest = usingResponsesAPI switch
2024-05-04 11:11:23 +02:00
{
2025-09-03 10:08:04 +02:00
// Chat Completion API request:
false => JsonSerializer . Serialize ( new ChatCompletionAPIRequest
2024-05-04 11:11:23 +02:00
{
2025-09-03 10:08:04 +02:00
Model = chatModel . Id ,
2025-12-28 14:10:20 +01:00
// All messages go into the messages field:
2025-12-10 13:48:13 +01:00
Messages = [ systemPrompt , .. messages ],
2025-09-03 10:08:04 +02:00
// Right now, we only support streaming completions:
Stream = true ,
2026-09-04 15:48:07 +02:00
AdditionalApiParameters = additionalApiParameters
2025-09-03 10:08:04 +02:00
}, JSON_SERIALIZER_OPTIONS ),
2026-09-04 15:48:07 +02:00
2025-09-03 10:08:04 +02:00
// Responses API request:
true => JsonSerializer . Serialize ( new ResponsesAPIRequest
{
Model = chatModel . Id ,
2025-12-28 14:10:20 +01:00
// All messages go into the input field:
2026-09-04 15:48:07 +02:00
Input = baseInput ,
2024-05-04 11:11:23 +02:00
2025-09-03 10:08:04 +02:00
// Right now, we only support streaming completions:
Stream = true ,
// We do not want to store any data on OpenAI's servers:
Store = false ,
// Tools we want to use:
2026-09-04 15:48:07 +02:00
Tools = providerTools ,
2025-09-03 10:08:04 +02:00
2025-11-13 18:13:16 +01:00
// Additional API parameters:
2026-09-04 15:48:07 +02:00
AdditionalApiParameters = additionalApiParameters
2025-11-13 18:13:16 +01:00
2025-09-03 10:08:04 +02:00
}, JSON_SERIALIZER_OPTIONS ),
};
2025-12-30 18:30:32 +01:00
2025-01-04 14:11:32 +01:00
async Task < HttpRequestMessage > RequestBuilder ()
2025-01-01 15:49:27 +01:00
{
2025-01-04 14:11:32 +01:00
// Build the HTTP post request:
2025-09-03 10:08:04 +02:00
var request = new HttpRequestMessage ( HttpMethod . Post , requestPath );
2025-01-01 15:49:27 +01:00
2025-01-04 14:11:32 +01:00
// Set the authorization header:
2026-06-10 21:01:27 +02:00
request . Headers . Authorization = new AuthenticationHeaderValue ( "Bearer" , await requestedSecret . Secret . Decrypt ( Program . ENCRYPTION ));
2025-01-01 15:49:27 +01:00
2025-01-04 14:11:32 +01:00
// Set the content:
request . Content = new StringContent ( openAIChatRequest , Encoding . UTF8 , "application/json" );
return request ;
2025-01-04 12:37:49 +01:00
}
2025-09-03 10:08:04 +02:00
if ( usingResponsesAPI )
await foreach ( var content in this . StreamResponsesInternal < ResponsesDeltaStreamLine , ResponsesAnnotationStreamLine >( "OpenAI" , RequestBuilder , token ))
yield return content ;
2024-05-04 11:11:23 +02:00
2025-09-03 10:08:04 +02:00
else
await foreach ( var content in this . StreamChatCompletionInternal < ChatCompletionDeltaStreamLine , ChatCompletionAnnotationStreamLine >( "OpenAI" , RequestBuilder , token ))
yield return content ;
2024-05-04 11:11:23 +02:00
}
2026-09-04 15:48:07 +02:00
private async Task < ResponsesResponse ?> ExecuteResponsesRequest ( ResponsesAPIRequest requestDto , RequestedSecret requestedSecret , CancellationToken token )
{
using var request = new HttpRequestMessage ( HttpMethod . Post , "responses" );
request . Headers . Authorization = new AuthenticationHeaderValue ( "Bearer" , await requestedSecret . Secret . Decrypt ( Program . ENCRYPTION ));
request . Content = new StringContent ( JsonSerializer . Serialize ( requestDto , JSON_SERIALIZER_OPTIONS ), Encoding . UTF8 , "application/json" );
using var response = await this . HttpClient . SendAsync ( request , token );
if (! response . IsSuccessStatusCode )
{
var responseBody = await response . Content . ReadAsStringAsync ( token );
LOGGER . LogError ( "Tool calling Responses API request failed with status code {ResponseStatusCode} and body: '{ResponseBody}'." , response . StatusCode , responseBody );
await ToolCallingMessages . SendToolCallingRequestFailedAsync (( int ) response . StatusCode );
return null ;
}
return await response . Content . ReadFromJsonAsync < ResponsesResponse >( JSON_SERIALIZER_OPTIONS , token );
}
2024-05-04 11:11:23 +02:00
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
2025-09-03 10:08:04 +02:00
2024-05-04 11:11:23 +02:00
/// <inheritdoc />
2024-12-03 15:24:40 +01:00
public override async IAsyncEnumerable < ImageURL > StreamImageCompletion ( Model imageModel , string promptPositive , string promptNegative = FilterOperator . String . Empty , ImageURL referenceImageURL = default , [ EnumeratorCancellation ] CancellationToken token = default )
2024-05-04 11:11:23 +02:00
{
yield break ;
}
2025-09-03 10:08:04 +02:00
2024-05-04 11:11:23 +02:00
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
2026-01-11 16:02:28 +01:00
/// <inheritdoc />
2026-05-23 11:25:18 +02:00
public override async Task < TranscriptionResult > TranscribeAudioAsync ( Model transcriptionModel , string audioFilePath , SettingsManager settingsManager , CancellationToken token = default )
2026-01-11 16:02:28 +01:00
{
2026-06-10 21:01:27 +02:00
var requestedSecret = await Program . RUST_SERVICE . GetAPIKey ( this , SecretStoreType . TRANSCRIPTION_PROVIDER );
2026-01-11 16:02:28 +01:00
return await this . PerformStandardTranscriptionRequest ( requestedSecret , transcriptionModel , audioFilePath , token : token );
}
2026-02-20 15:32:54 +01:00
/// <inhertidoc />
public override async Task < IReadOnlyList < IReadOnlyList < float >>> EmbedTextAsync ( Model embeddingModel , SettingsManager settingsManager , CancellationToken token = default , params List < string > texts )
{
2026-06-10 21:01:27 +02:00
var requestedSecret = await Program . RUST_SERVICE . GetAPIKey ( this , SecretStoreType . EMBEDDING_PROVIDER );
2026-02-20 15:32:54 +01:00
return await this . PerformStandardTextEmbeddingRequest ( requestedSecret , embeddingModel , token : token , texts : texts );
}
2024-05-04 11:11:23 +02:00
2026-08-30 13:58:16 +02:00
//
// OpenAI offers every kind of model through one models endpoint, so we have to sort them apart
// ourselves. We used to do that with lists of name prefixes kept here. The shared model kind
// detection knows those families as well, and it knows them for every provider, so we ask it
// instead of maintaining a second set of rules which only ever lagged behind.
//
2024-05-04 11:11:23 +02:00
/// <inheritdoc />
2026-08-30 13:58:16 +02:00
public override Task < ModelLoadResult > GetTextModels ( string? apiKeyProvisional = null , CancellationToken token = default )
2024-05-04 11:11:23 +02:00
{
2026-09-13 14:17:25 +02:00
return this . LoadModels ( SecretStoreType . LLM_PROVIDER , model => model . IsChatModel ( this . Provider ), apiKeyProvisional , token );
2024-05-04 11:11:23 +02:00
}
/// <inheritdoc />
2026-04-14 13:39:11 +02:00
public override Task < ModelLoadResult > GetImageModels ( string? apiKeyProvisional = null , CancellationToken token = default )
2024-05-04 11:11:23 +02:00
{
2026-09-13 14:17:25 +02:00
return this . LoadModels ( SecretStoreType . IMAGE_PROVIDER , model => model . IsImageModel ( this . Provider ), apiKeyProvisional , token );
2024-05-04 11:11:23 +02:00
}
2026-08-30 13:58:16 +02:00
2024-12-03 15:24:40 +01:00
/// <inheritdoc />
2026-04-14 13:39:11 +02:00
public override Task < ModelLoadResult > GetEmbeddingModels ( string? apiKeyProvisional = null , CancellationToken token = default )
2024-12-03 15:24:40 +01:00
{
2026-09-13 14:17:25 +02:00
return this . LoadModels ( SecretStoreType . EMBEDDING_PROVIDER , model => model . IsEmbeddingModel ( this . Provider ), apiKeyProvisional , token );
2024-12-03 15:24:40 +01:00
}
2026-08-30 13:58:16 +02:00
2026-01-09 12:45:21 +01:00
/// <inheritdoc />
2026-08-30 13:58:16 +02:00
public override Task < ModelLoadResult > GetTranscriptionModels ( string? apiKeyProvisional = null , CancellationToken token = default )
2026-01-09 12:45:21 +01:00
{
2026-09-13 14:17:25 +02:00
return this . LoadModels ( SecretStoreType . TRANSCRIPTION_PROVIDER , model => model . IsTranscriptionModel ( this . Provider ), apiKeyProvisional , token );
2026-01-09 12:45:21 +01:00
}
2024-05-04 11:11:23 +02:00
#endregion
2026-09-04 15:48:07 +02:00
private Task < ModelLoadResult > LoadModels ( SecretStoreType storeType , Func < Model , bool > isWantedKind , string? apiKeyProvisional , CancellationToken token )
2024-05-04 11:11:23 +02:00
{
2026-04-14 13:39:11 +02:00
return this . LoadModelsResponse < ModelsResponse >(
storeType ,
"models" ,
2026-08-30 13:58:16 +02:00
modelResponse => modelResponse . Data . Where ( isWantedKind ),
2026-09-04 15:48:07 +02:00
apiKeyProvisional , token : token );
2024-05-04 11:11:23 +02:00
}
2026-05-25 17:32:54 +02:00
private static bool HasInsufficientQuotaError ( string responseBody )
{
if ( string . IsNullOrWhiteSpace ( responseBody ))
return false ;
try
{
using var document = JsonDocument . Parse ( responseBody );
return HasInsufficientQuotaError ( document . RootElement );
}
catch ( JsonException )
{
return false ;
}
}
private static bool HasInsufficientQuotaError ( JsonElement element )
{
switch ( element . ValueKind )
{
case JsonValueKind . Object :
if ( HasJsonStringValue ( element , "type" , "insufficient_quota" ) ||
HasJsonStringValue ( element , "code" , "insufficient_quota" ))
return true ;
foreach ( var property in element . EnumerateObject ())
if ( HasInsufficientQuotaError ( property . Value ))
return true ;
return false ;
case JsonValueKind . Array :
foreach ( var item in element . EnumerateArray ())
if ( HasInsufficientQuotaError ( item ))
return true ;
return false ;
default :
return false ;
}
}
private static bool IsInsufficientQuota ( string? value )
{
return value is not null && value . Equals ( "insufficient_quota" , StringComparison . OrdinalIgnoreCase );
}
private static bool HasJsonStringValue ( JsonElement element , string propertyName , string expectedValue )
{
return element . TryGetProperty ( propertyName , out var propertyElement ) &&
propertyElement . ValueKind is JsonValueKind . String &&
string . Equals ( propertyElement . GetString (), expectedValue , StringComparison . OrdinalIgnoreCase );
}
2026-09-04 15:48:07 +02:00
}