types.go 9.0 KB

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