mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-10-14 01:13:48 +00:00
Merge branch 'main' into chunk-data
This commit is contained in:
commit
9932b5870b
484 files changed
+45549
-2467
No files matched your search
@@ -0,0 +1,96 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace AIStudio.Provider;
|
||||
|
||||
/// <summary>
|
||||
/// Parses the provider-specific JSON fragment stored in <see cref="IProvider.AdditionalJsonApiParameters"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The provider settings UI stores only the body of a JSON object, such as
|
||||
/// <c>"temperature": 0.5</c>. This parser wraps that fragment in curly braces,
|
||||
/// parses it as JSON, and converts it to regular CLR dictionaries, lists, and
|
||||
/// primitive values so request builders and feature detectors can inspect it.
|
||||
/// </remarks>
|
||||
public static class AdditionalApiParametersParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Try to parse an additional-API-parameters JSON fragment into a dictionary.
|
||||
/// </summary>
|
||||
/// <param name="additionalJsonApiParameters">The JSON object body without the surrounding curly braces.</param>
|
||||
/// <param name="parameters">The parsed parameters if parsing succeeds; otherwise an empty dictionary.</param>
|
||||
/// <param name="errorMessage">The JSON parsing error message if parsing fails; otherwise <see langword="null"/>.</param>
|
||||
/// <returns><see langword="true"/> if the fragment is empty or valid JSON; otherwise <see langword="false"/>.</returns>
|
||||
public static bool TryParse(string additionalJsonApiParameters, out IDictionary<string, object> parameters, out string? errorMessage)
|
||||
{
|
||||
parameters = new Dictionary<string, object>();
|
||||
errorMessage = null;
|
||||
if (string.IsNullOrWhiteSpace(additionalJsonApiParameters))
|
||||
return true;
|
||||
|
||||
try
|
||||
{
|
||||
// The UI stores only the object body, so wrap it before parsing.
|
||||
using var jsonDoc = JsonDocument.Parse($"{{{additionalJsonApiParameters}}}");
|
||||
parameters = ConvertToDictionary(jsonDoc.RootElement);
|
||||
return true;
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
errorMessage = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove keys from a parsed parameter dictionary using case-insensitive matching.
|
||||
/// </summary>
|
||||
/// <param name="parameters">The parsed parameter dictionary to mutate.</param>
|
||||
/// <param name="keysToRemove">The parameter names that should be removed.</param>
|
||||
/// <returns>The same dictionary instance after the matching keys were removed.</returns>
|
||||
public static IDictionary<string, object> RemoveKeys(IDictionary<string, object> parameters, IEnumerable<string> keysToRemove)
|
||||
{
|
||||
var removeSet = new HashSet<string>(keysToRemove, StringComparer.OrdinalIgnoreCase);
|
||||
if (removeSet.Count is 0)
|
||||
return parameters;
|
||||
|
||||
foreach (var key in parameters.Keys.ToList())
|
||||
if (removeSet.Contains(key))
|
||||
parameters.Remove(key);
|
||||
|
||||
return parameters;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert a JSON object element into a dictionary of recursively converted CLR values.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON object element to convert.</param>
|
||||
/// <returns>A dictionary containing all JSON object properties.</returns>
|
||||
private static IDictionary<string, object> ConvertToDictionary(JsonElement element)
|
||||
{
|
||||
return element.EnumerateObject()
|
||||
.ToDictionary<JsonProperty, string, object>(
|
||||
p => p.Name,
|
||||
p => ConvertJsonValue(p.Value) ?? string.Empty
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert a JSON value to the closest CLR representation used by provider request objects.
|
||||
/// </summary>
|
||||
/// <param name="element">The JSON element to convert.</param>
|
||||
/// <returns>A string, number, boolean, dictionary, list, or empty string for unsupported/null values.</returns>
|
||||
private static object? ConvertJsonValue(JsonElement element) => element.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => element.GetString(),
|
||||
JsonValueKind.Number => element.TryGetInt32(out var i) ? i :
|
||||
element.TryGetInt64(out var l) ? l :
|
||||
element.TryGetDouble(out var d) ? d :
|
||||
element.GetDecimal(),
|
||||
JsonValueKind.True or JsonValueKind.False => element.GetBoolean(),
|
||||
JsonValueKind.Null => string.Empty,
|
||||
JsonValueKind.Object => ConvertToDictionary(element),
|
||||
JsonValueKind.Array => element.EnumerateArray().Select(ConvertJsonValue).ToList(),
|
||||
|
||||
_ => string.Empty,
|
||||
};
|
||||
}
|
||||
@@ -1072,7 +1072,11 @@ public abstract class BaseProvider : IProvider, ISecretId
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await requestedSecret.Secret.Decrypt(Program.ENCRYPTION));
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
this.logger.LogInformation("Uploading transcription media '{FileName}' with content type '{ContentType}' and {FileSize} bytes.",
|
||||
Path.GetFileName(audioFilePath),
|
||||
mimeType.TextRepresentation,
|
||||
fileStream.Length);
|
||||
using var response = await this.HttpClient.SendAsync(request, token);
|
||||
var responseBody = await response.Content.ReadAsStringAsync(token);
|
||||
|
||||
@@ -1092,6 +1096,10 @@ public abstract class BaseProvider : IProvider, ISecretId
|
||||
|
||||
return TranscriptionResult.FromText(transcriptionResponse.Text);
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (this.IsTimeoutException(e, token))
|
||||
@@ -1194,42 +1202,15 @@ public abstract class BaseProvider : IProvider, ISecretId
|
||||
protected IDictionary<string, object> ParseAdditionalApiParameters(
|
||||
params string[] keysToRemove)
|
||||
{
|
||||
if(string.IsNullOrWhiteSpace(this.AdditionalJsonApiParameters))
|
||||
return new Dictionary<string, object>();
|
||||
|
||||
try
|
||||
if (!AdditionalApiParametersParser.TryParse(this.AdditionalJsonApiParameters, out var apiParameters, out var errorMessage))
|
||||
{
|
||||
// Wrap the user-provided parameters in curly brackets to form a valid JSON object:
|
||||
var json = $"{{{this.AdditionalJsonApiParameters}}}";
|
||||
var jsonDoc = JsonSerializer.Deserialize<JsonElement>(json, JSON_SERIALIZER_OPTIONS);
|
||||
var dict = ConvertToDictionary(jsonDoc);
|
||||
|
||||
// Some keys are always removed because we set them:
|
||||
var removeSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (keysToRemove.Length > 0)
|
||||
removeSet.UnionWith(keysToRemove);
|
||||
|
||||
removeSet.Add("stream");
|
||||
removeSet.Add("model");
|
||||
removeSet.Add("messages");
|
||||
|
||||
// Remove the specified keys (case-insensitive):
|
||||
if (removeSet.Count > 0)
|
||||
{
|
||||
foreach (var key in dict.Keys.ToList())
|
||||
{
|
||||
if (removeSet.Contains(key))
|
||||
dict.Remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
return dict;
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
this.logger.LogError("Failed to parse additional API parameters: {ExceptionMessage}", ex.Message);
|
||||
this.logger.LogError("Failed to parse additional API parameters: {ExceptionMessage}", errorMessage);
|
||||
return new Dictionary<string, object>();
|
||||
}
|
||||
|
||||
// Some keys are always removed because AI Studio sets them itself.
|
||||
var reservedKeys = keysToRemove.Concat(["stream", "model", "messages"]);
|
||||
return AdditionalApiParametersParser.RemoveKeys(apiParameters, reservedKeys);
|
||||
}
|
||||
|
||||
protected static bool TryPopIntParameter(IDictionary<string, object> parameters, string key, out int value)
|
||||
@@ -1311,27 +1292,4 @@ public abstract class BaseProvider : IProvider, ISecretId
|
||||
return true;
|
||||
}
|
||||
|
||||
private static IDictionary<string, object> ConvertToDictionary(JsonElement element)
|
||||
{
|
||||
return element.EnumerateObject()
|
||||
.ToDictionary<JsonProperty, string, object>(
|
||||
p => p.Name,
|
||||
p => ConvertJsonValue(p.Value) ?? string.Empty
|
||||
);
|
||||
}
|
||||
|
||||
private static object? ConvertJsonValue(JsonElement element) => element.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => element.GetString(),
|
||||
JsonValueKind.Number => element.TryGetInt32(out var i) ? i :
|
||||
element.TryGetInt64(out var l) ? l :
|
||||
element.TryGetDouble(out var d) ? d :
|
||||
element.GetDecimal(),
|
||||
JsonValueKind.True or JsonValueKind.False => element.GetBoolean(),
|
||||
JsonValueKind.Null => string.Empty,
|
||||
JsonValueKind.Object => ConvertToDictionary(element),
|
||||
JsonValueKind.Array => element.EnumerateArray().Select(ConvertJsonValue).ToList(),
|
||||
|
||||
_ => string.Empty,
|
||||
};
|
||||
}
|
||||
@@ -71,15 +71,20 @@ public enum Capability
|
||||
VIDEO_OUTPUT,
|
||||
|
||||
/// <summary>
|
||||
/// The AI model can perform reasoning tasks.
|
||||
/// The AI model can perform reasoning tasks. You can enable reasoning optionally, but it is disabled by default.
|
||||
/// </summary>
|
||||
OPTIONAL_REASONING,
|
||||
|
||||
/// <summary>
|
||||
/// The AI model always performs reasoning.
|
||||
/// The AI model always performs reasoning. There is no option to disable reasoning.
|
||||
/// </summary>
|
||||
ALWAYS_REASONING,
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// The AI model performs optional reasoning, but it is enabled by default.
|
||||
/// </summary>
|
||||
REASONING_BY_DEFAULT,
|
||||
|
||||
/// <summary>
|
||||
/// The AI model can embed information or data.
|
||||
/// </summary>
|
||||
|
||||
@@ -35,9 +35,17 @@ public static class LLMProvidersExtensions
|
||||
/// </remarks>
|
||||
/// <param name="llmProvider">The provider.</param>
|
||||
/// <returns>The human-readable name of the provider.</returns>
|
||||
public static string ToName(this LLMProviders llmProvider) => llmProvider switch
|
||||
public static string ToName(this LLMProviders llmProvider) => llmProvider.ToName(translate: true);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the human-readable name of the provider.
|
||||
/// </summary>
|
||||
/// <param name="llmProvider">The provider.</param>
|
||||
/// <param name="translate">Whether generic provider names should be translated.</param>
|
||||
/// <returns>The human-readable name of the provider.</returns>
|
||||
public static string ToName(this LLMProviders llmProvider, bool translate) => llmProvider switch
|
||||
{
|
||||
LLMProviders.NONE => TB("No provider selected"),
|
||||
LLMProviders.NONE => translate ? TB("No provider selected") : "No provider selected",
|
||||
|
||||
LLMProviders.OPEN_AI => "OpenAI",
|
||||
LLMProviders.ANTHROPIC => "Anthropic",
|
||||
@@ -53,12 +61,12 @@ public static class LLMProvidersExtensions
|
||||
LLMProviders.FIREWORKS => "Fireworks.ai",
|
||||
LLMProviders.HUGGINGFACE => "Hugging Face",
|
||||
|
||||
LLMProviders.SELF_HOSTED => TB("Self-hosted"),
|
||||
LLMProviders.SELF_HOSTED => translate ? TB("Self-hosted") : "Self-hosted",
|
||||
|
||||
LLMProviders.HELMHOLTZ => "Helmholtz Blablador",
|
||||
LLMProviders.GWDG => "GWDG SAIA",
|
||||
|
||||
_ => TB("Unknown"),
|
||||
_ => translate ? TB("Unknown") : "Unknown",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace AIStudio.Provider;
|
||||
|
||||
/// <summary>
|
||||
/// Describes whether the provider selection should show the reasoning capability icon.
|
||||
/// </summary>
|
||||
public enum ReasoningIndicatorState
|
||||
{
|
||||
/// <summary>
|
||||
/// Do not show a reasoning indicator for the configured provider.
|
||||
/// </summary>
|
||||
NONE,
|
||||
|
||||
/// <summary>
|
||||
/// Show that the selected model always performs reasoning.
|
||||
/// </summary>
|
||||
ALWAYS_ON,
|
||||
|
||||
/// <summary>
|
||||
/// Show that reasoning is enabled by the provider or model default.
|
||||
/// </summary>
|
||||
DEFAULT_ON,
|
||||
|
||||
/// <summary>
|
||||
/// Show that reasoning was explicitly enabled through the provider settings.
|
||||
/// </summary>
|
||||
CONFIGURED,
|
||||
}
|
||||
Reference in new issue
Block a user