types.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. RopeFrequencyBase float32 `json:"rope_frequency_base,omitempty"`
  137. RopeFrequencyScale float32 `json:"rope_frequency_scale,omitempty"`
  138. // Predict options
  139. RepeatLastN int `json:"repeat_last_n,omitempty"`
  140. RepeatPenalty float32 `json:"repeat_penalty,omitempty"`
  141. FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
  142. PresencePenalty float32 `json:"presence_penalty,omitempty"`
  143. Temperature float32 `json:"temperature,omitempty"`
  144. TopK int `json:"top_k,omitempty"`
  145. TopP float32 `json:"top_p,omitempty"`
  146. TFSZ float32 `json:"tfs_z,omitempty"`
  147. TypicalP float32 `json:"typical_p,omitempty"`
  148. Mirostat int `json:"mirostat,omitempty"`
  149. MirostatTau float32 `json:"mirostat_tau,omitempty"`
  150. MirostatEta float32 `json:"mirostat_eta,omitempty"`
  151. PenalizeNewline bool `json:"penalize_newline,omitempty"`
  152. Stop []string `json:"stop,omitempty"`
  153. NumThread int `json:"num_thread,omitempty"`
  154. }
  155. func (opts *Options) FromMap(m map[string]interface{}) error {
  156. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  157. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  158. // build map of json struct tags to their types
  159. jsonOpts := make(map[string]reflect.StructField)
  160. for _, field := range reflect.VisibleFields(typeOpts) {
  161. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  162. if jsonTag != "" {
  163. jsonOpts[jsonTag] = field
  164. }
  165. }
  166. for key, val := range m {
  167. if opt, ok := jsonOpts[key]; ok {
  168. field := valueOpts.FieldByName(opt.Name)
  169. if field.IsValid() && field.CanSet() {
  170. switch field.Kind() {
  171. case reflect.Int:
  172. // when JSON unmarshals numbers, it uses float64 by default, not int
  173. val, ok := val.(float64)
  174. if !ok {
  175. log.Printf("could not convert model parmeter %v to int, skipped", key)
  176. continue
  177. }
  178. field.SetInt(int64(val))
  179. case reflect.Bool:
  180. val, ok := val.(bool)
  181. if !ok {
  182. log.Printf("could not convert model parmeter %v to bool, skipped", key)
  183. continue
  184. }
  185. field.SetBool(val)
  186. case reflect.Float32:
  187. // JSON unmarshals to float64
  188. val, ok := val.(float64)
  189. if !ok {
  190. log.Printf("could not convert model parmeter %v to float32, skipped", key)
  191. continue
  192. }
  193. field.SetFloat(val)
  194. case reflect.String:
  195. val, ok := val.(string)
  196. if !ok {
  197. log.Printf("could not convert model parmeter %v to string, skipped", key)
  198. continue
  199. }
  200. field.SetString(val)
  201. case reflect.Slice:
  202. // JSON unmarshals to []interface{}, not []string
  203. val, ok := val.([]interface{})
  204. if !ok {
  205. log.Printf("could not convert model parmeter %v to slice, skipped", key)
  206. continue
  207. }
  208. // convert []interface{} to []string
  209. slice := make([]string, len(val))
  210. for i, item := range val {
  211. str, ok := item.(string)
  212. if !ok {
  213. log.Printf("could not convert model parmeter %v to slice of strings, skipped", key)
  214. continue
  215. }
  216. slice[i] = str
  217. }
  218. field.Set(reflect.ValueOf(slice))
  219. default:
  220. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  221. }
  222. }
  223. }
  224. }
  225. return nil
  226. }
  227. func DefaultOptions() Options {
  228. return Options{
  229. Seed: -1,
  230. UseNUMA: false,
  231. NumCtx: 2048,
  232. NumBatch: 512,
  233. NumGPU: 1,
  234. NumGQA: 1,
  235. LowVRAM: false,
  236. F16KV: true,
  237. UseMMap: true,
  238. UseMLock: false,
  239. RopeFrequencyBase: 10000.0,
  240. RopeFrequencyScale: 1.0,
  241. RepeatLastN: 64,
  242. RepeatPenalty: 1.1,
  243. FrequencyPenalty: 0.0,
  244. PresencePenalty: 0.0,
  245. Temperature: 0.8,
  246. TopK: 40,
  247. TopP: 0.9,
  248. TFSZ: 1.0,
  249. TypicalP: 1.0,
  250. Mirostat: 0,
  251. MirostatTau: 5.0,
  252. MirostatEta: 0.1,
  253. PenalizeNewline: true,
  254. NumThread: runtime.NumCPU(),
  255. }
  256. }
  257. type Duration struct {
  258. time.Duration
  259. }
  260. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  261. var v any
  262. if err := json.Unmarshal(b, &v); err != nil {
  263. return err
  264. }
  265. d.Duration = 5 * time.Minute
  266. switch t := v.(type) {
  267. case float64:
  268. if t < 0 {
  269. t = math.MaxFloat64
  270. }
  271. d.Duration = time.Duration(t)
  272. case string:
  273. d.Duration, err = time.ParseDuration(t)
  274. if err != nil {
  275. return err
  276. }
  277. }
  278. return nil
  279. }