types.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math"
  6. "os"
  7. "reflect"
  8. "strings"
  9. "time"
  10. )
  11. type StatusError struct {
  12. StatusCode int
  13. Status string
  14. ErrorMessage string `json:"error"`
  15. }
  16. func (e StatusError) Error() string {
  17. switch {
  18. case e.Status != "" && e.ErrorMessage != "":
  19. return fmt.Sprintf("%s: %s", e.Status, e.ErrorMessage)
  20. case e.Status != "":
  21. return e.Status
  22. case e.ErrorMessage != "":
  23. return e.ErrorMessage
  24. default:
  25. // this should not happen
  26. return "something went wrong, please see the ollama server logs for details"
  27. }
  28. }
  29. type GenerateRequest struct {
  30. Model string `json:"model"`
  31. Prompt string `json:"prompt"`
  32. System string `json:"system"`
  33. Template string `json:"template"`
  34. Context []int `json:"context,omitempty"`
  35. Stream *bool `json:"stream,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. Stream *bool `json:"stream,omitempty"`
  50. }
  51. type DeleteRequest struct {
  52. Name string `json:"name"`
  53. }
  54. type ShowRequest struct {
  55. Name string `json:"name"`
  56. }
  57. type ShowResponse struct {
  58. License string `json:"license,omitempty"`
  59. Modelfile string `json:"modelfile,omitempty"`
  60. Parameters string `json:"parameters,omitempty"`
  61. Template string `json:"template,omitempty"`
  62. System string `json:"system,omitempty"`
  63. }
  64. type CopyRequest struct {
  65. Source string `json:"source"`
  66. Destination string `json:"destination"`
  67. }
  68. type PullRequest struct {
  69. Name string `json:"name"`
  70. Insecure bool `json:"insecure,omitempty"`
  71. Username string `json:"username"`
  72. Password string `json:"password"`
  73. Stream *bool `json:"stream,omitempty"`
  74. }
  75. type ProgressResponse struct {
  76. Status string `json:"status"`
  77. Digest string `json:"digest,omitempty"`
  78. Total int64 `json:"total,omitempty"`
  79. Completed int64 `json:"completed,omitempty"`
  80. }
  81. type PushRequest struct {
  82. Name string `json:"name"`
  83. Insecure bool `json:"insecure,omitempty"`
  84. Username string `json:"username"`
  85. Password string `json:"password"`
  86. Stream *bool `json:"stream,omitempty"`
  87. }
  88. type ListResponse struct {
  89. Models []ModelResponse `json:"models"`
  90. }
  91. type ModelResponse struct {
  92. Name string `json:"name"`
  93. ModifiedAt time.Time `json:"modified_at"`
  94. Size int64 `json:"size"`
  95. Digest string `json:"digest"`
  96. }
  97. type TokenResponse struct {
  98. Token string `json:"token"`
  99. }
  100. type GenerateResponse struct {
  101. Model string `json:"model"`
  102. CreatedAt time.Time `json:"created_at"`
  103. Response string `json:"response"`
  104. Done bool `json:"done"`
  105. Context []int `json:"context,omitempty"`
  106. TotalDuration time.Duration `json:"total_duration,omitempty"`
  107. LoadDuration time.Duration `json:"load_duration,omitempty"`
  108. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  109. PromptEvalDuration time.Duration `json:"prompt_eval_duration,omitempty"`
  110. EvalCount int `json:"eval_count,omitempty"`
  111. EvalDuration time.Duration `json:"eval_duration,omitempty"`
  112. }
  113. func (r *GenerateResponse) Summary() {
  114. if r.TotalDuration > 0 {
  115. fmt.Fprintf(os.Stderr, "total duration: %v\n", r.TotalDuration)
  116. }
  117. if r.LoadDuration > 0 {
  118. fmt.Fprintf(os.Stderr, "load duration: %v\n", r.LoadDuration)
  119. }
  120. if r.PromptEvalCount > 0 {
  121. fmt.Fprintf(os.Stderr, "prompt eval count: %d token(s)\n", r.PromptEvalCount)
  122. }
  123. if r.PromptEvalDuration > 0 {
  124. fmt.Fprintf(os.Stderr, "prompt eval duration: %s\n", r.PromptEvalDuration)
  125. fmt.Fprintf(os.Stderr, "prompt eval rate: %.2f tokens/s\n", float64(r.PromptEvalCount)/r.PromptEvalDuration.Seconds())
  126. }
  127. if r.EvalCount > 0 {
  128. fmt.Fprintf(os.Stderr, "eval count: %d token(s)\n", r.EvalCount)
  129. }
  130. if r.EvalDuration > 0 {
  131. fmt.Fprintf(os.Stderr, "eval duration: %s\n", r.EvalDuration)
  132. fmt.Fprintf(os.Stderr, "eval rate: %.2f tokens/s\n", float64(r.EvalCount)/r.EvalDuration.Seconds())
  133. }
  134. }
  135. // Runner options which must be set when the model is loaded into memory
  136. type Runner struct {
  137. UseNUMA bool `json:"numa,omitempty"`
  138. NumCtx int `json:"num_ctx,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. NumThread int `json:"num_thread,omitempty"`
  153. }
  154. type Options struct {
  155. Runner
  156. // Predict options used at runtime
  157. NumKeep int `json:"num_keep,omitempty"`
  158. Seed int `json:"seed,omitempty"`
  159. NumPredict int `json:"num_predict,omitempty"`
  160. TopK int `json:"top_k,omitempty"`
  161. TopP float32 `json:"top_p,omitempty"`
  162. TFSZ float32 `json:"tfs_z,omitempty"`
  163. TypicalP float32 `json:"typical_p,omitempty"`
  164. RepeatLastN int `json:"repeat_last_n,omitempty"`
  165. Temperature float32 `json:"temperature,omitempty"`
  166. RepeatPenalty float32 `json:"repeat_penalty,omitempty"`
  167. PresencePenalty float32 `json:"presence_penalty,omitempty"`
  168. FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
  169. Mirostat int `json:"mirostat,omitempty"`
  170. MirostatTau float32 `json:"mirostat_tau,omitempty"`
  171. MirostatEta float32 `json:"mirostat_eta,omitempty"`
  172. PenalizeNewline bool `json:"penalize_newline,omitempty"`
  173. Stop []string `json:"stop,omitempty"`
  174. }
  175. var ErrInvalidOpts = fmt.Errorf("invalid options")
  176. func (opts *Options) FromMap(m map[string]interface{}) error {
  177. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  178. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  179. // build map of json struct tags to their types
  180. jsonOpts := make(map[string]reflect.StructField)
  181. for _, field := range reflect.VisibleFields(typeOpts) {
  182. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  183. if jsonTag != "" {
  184. jsonOpts[jsonTag] = field
  185. }
  186. }
  187. invalidOpts := []string{}
  188. for key, val := range m {
  189. if opt, ok := jsonOpts[key]; ok {
  190. field := valueOpts.FieldByName(opt.Name)
  191. if field.IsValid() && field.CanSet() {
  192. if val == nil {
  193. continue
  194. }
  195. switch field.Kind() {
  196. case reflect.Int:
  197. switch t := val.(type) {
  198. case int64:
  199. field.SetInt(t)
  200. case float64:
  201. // when JSON unmarshals numbers, it uses float64, not int
  202. field.SetInt(int64(t))
  203. default:
  204. return fmt.Errorf("option %q must be of type integer", key)
  205. }
  206. case reflect.Bool:
  207. val, ok := val.(bool)
  208. if !ok {
  209. return fmt.Errorf("option %q must be of type boolean", key)
  210. }
  211. field.SetBool(val)
  212. case reflect.Float32:
  213. // JSON unmarshals to float64
  214. val, ok := val.(float64)
  215. if !ok {
  216. return fmt.Errorf("option %q must be of type float32", key)
  217. }
  218. field.SetFloat(val)
  219. case reflect.String:
  220. val, ok := val.(string)
  221. if !ok {
  222. return fmt.Errorf("option %q must be of type string", key)
  223. }
  224. field.SetString(val)
  225. case reflect.Slice:
  226. // JSON unmarshals to []interface{}, not []string
  227. val, ok := val.([]interface{})
  228. if !ok {
  229. return fmt.Errorf("option %q must be of type array", key)
  230. }
  231. // convert []interface{} to []string
  232. slice := make([]string, len(val))
  233. for i, item := range val {
  234. str, ok := item.(string)
  235. if !ok {
  236. return fmt.Errorf("option %q must be of an array of strings", key)
  237. }
  238. slice[i] = str
  239. }
  240. field.Set(reflect.ValueOf(slice))
  241. default:
  242. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  243. }
  244. }
  245. } else {
  246. invalidOpts = append(invalidOpts, key)
  247. }
  248. }
  249. if len(invalidOpts) > 0 {
  250. return fmt.Errorf("%w: %v", ErrInvalidOpts, strings.Join(invalidOpts, ", "))
  251. }
  252. return nil
  253. }
  254. func DefaultOptions() Options {
  255. return Options{
  256. // options set on request to runner
  257. NumPredict: -1,
  258. NumKeep: -1,
  259. Temperature: 0.8,
  260. TopK: 40,
  261. TopP: 0.9,
  262. TFSZ: 1.0,
  263. TypicalP: 1.0,
  264. RepeatLastN: 64,
  265. RepeatPenalty: 1.1,
  266. PresencePenalty: 0.0,
  267. FrequencyPenalty: 0.0,
  268. Mirostat: 0,
  269. MirostatTau: 5.0,
  270. MirostatEta: 0.1,
  271. PenalizeNewline: true,
  272. Seed: -1,
  273. Runner: Runner{
  274. // options set when the model is loaded
  275. NumCtx: 2048,
  276. RopeFrequencyBase: 10000.0,
  277. RopeFrequencyScale: 1.0,
  278. NumBatch: 512,
  279. NumGPU: -1, // -1 here indicates that NumGPU should be set dynamically
  280. NumGQA: 1,
  281. NumThread: 0, // let the runtime decide
  282. LowVRAM: false,
  283. F16KV: true,
  284. UseMLock: false,
  285. UseMMap: true,
  286. UseNUMA: false,
  287. EmbeddingOnly: true,
  288. },
  289. }
  290. }
  291. type Duration struct {
  292. time.Duration
  293. }
  294. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  295. var v any
  296. if err := json.Unmarshal(b, &v); err != nil {
  297. return err
  298. }
  299. d.Duration = 5 * time.Minute
  300. switch t := v.(type) {
  301. case float64:
  302. if t < 0 {
  303. t = math.MaxFloat64
  304. }
  305. d.Duration = time.Duration(t)
  306. case string:
  307. d.Duration, err = time.ParseDuration(t)
  308. if err != nil {
  309. return err
  310. }
  311. }
  312. return nil
  313. }