types.go 12 KB

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