model.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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 compose
  14. import (
  15. "bufio"
  16. "context"
  17. "encoding/json"
  18. "fmt"
  19. "os/exec"
  20. "slices"
  21. "strconv"
  22. "strings"
  23. "github.com/compose-spec/compose-go/v2/types"
  24. "github.com/containerd/errdefs"
  25. "github.com/docker/cli/cli-plugins/manager"
  26. "github.com/docker/compose/v2/pkg/api"
  27. "github.com/spf13/cobra"
  28. "golang.org/x/sync/errgroup"
  29. )
  30. func (s *composeService) ensureModels(ctx context.Context, project *types.Project, quietPull bool) error {
  31. if len(project.Models) == 0 {
  32. return nil
  33. }
  34. api, err := s.newModelAPI(project)
  35. if err != nil {
  36. return err
  37. }
  38. defer api.Close()
  39. availableModels, err := api.ListModels(ctx)
  40. eg, ctx := errgroup.WithContext(ctx)
  41. eg.Go(func() error {
  42. return api.SetModelVariables(ctx, project)
  43. })
  44. for name, config := range project.Models {
  45. if config.Name == "" {
  46. config.Name = name
  47. }
  48. eg.Go(func() error {
  49. if !slices.Contains(availableModels, config.Model) {
  50. err = api.PullModel(ctx, config, quietPull, s.events)
  51. if err != nil {
  52. return err
  53. }
  54. }
  55. return api.ConfigureModel(ctx, config, s.events)
  56. })
  57. }
  58. return eg.Wait()
  59. }
  60. type modelAPI struct {
  61. path string
  62. env []string
  63. prepare func(ctx context.Context, cmd *exec.Cmd) error
  64. cleanup func()
  65. }
  66. func (s *composeService) newModelAPI(project *types.Project) (*modelAPI, error) {
  67. dockerModel, err := manager.GetPlugin("model", s.dockerCli, &cobra.Command{})
  68. if err != nil {
  69. if errdefs.IsNotFound(err) {
  70. return nil, fmt.Errorf("'models' support requires Docker Model plugin")
  71. }
  72. return nil, err
  73. }
  74. endpoint, cleanup, err := s.propagateDockerEndpoint()
  75. if err != nil {
  76. return nil, err
  77. }
  78. return &modelAPI{
  79. path: dockerModel.Path,
  80. prepare: func(ctx context.Context, cmd *exec.Cmd) error {
  81. return s.prepareShellOut(ctx, project.Environment, cmd)
  82. },
  83. cleanup: cleanup,
  84. env: append(project.Environment.Values(), endpoint...),
  85. }, nil
  86. }
  87. func (m *modelAPI) Close() {
  88. m.cleanup()
  89. }
  90. func (m *modelAPI) PullModel(ctx context.Context, model types.ModelConfig, quietPull bool, events api.EventProcessor) error {
  91. events.On(api.Resource{
  92. ID: model.Name,
  93. Status: api.Working,
  94. Text: "Pulling",
  95. })
  96. cmd := exec.CommandContext(ctx, m.path, "pull", model.Model)
  97. err := m.prepare(ctx, cmd)
  98. if err != nil {
  99. return err
  100. }
  101. stream, err := cmd.StdoutPipe()
  102. if err != nil {
  103. return err
  104. }
  105. err = cmd.Start()
  106. if err != nil {
  107. return err
  108. }
  109. scanner := bufio.NewScanner(stream)
  110. for scanner.Scan() {
  111. msg := scanner.Text()
  112. if msg == "" {
  113. continue
  114. }
  115. if !quietPull {
  116. events.On(api.Resource{
  117. ID: model.Name,
  118. Status: api.Working,
  119. Text: api.StatusPulling,
  120. })
  121. }
  122. }
  123. err = cmd.Wait()
  124. if err != nil {
  125. events.On(errorEvent(model.Name, err.Error()))
  126. }
  127. events.On(api.Resource{
  128. ID: model.Name,
  129. Status: api.Working,
  130. Text: api.StatusPulled,
  131. })
  132. return err
  133. }
  134. func (m *modelAPI) ConfigureModel(ctx context.Context, config types.ModelConfig, events api.EventProcessor) error {
  135. events.On(api.Resource{
  136. ID: config.Name,
  137. Status: api.Working,
  138. Text: "Configuring",
  139. })
  140. // configure [--context-size=<n>] MODEL [-- <runtime-flags...>]
  141. args := []string{"configure"}
  142. if config.ContextSize > 0 {
  143. args = append(args, "--context-size", strconv.Itoa(config.ContextSize))
  144. }
  145. args = append(args, config.Model)
  146. if len(config.RuntimeFlags) != 0 {
  147. args = append(args, "--")
  148. args = append(args, config.RuntimeFlags...)
  149. }
  150. cmd := exec.CommandContext(ctx, m.path, args...)
  151. err := m.prepare(ctx, cmd)
  152. if err != nil {
  153. return err
  154. }
  155. return cmd.Run()
  156. }
  157. func (m *modelAPI) SetModelVariables(ctx context.Context, project *types.Project) error {
  158. cmd := exec.CommandContext(ctx, m.path, "status", "--json")
  159. err := m.prepare(ctx, cmd)
  160. if err != nil {
  161. return err
  162. }
  163. statusOut, err := cmd.CombinedOutput()
  164. if err != nil {
  165. return fmt.Errorf("error checking docker-model status: %w", err)
  166. }
  167. type Status struct {
  168. Endpoint string `json:"endpoint"`
  169. }
  170. var status Status
  171. err = json.Unmarshal(statusOut, &status)
  172. if err != nil {
  173. return err
  174. }
  175. for _, service := range project.Services {
  176. for ref, modelConfig := range service.Models {
  177. model := project.Models[ref]
  178. varPrefix := strings.ReplaceAll(strings.ToUpper(ref), "-", "_")
  179. var variable string
  180. if modelConfig != nil && modelConfig.ModelVariable != "" {
  181. variable = modelConfig.ModelVariable
  182. } else {
  183. variable = varPrefix + "_MODEL"
  184. }
  185. service.Environment[variable] = &model.Model
  186. if modelConfig != nil && modelConfig.EndpointVariable != "" {
  187. variable = modelConfig.EndpointVariable
  188. } else {
  189. variable = varPrefix + "_URL"
  190. }
  191. service.Environment[variable] = &status.Endpoint
  192. }
  193. }
  194. return nil
  195. }
  196. type Model struct {
  197. Id string `json:"id"`
  198. Tags []string `json:"tags"`
  199. Created int `json:"created"`
  200. Config struct {
  201. Format string `json:"format"`
  202. Quantization string `json:"quantization"`
  203. Parameters string `json:"parameters"`
  204. Architecture string `json:"architecture"`
  205. Size string `json:"size"`
  206. } `json:"config"`
  207. }
  208. func (m *modelAPI) ListModels(ctx context.Context) ([]string, error) {
  209. cmd := exec.CommandContext(ctx, m.path, "ls", "--json")
  210. err := m.prepare(ctx, cmd)
  211. if err != nil {
  212. return nil, err
  213. }
  214. output, err := cmd.CombinedOutput()
  215. if err != nil {
  216. return nil, fmt.Errorf("error checking available models: %w", err)
  217. }
  218. type AvailableModel struct {
  219. Id string `json:"id"`
  220. Tags []string `json:"tags"`
  221. Created int `json:"created"`
  222. }
  223. models := []AvailableModel{}
  224. err = json.Unmarshal(output, &models)
  225. if err != nil {
  226. return nil, fmt.Errorf("error unmarshalling available models: %w", err)
  227. }
  228. var availableModels []string
  229. for _, model := range models {
  230. availableModels = append(availableModels, model.Tags...)
  231. }
  232. return availableModels, nil
  233. }