mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-10-17 12:38:00 +00:00
Added LiteLLM as a new LLM provider (#909)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
This commit is contained in:
1 parent
2965102c53
commit
5966f0f6a5
19 files changed
+206
-22
No files matched your search
@@ -1097,6 +1097,15 @@ public abstract class BaseProvider : IProvider, ISecretId
|
||||
|
||||
form.Add(new StringContent(modelName), "model");
|
||||
|
||||
//
|
||||
// Ask for the plain JSON format explicitly. We only ever read the 'text' field, so the
|
||||
// additional data of 'verbose_json' would be wasted anyway. More importantly, gateways
|
||||
// fill in a format of their own when the client names none: LiteLLM asks for
|
||||
// 'verbose_json' to get the duration it needs for its cost tracking, and the newer
|
||||
// transcription models of OpenAI reject that format.
|
||||
//
|
||||
form.Add(new StringContent("json"), "response_format");
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, host.TranscriptionURL());
|
||||
request.Content = form;
|
||||
|
||||
|
||||
@@ -47,6 +47,12 @@ public sealed record Confidence
|
||||
Description = TB("The trust level of this provider **has not yet** been thoroughly **investigated and evaluated**. We do not know if your data is safe."),
|
||||
};
|
||||
|
||||
public static readonly Confidence USER_OPERATED_GATEWAY = new()
|
||||
{
|
||||
Level = ConfidenceLevel.UNKNOWN,
|
||||
Description = TB("You or your organization operate this gateway. However, it forwards your data to **whichever providers you configured behind it**, which may be cloud services in any jurisdiction. We cannot know where your data ends up, so **please assign the trust level yourself**."),
|
||||
};
|
||||
|
||||
public static readonly Confidence USA_NO_TRAINING = new()
|
||||
{
|
||||
Level = ConfidenceLevel.MODERATE,
|
||||
|
||||
@@ -18,6 +18,7 @@ public enum LLMProviders
|
||||
OPEN_ROUTER = 15,
|
||||
HETZNER = 16,
|
||||
IONOS = 17,
|
||||
LITE_LLM = 18,
|
||||
|
||||
FIREWORKS = 5,
|
||||
GROQ = 6,
|
||||
|
||||
@@ -9,6 +9,7 @@ using AIStudio.Provider.Helmholtz;
|
||||
using AIStudio.Provider.Hetzner;
|
||||
using AIStudio.Provider.HuggingFace;
|
||||
using AIStudio.Provider.IONOS;
|
||||
using AIStudio.Provider.LiteLLM;
|
||||
using AIStudio.Provider.Mistral;
|
||||
using AIStudio.Provider.OpenAI;
|
||||
using AIStudio.Provider.OpenRouter;
|
||||
@@ -60,11 +61,12 @@ public static class LLMProvidersExtensions
|
||||
LLMProviders.OPEN_ROUTER => "OpenRouter",
|
||||
LLMProviders.HETZNER => "Hetzner (Experimental)",
|
||||
LLMProviders.IONOS => "IONOS",
|
||||
LLMProviders.LITE_LLM => "LiteLLM",
|
||||
|
||||
LLMProviders.GROQ => "Groq",
|
||||
LLMProviders.FIREWORKS => "Fireworks.ai",
|
||||
LLMProviders.HUGGINGFACE => "Hugging Face",
|
||||
|
||||
|
||||
LLMProviders.SELF_HOSTED => translate ? TB("Self-hosted") : "Self-hosted",
|
||||
|
||||
LLMProviders.HELMHOLTZ => "Helmholtz Blablador",
|
||||
@@ -97,6 +99,7 @@ public static class LLMProvidersExtensions
|
||||
LLMProviders.OPEN_ROUTER => "OpenRouter",
|
||||
LLMProviders.HETZNER => "Hetzner",
|
||||
LLMProviders.IONOS => "IONOS",
|
||||
LLMProviders.LITE_LLM => "LiteLLM",
|
||||
|
||||
LLMProviders.GROQ => "Groq",
|
||||
LLMProviders.FIREWORKS => "Fireworks.ai",
|
||||
@@ -161,6 +164,12 @@ public static class LLMProvidersExtensions
|
||||
"https://www.ionos.com/terms-gtc/privacy-policy/"
|
||||
).WithLevel(settingsManager.GetConfiguredConfidenceLevel(llmProvider)),
|
||||
|
||||
// LiteLLM is a gateway the user runs, but it is not a self-hosted LLM: the proxy owner decides
|
||||
// which downstream providers it routes to, and those are usually cloud services. Self-hosting
|
||||
// the proxy therefore says nothing about where the data ends up, so we do not claim the trust
|
||||
// of a self-hosted model here and let the user assign the level themselves.
|
||||
LLMProviders.LITE_LLM => Confidence.USER_OPERATED_GATEWAY.WithSources("https://docs.litellm.ai/docs/data_security").WithLevel(settingsManager.GetConfiguredConfidenceLevel(llmProvider)),
|
||||
|
||||
LLMProviders.SELF_HOSTED => Confidence.SELF_HOSTED.WithLevel(settingsManager.GetConfiguredConfidenceLevel(llmProvider)),
|
||||
|
||||
LLMProviders.HELMHOLTZ => Confidence.GDPR_NO_TRAINING.WithRegion("Europe, Germany").WithSources("https://helmholtz.cloud/services/?serviceID=d7d5c597-a2f6-4bd1-b71e-4d6499d98570").WithLevel(settingsManager.GetConfiguredConfidenceLevel(llmProvider)),
|
||||
@@ -187,6 +196,7 @@ public static class LLMProvidersExtensions
|
||||
LLMProviders.IONOS => true,
|
||||
LLMProviders.GWDG => true,
|
||||
LLMProviders.OPEN_ROUTER => true,
|
||||
LLMProviders.LITE_LLM => true,
|
||||
|
||||
//
|
||||
// Providers that do not support embeddings:
|
||||
@@ -204,10 +214,10 @@ public static class LLMProvidersExtensions
|
||||
// Self-hosted providers are treated as a special case anyway.
|
||||
//
|
||||
LLMProviders.SELF_HOSTED => true,
|
||||
|
||||
|
||||
_ => false,
|
||||
};
|
||||
|
||||
|
||||
public static bool ProvideTranscriptionAPI(this LLMProviders llmProvider) => llmProvider switch
|
||||
{
|
||||
//
|
||||
@@ -219,6 +229,7 @@ public static class LLMProvidersExtensions
|
||||
LLMProviders.GWDG => true,
|
||||
LLMProviders.HELMHOLTZ => true,
|
||||
LLMProviders.GROQ => true,
|
||||
LLMProviders.LITE_LLM => true,
|
||||
|
||||
//
|
||||
// Providers that support transcription but provide no OpenAI-compatible API yet:
|
||||
@@ -293,6 +304,7 @@ public static class LLMProvidersExtensions
|
||||
LLMProviders.OPEN_ROUTER => new ProviderOpenRouter { InstanceName = instanceName, ConfiguredProviderId = configuredProviderId, AdditionalJsonApiParameters = expertProviderApiParameter, IsEnterpriseConfiguration = isEnterpriseConfiguration },
|
||||
LLMProviders.HETZNER => new ProviderHetzner { InstanceName = instanceName, ConfiguredProviderId = configuredProviderId, AdditionalJsonApiParameters = expertProviderApiParameter, IsEnterpriseConfiguration = isEnterpriseConfiguration },
|
||||
LLMProviders.IONOS => new ProviderIONOS { InstanceName = instanceName, ConfiguredProviderId = configuredProviderId, AdditionalJsonApiParameters = expertProviderApiParameter, IsEnterpriseConfiguration = isEnterpriseConfiguration },
|
||||
LLMProviders.LITE_LLM => new ProviderLiteLLM(hostname) { InstanceName = instanceName, ConfiguredProviderId = configuredProviderId, AdditionalJsonApiParameters = expertProviderApiParameter, IsEnterpriseConfiguration = isEnterpriseConfiguration },
|
||||
|
||||
LLMProviders.GROQ => new ProviderGroq { InstanceName = instanceName, ConfiguredProviderId = configuredProviderId, AdditionalJsonApiParameters = expertProviderApiParameter, IsEnterpriseConfiguration = isEnterpriseConfiguration },
|
||||
LLMProviders.FIREWORKS => new ProviderFireworks { InstanceName = instanceName, ConfiguredProviderId = configuredProviderId, AdditionalJsonApiParameters = expertProviderApiParameter, IsEnterpriseConfiguration = isEnterpriseConfiguration },
|
||||
@@ -436,6 +448,7 @@ public static class LLMProvidersExtensions
|
||||
public static bool IsHostnameNeeded(this LLMProviders provider) => provider switch
|
||||
{
|
||||
LLMProviders.SELF_HOSTED => true,
|
||||
LLMProviders.LITE_LLM => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
@@ -452,15 +465,16 @@ public static class LLMProvidersExtensions
|
||||
LLMProviders.OPEN_ROUTER => true,
|
||||
LLMProviders.HETZNER => true,
|
||||
LLMProviders.IONOS => true,
|
||||
LLMProviders.LITE_LLM => true,
|
||||
|
||||
LLMProviders.GROQ => true,
|
||||
LLMProviders.FIREWORKS => true,
|
||||
LLMProviders.HELMHOLTZ => true,
|
||||
LLMProviders.GWDG => true,
|
||||
LLMProviders.HUGGINGFACE => true,
|
||||
|
||||
|
||||
LLMProviders.SELF_HOSTED => host is (Host.OLLAMA or Host.VLLM),
|
||||
|
||||
|
||||
_ => false,
|
||||
};
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ public static class LLMProvidersIconExtensions
|
||||
LLMProviders.OPEN_ROUTER => $"{ICON_ROOT}/openrouter.svg",
|
||||
LLMProviders.HETZNER => $"{ICON_ROOT}/hetzner.svg",
|
||||
LLMProviders.IONOS => $"{ICON_ROOT}/ionos.svg",
|
||||
LLMProviders.LITE_LLM => $"{ICON_ROOT}/litellm.svg",
|
||||
LLMProviders.GROQ => $"{ICON_ROOT}/groq.svg",
|
||||
LLMProviders.FIREWORKS => $"{ICON_ROOT}/fireworks.svg",
|
||||
LLMProviders.HUGGINGFACE => $"{ICON_ROOT}/hugging-face.svg",
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
using AIStudio.Chat;
|
||||
using AIStudio.Provider.OpenAI;
|
||||
using AIStudio.Settings;
|
||||
|
||||
namespace AIStudio.Provider.LiteLLM;
|
||||
|
||||
public sealed class ProviderLiteLLM(string hostname) : BaseProvider(LLMProviders.LITE_LLM, BuildBaseUri(hostname), ExternalHttpTrustPolicy.ALLOW_CUSTOM_ROOTS_WHEN_HOST_WHITELISTED, LOGGER)
|
||||
{
|
||||
private static readonly ILogger<ProviderLiteLLM> LOGGER = Program.LOGGER_FACTORY.CreateLogger<ProviderLiteLLM>();
|
||||
|
||||
#region Implementation of IProvider
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Id => LLMProviders.LITE_LLM.ToSecretId();
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string InstanceName { get; set; } = "LiteLLM";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool HasModelLoadingCapability => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async IAsyncEnumerable<ContentStreamChunk> StreamChatCompletion(Model chatModel, ChatThread chatThread, SettingsManager settingsManager, [EnumeratorCancellation] CancellationToken token = default)
|
||||
{
|
||||
await foreach (var content in this.StreamOpenAICompatibleChatCompletion<ChatCompletionAPIRequest, ChatCompletionDeltaStreamLine, NoChatCompletionAnnotationStreamLine>(
|
||||
"LiteLLM",
|
||||
chatModel,
|
||||
chatThread,
|
||||
settingsManager,
|
||||
async (systemPrompt, apiParameters) =>
|
||||
{
|
||||
// Build the list of messages:
|
||||
var messages = await chatThread.Blocks.BuildMessagesUsingDirectImageUrlAsync(this.Provider, chatModel);
|
||||
|
||||
return new ChatCompletionAPIRequest
|
||||
{
|
||||
Model = chatModel.Id,
|
||||
|
||||
// Build the messages:
|
||||
// - First of all the system prompt
|
||||
// - Then none-empty user and AI messages
|
||||
Messages = [systemPrompt, ..messages],
|
||||
|
||||
Stream = true,
|
||||
AdditionalApiParameters = apiParameters
|
||||
};
|
||||
},
|
||||
token: token))
|
||||
yield return content;
|
||||
}
|
||||
|
||||
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
|
||||
/// <inheritdoc />
|
||||
public override async IAsyncEnumerable<ImageURL> StreamImageCompletion(Model imageModel, string promptPositive, string promptNegative = FilterOperator.String.Empty, ImageURL referenceImageURL = default, [EnumeratorCancellation] CancellationToken token = default)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task<TranscriptionResult> TranscribeAudioAsync(Model transcriptionModel, string audioFilePath, SettingsManager settingsManager, CancellationToken token = default)
|
||||
{
|
||||
var requestedSecret = await Program.RUST_SERVICE.GetAPIKey(this, SecretStoreType.TRANSCRIPTION_PROVIDER);
|
||||
return await this.PerformStandardTranscriptionRequest(requestedSecret, transcriptionModel, audioFilePath, token: token);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task<IReadOnlyList<IReadOnlyList<float>>> EmbedTextAsync(Model embeddingModel, SettingsManager settingsManager, CancellationToken token = default, params List<string> texts)
|
||||
{
|
||||
var requestedSecret = await Program.RUST_SERVICE.GetAPIKey(this, SecretStoreType.EMBEDDING_PROVIDER);
|
||||
return await this.PerformStandardTextEmbeddingRequest(requestedSecret, embeddingModel, token: token, texts: texts);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override Task<ModelLoadResult> GetTextModels(string? apiKeyProvisional = null, CancellationToken token = default)
|
||||
{
|
||||
return this.LoadModels(SecretStoreType.LLM_PROVIDER, static model => model.IsChatModel(), token, apiKeyProvisional);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override Task<ModelLoadResult> GetImageModels(string? apiKeyProvisional = null, CancellationToken token = default)
|
||||
{
|
||||
return Task.FromResult(ModelLoadResult.FromModels([]));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override Task<ModelLoadResult> GetEmbeddingModels(string? apiKeyProvisional = null, CancellationToken token = default)
|
||||
{
|
||||
return this.LoadModels(SecretStoreType.EMBEDDING_PROVIDER, static model => model.IsEmbeddingModel(), token, apiKeyProvisional);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override Task<ModelLoadResult> GetTranscriptionModels(string? apiKeyProvisional = null, CancellationToken token = default)
|
||||
{
|
||||
return this.LoadModels(SecretStoreType.TRANSCRIPTION_PROVIDER, static model => model.IsTranscriptionModel(), token, apiKeyProvisional);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private static Uri BuildBaseUri(string hostname)
|
||||
{
|
||||
// LiteLLM exposes an OpenAI-compatible API under the "/v1/" path. Users configure the
|
||||
// base URL of their LiteLLM proxy (e.g. http://localhost:4000); we normalize any trailing
|
||||
// slash and append the OpenAI-compatible path.
|
||||
var normalizedHostname = hostname.TrimEnd('/');
|
||||
return new Uri($"{normalizedHostname}/v1/");
|
||||
}
|
||||
|
||||
private Task<ModelLoadResult> LoadModels(SecretStoreType storeType, Func<Model, bool> isWantedKind, CancellationToken token, string? apiKeyProvisional = null)
|
||||
{
|
||||
//
|
||||
// The gateway serves every kind of model through one endpoint, so we have to sort
|
||||
// them apart ourselves. We use the shared model kind detection for that, which every
|
||||
// other provider uses as well:
|
||||
//
|
||||
return this.LoadModelsResponse<ModelsResponse>(
|
||||
storeType,
|
||||
"models",
|
||||
modelResponse => modelResponse.Data.Where(isWantedKind),
|
||||
token,
|
||||
apiKeyProvisional);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user