types.go 14 KB

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