types.go 8.5 KB

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