types.go 9.4 KB

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