litellm.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. /*
  2. Copyright 2026 LocoStack.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package reconciler
  14. import (
  15. "context"
  16. "crypto/rand"
  17. "crypto/sha256"
  18. "encoding/hex"
  19. "fmt"
  20. "maps"
  21. "sort"
  22. "github.com/LocoStack/loco-operator/api/v1alpha1"
  23. "github.com/LocoStack/loco-operator/pkg/templates/litellm"
  24. "go.yaml.in/yaml/v2"
  25. corev1 "k8s.io/api/core/v1"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. "k8s.io/apimachinery/pkg/runtime"
  28. "sigs.k8s.io/controller-runtime/pkg/client"
  29. "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
  30. )
  31. type LiteLLMReconciler struct {
  32. *DefaultComponentReconciler
  33. client client.Client
  34. scheme *runtime.Scheme
  35. stack *v1alpha1.Stack
  36. component *v1alpha1.Component
  37. }
  38. func NewLiteLLMReconciler(client client.Client, scheme *runtime.Scheme, stack *v1alpha1.Stack, component *v1alpha1.Component) *LiteLLMReconciler {
  39. return &LiteLLMReconciler{
  40. DefaultComponentReconciler: NewDefaultComponentReconciler(client, scheme, stack, component),
  41. client: client,
  42. scheme: scheme,
  43. stack: stack,
  44. component: component,
  45. }
  46. }
  47. func (r *LiteLLMReconciler) ReconcileComponent(ctx context.Context, tmpl *v1alpha1.Template, variables map[string]string) ([]client.Object, error) {
  48. if err := r.ReconcileKey(ctx, "litellm", litellm.LITELLM_AUTH_SECRET_KEY, generateKey); err != nil {
  49. return nil, fmt.Errorf("Failed to reconcile LiteLLM master key: %w", err)
  50. }
  51. deps := make([]client.Object, 0)
  52. emList := make([]*v1alpha1.ExternalModel, 0)
  53. mmList := make([]*v1alpha1.ManagedModel, 0)
  54. for _, dep := range r.component.Spec.Dependencies {
  55. switch dep.Kind {
  56. case "ExternalModel":
  57. em := &v1alpha1.ExternalModel{}
  58. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, em); err != nil {
  59. return nil, fmt.Errorf("Failed to get ExternalModel %s/%s: %w", dep.Namespace, dep.Name, err)
  60. }
  61. emList = append(emList, em)
  62. deps = append(deps, em)
  63. case "ManagedModel":
  64. mm := &v1alpha1.ManagedModel{}
  65. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, mm); err != nil {
  66. return nil, fmt.Errorf("Failed to get ManagedModel %s/%s: %w", dep.Namespace, dep.Name, err)
  67. }
  68. mmList = append(mmList, mm)
  69. deps = append(deps, mm)
  70. }
  71. }
  72. configHash, err := r.reconcileConfigMap(ctx, emList, mmList)
  73. if err != nil {
  74. return nil, fmt.Errorf("Failed to reconcile LiteLLM config: %w", err)
  75. }
  76. authSpecs := make(map[string]map[string]*v1alpha1.AuthSpec)
  77. for _, em := range emList {
  78. if em.Spec.Auth != nil {
  79. if _, ok := authSpecs["ExternalModel"]; !ok {
  80. authSpecs["ExternalModel"] = make(map[string]*v1alpha1.AuthSpec)
  81. }
  82. authSpecs["ExternalModel"][em.Name] = em.Spec.Auth
  83. }
  84. }
  85. injectSecrets(tmpl, authSpecs)
  86. if tmpl.Metadata.Annotations == nil {
  87. tmpl.Metadata.Annotations = make(map[string]string)
  88. }
  89. maps.Copy(tmpl.Metadata.Annotations, map[string]string{
  90. "locostack.com/configHash": configHash,
  91. })
  92. if _, err := r.DefaultComponentReconciler.ReconcileComponent(ctx, tmpl, variables); err != nil {
  93. return nil, err
  94. }
  95. return deps, nil
  96. }
  97. func (r *LiteLLMReconciler) reconcileConfigMap(ctx context.Context, emList []*v1alpha1.ExternalModel, mmList []*v1alpha1.ManagedModel) (string, error) {
  98. var o11yComp *v1alpha1.Component
  99. if r.stack.Spec.Observability != nil && r.stack.Spec.Observability.Enabled {
  100. o11yComp = &v1alpha1.Component{}
  101. if err := r.client.Get(ctx, client.ObjectKey{Name: fmt.Sprintf("observability-%s", r.stack.Name), Namespace: r.stack.Namespace}, o11yComp); err != nil {
  102. return "", fmt.Errorf("Failed to get Observability component: %w", err)
  103. }
  104. }
  105. configBuilder := litellm.LiteLLMConfigBuilder{
  106. MasterKeyEnvName: litellm.LITELLM_MASTER_KEY_ENV_NAME,
  107. Stack: r.stack,
  108. ObservabilityComponent: o11yComp,
  109. ExternalModels: emList,
  110. ManagedModels: mmList,
  111. }
  112. config, err := configBuilder.BuildLiteLLMConfig()
  113. if err != nil {
  114. return "", fmt.Errorf("Failed to build LiteLLM config: %w", err)
  115. }
  116. configData, err := yaml.Marshal(config)
  117. if err != nil {
  118. return "", fmt.Errorf("Failed to marshal LiteLLM config: %w", err)
  119. }
  120. configDataStr := string(configData)
  121. h := sha256.Sum256([]byte(configDataStr))
  122. configHash := hex.EncodeToString(h[:])
  123. cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: r.ResourceName("config"), Namespace: r.component.GetNamespace()}}
  124. if _, err := controllerutil.CreateOrUpdate(ctx, r.client, cm, func() error {
  125. if cm.Labels == nil {
  126. cm.Labels = map[string]string{}
  127. }
  128. maps.Copy(cm.Labels, r.ResourceLabels())
  129. if cm.Annotations == nil {
  130. cm.Annotations = make(map[string]string)
  131. }
  132. cm.Annotations["hash"] = configHash
  133. cm.Data = map[string]string{litellm.LITELLM_CONFIG_KEY: configDataStr}
  134. return controllerutil.SetControllerReference(r.component, cm, r.scheme)
  135. }); err != nil {
  136. return "", err
  137. }
  138. return configHash, nil
  139. }
  140. func generateKey() (string, error) {
  141. b := make([]byte, 24)
  142. if _, err := rand.Read(b); err != nil {
  143. return "", err
  144. }
  145. return "sk-" + hex.EncodeToString(b), nil
  146. }
  147. func injectSecrets(tmpl *v1alpha1.Template, authSpecs map[string]map[string]*v1alpha1.AuthSpec) {
  148. envVars := []corev1.EnvVar{}
  149. kinds := make([]string, 0, len(authSpecs))
  150. for kind := range authSpecs {
  151. kinds = append(kinds, kind)
  152. }
  153. sort.Strings(kinds)
  154. for _, kind := range kinds {
  155. kindAuthSpecs := authSpecs[kind]
  156. names := make([]string, 0, len(kindAuthSpecs))
  157. for name := range kindAuthSpecs {
  158. names = append(names, name)
  159. }
  160. sort.Strings(names)
  161. for _, name := range names {
  162. auth := kindAuthSpecs[name]
  163. var refName string
  164. var refKey string
  165. if auth.APIKey != nil {
  166. refName = auth.APIKey.SecretRef.Name
  167. refKey = auth.APIKey.SecretRef.Key
  168. } else if auth.BearerToken != nil {
  169. refName = auth.BearerToken.Name
  170. refKey = auth.BearerToken.Key
  171. }
  172. if refName != "" && refKey != "" {
  173. envVars = append(envVars, corev1.EnvVar{
  174. Name: litellm.AuthEnvVarName(kind, name),
  175. ValueFrom: &corev1.EnvVarSource{
  176. SecretKeyRef: &corev1.SecretKeySelector{
  177. LocalObjectReference: corev1.LocalObjectReference{Name: refName},
  178. Key: refKey,
  179. },
  180. },
  181. })
  182. }
  183. if auth.Headers != nil {
  184. for _, header := range auth.Headers {
  185. if header.ValueFrom.SecretKeyRef != nil {
  186. envVars = append(envVars, corev1.EnvVar{
  187. Name: litellm.AuthEnvVarName(kind, name+"_"+header.Name),
  188. ValueFrom: &corev1.EnvVarSource{
  189. SecretKeyRef: &corev1.SecretKeySelector{
  190. LocalObjectReference: header.ValueFrom.SecretKeyRef.LocalObjectReference,
  191. Key: header.ValueFrom.SecretKeyRef.Key,
  192. },
  193. },
  194. })
  195. }
  196. }
  197. }
  198. }
  199. }
  200. tmpl.Spec.Runtime.Env = append(tmpl.Spec.Runtime.Env, envVars...)
  201. }