types.go 9.4 KB

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