types.go 9.1 KB

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