types.go 9.3 KB

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