model.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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/v5/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. mdlAPI, err := s.newModelAPI(project)
  35. if err != nil {
  36. return err
  37. }
  38. defer mdlAPI.Close()
  39. availableModels, err := mdlAPI.ListModels(ctx)
  40. eg, ctx := errgroup.WithContext(ctx)
  41. eg.Go(func() error {
  42. return mdlAPI.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 = mdlAPI.PullModel(ctx, config, quietPull, s.events)
  51. if err != nil {
  52. return err
  53. }
  54. }
  55. return mdlAPI.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. if len(config.RuntimeFlags) != 0 {
  136. return fmt.Errorf("runtime flags are not supported for model configuration")
  137. }
  138. events.On(api.Resource{
  139. ID: config.Name,
  140. Status: api.Working,
  141. Text: "Configuring",
  142. })
  143. // configure [--context-size=<n>] MODEL [-- <runtime-flags...>]
  144. args := []string{"configure"}
  145. if config.ContextSize > 0 {
  146. args = append(args, "--context-size", strconv.Itoa(config.ContextSize))
  147. }
  148. args = append(args, config.Model)
  149. if len(config.RuntimeFlags) != 0 {
  150. args = append(args, "--")
  151. args = append(args, config.RuntimeFlags...)
  152. }
  153. cmd := exec.CommandContext(ctx, m.path, args...)
  154. err := m.prepare(ctx, cmd)
  155. if err != nil {
  156. return err
  157. }
  158. return cmd.Run()
  159. }
  160. func (m *modelAPI) SetModelVariables(ctx context.Context, project *types.Project) error {
  161. cmd := exec.CommandContext(ctx, m.path, "status", "--json")
  162. err := m.prepare(ctx, cmd)
  163. if err != nil {
  164. return err
  165. }
  166. statusOut, err := cmd.CombinedOutput()
  167. if err != nil {
  168. return fmt.Errorf("error checking docker-model status: %w", err)
  169. }
  170. type Status struct {
  171. Endpoint string `json:"endpoint"`
  172. }
  173. var status Status
  174. err = json.Unmarshal(statusOut, &status)
  175. if err != nil {
  176. return err
  177. }
  178. for _, service := range project.Services {
  179. for ref, modelConfig := range service.Models {
  180. model := project.Models[ref]
  181. varPrefix := strings.ReplaceAll(strings.ToUpper(ref), "-", "_")
  182. var variable string
  183. if modelConfig != nil && modelConfig.ModelVariable != "" {
  184. variable = modelConfig.ModelVariable
  185. } else {
  186. variable = varPrefix + "_MODEL"
  187. }
  188. service.Environment[variable] = &model.Model
  189. if modelConfig != nil && modelConfig.EndpointVariable != "" {
  190. variable = modelConfig.EndpointVariable
  191. } else {
  192. variable = varPrefix + "_URL"
  193. }
  194. service.Environment[variable] = &status.Endpoint
  195. }
  196. }
  197. return nil
  198. }
  199. type Model struct {
  200. Id string `json:"id"`
  201. Tags []string `json:"tags"`
  202. Created int `json:"created"`
  203. Config struct {
  204. Format string `json:"format"`
  205. Quantization string `json:"quantization"`
  206. Parameters string `json:"parameters"`
  207. Architecture string `json:"architecture"`
  208. Size string `json:"size"`
  209. } `json:"config"`
  210. }
  211. func (m *modelAPI) ListModels(ctx context.Context) ([]string, error) {
  212. cmd := exec.CommandContext(ctx, m.path, "ls", "--json")
  213. err := m.prepare(ctx, cmd)
  214. if err != nil {
  215. return nil, err
  216. }
  217. output, err := cmd.CombinedOutput()
  218. if err != nil {
  219. return nil, fmt.Errorf("error checking available models: %w", err)
  220. }
  221. type AvailableModel struct {
  222. Id string `json:"id"`
  223. Tags []string `json:"tags"`
  224. Created int `json:"created"`
  225. }
  226. models := []AvailableModel{}
  227. err = json.Unmarshal(output, &models)
  228. if err != nil {
  229. return nil, fmt.Errorf("error unmarshalling available models: %w", err)
  230. }
  231. var availableModels []string
  232. for _, model := range models {
  233. availableModels = append(availableModels, model.Tags...)
  234. }
  235. return availableModels, nil
  236. }