model.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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/progress"
  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 progress.EventProcessor) error {
  91. events.On(progress.Event{
  92. ID: model.Name,
  93. Status: progress.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(progress.Event{
  117. ID: model.Name,
  118. Status: progress.Working,
  119. Text: "Pulling",
  120. StatusText: msg,
  121. })
  122. }
  123. }
  124. err = cmd.Wait()
  125. if err != nil {
  126. events.On(progress.ErrorMessageEvent(model.Name, err.Error()))
  127. }
  128. events.On(progress.Event{
  129. ID: model.Name,
  130. Status: progress.Working,
  131. Text: "Pulled",
  132. })
  133. return err
  134. }
  135. func (m *modelAPI) ConfigureModel(ctx context.Context, config types.ModelConfig, events progress.EventProcessor) error {
  136. events.On(progress.Event{
  137. ID: config.Name,
  138. Status: progress.Working,
  139. Text: "Configuring",
  140. })
  141. // configure [--context-size=<n>] MODEL [-- <runtime-flags...>]
  142. args := []string{"configure"}
  143. if config.ContextSize > 0 {
  144. args = append(args, "--context-size", strconv.Itoa(config.ContextSize))
  145. }
  146. args = append(args, config.Model)
  147. if len(config.RuntimeFlags) != 0 {
  148. args = append(args, "--")
  149. args = append(args, config.RuntimeFlags...)
  150. }
  151. cmd := exec.CommandContext(ctx, m.path, args...)
  152. err := m.prepare(ctx, cmd)
  153. if err != nil {
  154. return err
  155. }
  156. return cmd.Run()
  157. }
  158. func (m *modelAPI) SetModelVariables(ctx context.Context, project *types.Project) error {
  159. cmd := exec.CommandContext(ctx, m.path, "status", "--json")
  160. err := m.prepare(ctx, cmd)
  161. if err != nil {
  162. return err
  163. }
  164. statusOut, err := cmd.CombinedOutput()
  165. if err != nil {
  166. return fmt.Errorf("error checking docker-model status: %w", err)
  167. }
  168. type Status struct {
  169. Endpoint string `json:"endpoint"`
  170. }
  171. var status Status
  172. err = json.Unmarshal(statusOut, &status)
  173. if err != nil {
  174. return err
  175. }
  176. for _, service := range project.Services {
  177. for ref, modelConfig := range service.Models {
  178. model := project.Models[ref]
  179. varPrefix := strings.ReplaceAll(strings.ToUpper(ref), "-", "_")
  180. var variable string
  181. if modelConfig != nil && modelConfig.ModelVariable != "" {
  182. variable = modelConfig.ModelVariable
  183. } else {
  184. variable = varPrefix + "_MODEL"
  185. }
  186. service.Environment[variable] = &model.Model
  187. if modelConfig != nil && modelConfig.EndpointVariable != "" {
  188. variable = modelConfig.EndpointVariable
  189. } else {
  190. variable = varPrefix + "_URL"
  191. }
  192. service.Environment[variable] = &status.Endpoint
  193. }
  194. }
  195. return nil
  196. }
  197. type Model struct {
  198. Id string `json:"id"`
  199. Tags []string `json:"tags"`
  200. Created int `json:"created"`
  201. Config struct {
  202. Format string `json:"format"`
  203. Quantization string `json:"quantization"`
  204. Parameters string `json:"parameters"`
  205. Architecture string `json:"architecture"`
  206. Size string `json:"size"`
  207. } `json:"config"`
  208. }
  209. func (m *modelAPI) ListModels(ctx context.Context) ([]string, error) {
  210. cmd := exec.CommandContext(ctx, m.path, "ls", "--json")
  211. err := m.prepare(ctx, cmd)
  212. if err != nil {
  213. return nil, err
  214. }
  215. output, err := cmd.CombinedOutput()
  216. if err != nil {
  217. return nil, fmt.Errorf("error checking available models: %w", err)
  218. }
  219. type AvailableModel struct {
  220. Id string `json:"id"`
  221. Tags []string `json:"tags"`
  222. Created int `json:"created"`
  223. }
  224. models := []AvailableModel{}
  225. err = json.Unmarshal(output, &models)
  226. if err != nil {
  227. return nil, fmt.Errorf("error unmarshalling available models: %w", err)
  228. }
  229. var availableModels []string
  230. for _, model := range models {
  231. availableModels = append(availableModels, model.Tags...)
  232. }
  233. return availableModels, nil
  234. }