litellm.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. etList := make([]*v1alpha1.ExternalTool, 0)
  55. mtList := make([]*v1alpha1.ManagedTool, 0)
  56. for _, dep := range r.component.Spec.Dependencies {
  57. switch dep.Kind {
  58. case "ExternalModel":
  59. em := &v1alpha1.ExternalModel{}
  60. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, em); err != nil {
  61. return nil, fmt.Errorf("Failed to get ExternalModel %s/%s: %w", dep.Namespace, dep.Name, err)
  62. }
  63. emList = append(emList, em)
  64. deps = append(deps, em)
  65. case "ManagedModel":
  66. mm := &v1alpha1.ManagedModel{}
  67. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, mm); err != nil {
  68. return nil, fmt.Errorf("Failed to get ManagedModel %s/%s: %w", dep.Namespace, dep.Name, err)
  69. }
  70. mmList = append(mmList, mm)
  71. deps = append(deps, mm)
  72. case "ExternalTool":
  73. et := &v1alpha1.ExternalTool{}
  74. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, et); err != nil {
  75. return nil, fmt.Errorf("Failed to get ExternalTool %s/%s: %w", dep.Namespace, dep.Name, err)
  76. }
  77. etList = append(etList, et)
  78. deps = append(deps, et)
  79. case "ManagedTool":
  80. mt := &v1alpha1.ManagedTool{}
  81. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, mt); err != nil {
  82. return nil, fmt.Errorf("Failed to get ManagedTool %s/%s: %w", dep.Namespace, dep.Name, err)
  83. }
  84. mtList = append(mtList, mt)
  85. deps = append(deps, mt)
  86. }
  87. }
  88. configHash, err := r.reconcileConfigMap(ctx, emList, mmList, etList, mtList)
  89. if err != nil {
  90. return nil, fmt.Errorf("Failed to reconcile LiteLLM config: %w", err)
  91. }
  92. authSpecs := make(map[string]map[string]*v1alpha1.AuthSpec)
  93. for _, em := range emList {
  94. if em.Spec.Auth != nil {
  95. if _, ok := authSpecs["ExternalModel"]; !ok {
  96. authSpecs["ExternalModel"] = make(map[string]*v1alpha1.AuthSpec)
  97. }
  98. authSpecs["ExternalModel"][em.Name] = em.Spec.Auth
  99. }
  100. }
  101. for _, et := range etList {
  102. if et.Spec.Auth != nil {
  103. if _, ok := authSpecs["ExternalTool"]; !ok {
  104. authSpecs["ExternalTool"] = make(map[string]*v1alpha1.AuthSpec)
  105. }
  106. authSpecs["ExternalTool"][et.Name] = et.Spec.Auth
  107. }
  108. }
  109. for _, mt := range mtList {
  110. if mt.Spec.Auth != nil {
  111. if _, ok := authSpecs["ManagedTool"]; !ok {
  112. authSpecs["ManagedTool"] = make(map[string]*v1alpha1.AuthSpec)
  113. }
  114. authSpecs["ManagedTool"][mt.Name] = mt.Spec.Auth
  115. }
  116. }
  117. injectSecrets(tmpl, authSpecs)
  118. if tmpl.Metadata.Annotations == nil {
  119. tmpl.Metadata.Annotations = make(map[string]string)
  120. }
  121. maps.Copy(tmpl.Metadata.Annotations, map[string]string{
  122. "locostack.com/configHash": configHash,
  123. })
  124. if _, err := r.DefaultComponentReconciler.ReconcileComponent(ctx, tmpl, variables); err != nil {
  125. return nil, err
  126. }
  127. return deps, nil
  128. }
  129. func (r *LiteLLMReconciler) reconcileConfigMap(ctx context.Context, emList []*v1alpha1.ExternalModel, mmList []*v1alpha1.ManagedModel, etList []*v1alpha1.ExternalTool, mtList []*v1alpha1.ManagedTool) (string, error) {
  130. var o11yComp *v1alpha1.Component
  131. if r.stack.Spec.Observability != nil && r.stack.Spec.Observability.Enabled {
  132. o11yComp = &v1alpha1.Component{}
  133. if err := r.client.Get(ctx, client.ObjectKey{Name: fmt.Sprintf("observability-%s", r.stack.Name), Namespace: r.stack.Namespace}, o11yComp); err != nil {
  134. return "", fmt.Errorf("Failed to get Observability component: %w", err)
  135. }
  136. }
  137. configBuilder := litellm.LiteLLMConfigBuilder{
  138. MasterKeyEnvName: litellm.LITELLM_MASTER_KEY_ENV_NAME,
  139. Stack: r.stack,
  140. ObservabilityComponent: o11yComp,
  141. ExternalModels: emList,
  142. ManagedModels: mmList,
  143. ExternalTools: etList,
  144. ManagedTools: mtList,
  145. }
  146. config, err := configBuilder.BuildLiteLLMConfig()
  147. if err != nil {
  148. return "", fmt.Errorf("Failed to build LiteLLM config: %w", err)
  149. }
  150. configData, err := yaml.Marshal(config)
  151. if err != nil {
  152. return "", fmt.Errorf("Failed to marshal LiteLLM config: %w", err)
  153. }
  154. configDataStr := string(configData)
  155. h := sha256.Sum256([]byte(configDataStr))
  156. configHash := hex.EncodeToString(h[:])
  157. cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: r.ResourceName("config"), Namespace: r.component.GetNamespace()}}
  158. if _, err := controllerutil.CreateOrUpdate(ctx, r.client, cm, func() error {
  159. if cm.Labels == nil {
  160. cm.Labels = map[string]string{}
  161. }
  162. maps.Copy(cm.Labels, r.ResourceLabels())
  163. if cm.Annotations == nil {
  164. cm.Annotations = make(map[string]string)
  165. }
  166. cm.Annotations["hash"] = configHash
  167. cm.Data = map[string]string{litellm.LITELLM_CONFIG_KEY: configDataStr}
  168. return controllerutil.SetControllerReference(r.component, cm, r.scheme)
  169. }); err != nil {
  170. return "", err
  171. }
  172. return configHash, nil
  173. }
  174. func generateKey() (string, error) {
  175. b := make([]byte, 24)
  176. if _, err := rand.Read(b); err != nil {
  177. return "", err
  178. }
  179. return "sk-" + hex.EncodeToString(b), nil
  180. }
  181. func injectSecrets(tmpl *v1alpha1.Template, authSpecs map[string]map[string]*v1alpha1.AuthSpec) {
  182. envVars := []corev1.EnvVar{}
  183. kinds := make([]string, 0, len(authSpecs))
  184. for kind := range authSpecs {
  185. kinds = append(kinds, kind)
  186. }
  187. sort.Strings(kinds)
  188. for _, kind := range kinds {
  189. kindAuthSpecs := authSpecs[kind]
  190. names := make([]string, 0, len(kindAuthSpecs))
  191. for name := range kindAuthSpecs {
  192. names = append(names, name)
  193. }
  194. sort.Strings(names)
  195. for _, name := range names {
  196. auth := kindAuthSpecs[name]
  197. var refName string
  198. var refKey string
  199. if auth.APIKey != nil {
  200. refName = auth.APIKey.SecretRef.Name
  201. refKey = auth.APIKey.SecretRef.Key
  202. } else if auth.BearerToken != nil {
  203. refName = auth.BearerToken.Name
  204. refKey = auth.BearerToken.Key
  205. }
  206. if refName != "" && refKey != "" {
  207. envVars = append(envVars, corev1.EnvVar{
  208. Name: litellm.AuthEnvVarName(kind, name),
  209. ValueFrom: &corev1.EnvVarSource{
  210. SecretKeyRef: &corev1.SecretKeySelector{
  211. LocalObjectReference: corev1.LocalObjectReference{Name: refName},
  212. Key: refKey,
  213. },
  214. },
  215. })
  216. }
  217. if auth.Headers != nil {
  218. for _, header := range auth.Headers {
  219. if header.ValueFrom.SecretKeyRef != nil {
  220. envVars = append(envVars, corev1.EnvVar{
  221. Name: litellm.AuthEnvVarName(kind, name+"_"+header.Name),
  222. ValueFrom: &corev1.EnvVarSource{
  223. SecretKeyRef: &corev1.SecretKeySelector{
  224. LocalObjectReference: header.ValueFrom.SecretKeyRef.LocalObjectReference,
  225. Key: header.ValueFrom.SecretKeyRef.Key,
  226. },
  227. },
  228. })
  229. }
  230. }
  231. }
  232. }
  233. }
  234. tmpl.Spec.Runtime.Env = append(tmpl.Spec.Runtime.Env, envVars...)
  235. }