types.go 9.0 KB

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