types.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "math"
  7. "os"
  8. "reflect"
  9. "strings"
  10. "time"
  11. )
  12. type StatusError struct {
  13. StatusCode int
  14. Status string
  15. ErrorMessage string `json:"error"`
  16. }
  17. func (e StatusError) Error() string {
  18. switch {
  19. case e.Status != "" && e.ErrorMessage != "":
  20. return fmt.Sprintf("%s: %s", e.Status, e.ErrorMessage)
  21. case e.Status != "":
  22. return e.Status
  23. case e.ErrorMessage != "":
  24. return e.ErrorMessage
  25. default:
  26. // this should not happen
  27. return "something went wrong, please see the ollama server logs for details"
  28. }
  29. }
  30. type GenerateRequest struct {
  31. Model string `json:"model"`
  32. Prompt string `json:"prompt"`
  33. System string `json:"system"`
  34. Template string `json:"template"`
  35. Context []int `json:"context,omitempty"`
  36. Options map[string]interface{} `json:"options"`
  37. }
  38. type EmbeddingRequest struct {
  39. Model string `json:"model"`
  40. Prompt string `json:"prompt"`
  41. Options map[string]interface{} `json:"options"`
  42. }
  43. type EmbeddingResponse struct {
  44. Embedding []float64 `json:"embedding"`
  45. }
  46. type CreateRequest struct {
  47. Name string `json:"name"`
  48. Path string `json:"path"`
  49. }
  50. type DeleteRequest struct {
  51. Name string `json:"name"`
  52. }
  53. type ShowRequest struct {
  54. Name string `json:"name"`
  55. }
  56. type ShowResponse struct {
  57. License string `json:"license,omitempty"`
  58. Modelfile string `json:"modelfile,omitempty"`
  59. Parameters string `json:"parameters,omitempty"`
  60. Template string `json:"template,omitempty"`
  61. System string `json:"system,omitempty"`
  62. }
  63. type CopyRequest struct {
  64. Source string `json:"source"`
  65. Destination string `json:"destination"`
  66. }
  67. type PullRequest struct {
  68. Name string `json:"name"`
  69. Insecure bool `json:"insecure,omitempty"`
  70. }
  71. type ProgressResponse struct {
  72. Status string `json:"status"`
  73. Digest string `json:"digest,omitempty"`
  74. Total int64 `json:"total,omitempty"`
  75. Completed int64 `json:"completed,omitempty"`
  76. }
  77. type PushRequest struct {
  78. Name string `json:"name"`
  79. Insecure bool `json:"insecure,omitempty"`
  80. }
  81. type ListResponse struct {
  82. Models []ModelResponse `json:"models"`
  83. }
  84. type ModelResponse struct {
  85. Name string `json:"name"`
  86. ModifiedAt time.Time `json:"modified_at"`
  87. Size int64 `json:"size"`
  88. Digest string `json:"digest"`
  89. }
  90. type TokenResponse struct {
  91. Token string `json:"token"`
  92. }
  93. type GenerateResponse struct {
  94. Model string `json:"model"`
  95. CreatedAt time.Time `json:"created_at"`
  96. Response string `json:"response,omitempty"`
  97. Done bool `json:"done"`
  98. Context []int `json:"context,omitempty"`
  99. TotalDuration time.Duration `json:"total_duration,omitempty"`
  100. LoadDuration time.Duration `json:"load_duration,omitempty"`
  101. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  102. PromptEvalDuration time.Duration `json:"prompt_eval_duration,omitempty"`
  103. EvalCount int `json:"eval_count,omitempty"`
  104. EvalDuration time.Duration `json:"eval_duration,omitempty"`
  105. }
  106. func (r *GenerateResponse) Summary() {
  107. if r.TotalDuration > 0 {
  108. fmt.Fprintf(os.Stderr, "total duration: %v\n", r.TotalDuration)
  109. }
  110. if r.LoadDuration > 0 {
  111. fmt.Fprintf(os.Stderr, "load duration: %v\n", r.LoadDuration)
  112. }
  113. if r.PromptEvalCount > 0 {
  114. fmt.Fprintf(os.Stderr, "prompt eval count: %d token(s)\n", r.PromptEvalCount)
  115. }
  116. if r.PromptEvalDuration > 0 {
  117. fmt.Fprintf(os.Stderr, "prompt eval duration: %s\n", r.PromptEvalDuration)
  118. fmt.Fprintf(os.Stderr, "prompt eval rate: %.2f tokens/s\n", float64(r.PromptEvalCount)/r.PromptEvalDuration.Seconds())
  119. }
  120. if r.EvalCount > 0 {
  121. fmt.Fprintf(os.Stderr, "eval count: %d token(s)\n", r.EvalCount)
  122. }
  123. if r.EvalDuration > 0 {
  124. fmt.Fprintf(os.Stderr, "eval duration: %s\n", r.EvalDuration)
  125. fmt.Fprintf(os.Stderr, "eval rate: %.2f tokens/s\n", float64(r.EvalCount)/r.EvalDuration.Seconds())
  126. }
  127. }
  128. type Options struct {
  129. Seed int `json:"seed,omitempty"`
  130. // Backend options
  131. UseNUMA bool `json:"numa,omitempty"`
  132. // Model options
  133. NumCtx int `json:"num_ctx,omitempty"`
  134. NumKeep int `json:"num_keep,omitempty"`
  135. NumBatch int `json:"num_batch,omitempty"`
  136. NumGQA int `json:"num_gqa,omitempty"`
  137. NumGPU int `json:"num_gpu,omitempty"`
  138. MainGPU int `json:"main_gpu,omitempty"`
  139. LowVRAM bool `json:"low_vram,omitempty"`
  140. F16KV bool `json:"f16_kv,omitempty"`
  141. LogitsAll bool `json:"logits_all,omitempty"`
  142. VocabOnly bool `json:"vocab_only,omitempty"`
  143. UseMMap bool `json:"use_mmap,omitempty"`
  144. UseMLock bool `json:"use_mlock,omitempty"`
  145. EmbeddingOnly bool `json:"embedding_only,omitempty"`
  146. RopeFrequencyBase float32 `json:"rope_frequency_base,omitempty"`
  147. RopeFrequencyScale float32 `json:"rope_frequency_scale,omitempty"`
  148. // Predict options
  149. NumPredict int `json:"num_predict,omitempty"`
  150. TopK int `json:"top_k,omitempty"`
  151. TopP float32 `json:"top_p,omitempty"`
  152. TFSZ float32 `json:"tfs_z,omitempty"`
  153. TypicalP float32 `json:"typical_p,omitempty"`
  154. RepeatLastN int `json:"repeat_last_n,omitempty"`
  155. Temperature float32 `json:"temperature,omitempty"`
  156. RepeatPenalty float32 `json:"repeat_penalty,omitempty"`
  157. PresencePenalty float32 `json:"presence_penalty,omitempty"`
  158. FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
  159. Mirostat int `json:"mirostat,omitempty"`
  160. MirostatTau float32 `json:"mirostat_tau,omitempty"`
  161. MirostatEta float32 `json:"mirostat_eta,omitempty"`
  162. PenalizeNewline bool `json:"penalize_newline,omitempty"`
  163. Stop []string `json:"stop,omitempty"`
  164. NumThread int `json:"num_thread,omitempty"`
  165. }
  166. func (opts *Options) FromMap(m map[string]interface{}) error {
  167. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  168. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  169. // build map of json struct tags to their types
  170. jsonOpts := make(map[string]reflect.StructField)
  171. for _, field := range reflect.VisibleFields(typeOpts) {
  172. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  173. if jsonTag != "" {
  174. jsonOpts[jsonTag] = field
  175. }
  176. }
  177. for key, val := range m {
  178. if opt, ok := jsonOpts[key]; ok {
  179. field := valueOpts.FieldByName(opt.Name)
  180. if field.IsValid() && field.CanSet() {
  181. if val == nil {
  182. continue
  183. }
  184. switch field.Kind() {
  185. case reflect.Int:
  186. switch t := val.(type) {
  187. case int64:
  188. field.SetInt(t)
  189. case float64:
  190. // when JSON unmarshals numbers, it uses float64, not int
  191. field.SetInt(int64(t))
  192. default:
  193. log.Printf("could not convert model parameter %v to int, skipped", key)
  194. }
  195. case reflect.Bool:
  196. val, ok := val.(bool)
  197. if !ok {
  198. log.Printf("could not convert model parameter %v to bool, skipped", key)
  199. continue
  200. }
  201. field.SetBool(val)
  202. case reflect.Float32:
  203. // JSON unmarshals to float64
  204. val, ok := val.(float64)
  205. if !ok {
  206. log.Printf("could not convert model parameter %v to float32, skipped", key)
  207. continue
  208. }
  209. field.SetFloat(val)
  210. case reflect.String:
  211. val, ok := val.(string)
  212. if !ok {
  213. log.Printf("could not convert model parameter %v to string, skipped", key)
  214. continue
  215. }
  216. field.SetString(val)
  217. case reflect.Slice:
  218. // JSON unmarshals to []interface{}, not []string
  219. val, ok := val.([]interface{})
  220. if !ok {
  221. log.Printf("could not convert model parameter %v to slice, skipped", key)
  222. continue
  223. }
  224. // convert []interface{} to []string
  225. slice := make([]string, len(val))
  226. for i, item := range val {
  227. str, ok := item.(string)
  228. if !ok {
  229. log.Printf("could not convert model parameter %v to slice of strings, skipped", key)
  230. continue
  231. }
  232. slice[i] = str
  233. }
  234. field.Set(reflect.ValueOf(slice))
  235. default:
  236. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  237. }
  238. }
  239. }
  240. }
  241. return nil
  242. }
  243. func DefaultOptions() Options {
  244. return Options{
  245. Seed: -1,
  246. UseNUMA: false,
  247. NumCtx: 2048,
  248. NumKeep: -1,
  249. NumBatch: 512,
  250. NumGPU: -1, // -1 here indicates that NumGPU should be set dynamically
  251. NumGQA: 1,
  252. LowVRAM: false,
  253. F16KV: true,
  254. UseMMap: true,
  255. UseMLock: false,
  256. RopeFrequencyBase: 10000.0,
  257. RopeFrequencyScale: 1.0,
  258. EmbeddingOnly: true,
  259. RepeatLastN: 64,
  260. RepeatPenalty: 1.1,
  261. FrequencyPenalty: 0.0,
  262. PresencePenalty: 0.0,
  263. Temperature: 0.8,
  264. TopK: 40,
  265. TopP: 0.9,
  266. TFSZ: 1.0,
  267. TypicalP: 1.0,
  268. Mirostat: 0,
  269. MirostatTau: 5.0,
  270. MirostatEta: 0.1,
  271. PenalizeNewline: true,
  272. NumThread: 0, // let the runtime decide
  273. }
  274. }
  275. type Duration struct {
  276. time.Duration
  277. }
  278. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  279. var v any
  280. if err := json.Unmarshal(b, &v); err != nil {
  281. return err
  282. }
  283. d.Duration = 5 * time.Minute
  284. switch t := v.(type) {
  285. case float64:
  286. if t < 0 {
  287. t = math.MaxFloat64
  288. }
  289. d.Duration = time.Duration(t)
  290. case string:
  291. d.Duration, err = time.ParseDuration(t)
  292. if err != nil {
  293. return err
  294. }
  295. }
  296. return nil
  297. }