types.go 10 KB

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