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 specified 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. NumThread int `json:"num_thread,omitempty"`
  109. // Unused: RopeFrequencyBase is ignored. Instead the value in the model will be used
  110. RopeFrequencyBase float32 `json:"rope_frequency_base,omitempty"`
  111. // Unused: RopeFrequencyScale is ignored. Instead the value in the model will be used
  112. RopeFrequencyScale float32 `json:"rope_frequency_scale,omitempty"`
  113. }
  114. type EmbeddingRequest struct {
  115. Model string `json:"model"`
  116. Prompt string `json:"prompt"`
  117. KeepAlive *Duration `json:"keep_alive,omitempty"`
  118. Options map[string]interface{} `json:"options"`
  119. }
  120. type EmbeddingResponse struct {
  121. Embedding []float64 `json:"embedding"`
  122. }
  123. type CreateRequest struct {
  124. Model string `json:"model"`
  125. Path string `json:"path"`
  126. Modelfile string `json:"modelfile"`
  127. Stream *bool `json:"stream,omitempty"`
  128. Quantization string `json:"quantization,omitempty"`
  129. // Name is deprecated, see Model
  130. Name string `json:"name"`
  131. }
  132. type DeleteRequest struct {
  133. Model string `json:"model"`
  134. // Name is deprecated, see Model
  135. Name string `json:"name"`
  136. }
  137. type ShowRequest struct {
  138. Model string `json:"model"`
  139. System string `json:"system"`
  140. Template string `json:"template"`
  141. Options map[string]interface{} `json:"options"`
  142. // Name is deprecated, see Model
  143. Name string `json:"name"`
  144. }
  145. type ShowResponse struct {
  146. License string `json:"license,omitempty"`
  147. Modelfile string `json:"modelfile,omitempty"`
  148. Parameters string `json:"parameters,omitempty"`
  149. Template string `json:"template,omitempty"`
  150. System string `json:"system,omitempty"`
  151. Details ModelDetails `json:"details,omitempty"`
  152. Messages []Message `json:"messages,omitempty"`
  153. }
  154. type CopyRequest struct {
  155. Source string `json:"source"`
  156. Destination string `json:"destination"`
  157. }
  158. type PullRequest struct {
  159. Model string `json:"model"`
  160. Insecure bool `json:"insecure,omitempty"`
  161. Username string `json:"username"`
  162. Password string `json:"password"`
  163. Stream *bool `json:"stream,omitempty"`
  164. // Name is deprecated, see Model
  165. Name string `json:"name"`
  166. }
  167. type ProgressResponse struct {
  168. Status string `json:"status"`
  169. Digest string `json:"digest,omitempty"`
  170. Total int64 `json:"total,omitempty"`
  171. Completed int64 `json:"completed,omitempty"`
  172. }
  173. type PushRequest struct {
  174. Model string `json:"model"`
  175. Insecure bool `json:"insecure,omitempty"`
  176. Username string `json:"username"`
  177. Password string `json:"password"`
  178. Stream *bool `json:"stream,omitempty"`
  179. // Name is deprecated, see Model
  180. Name string `json:"name"`
  181. }
  182. type ListResponse struct {
  183. Models []ModelResponse `json:"models"`
  184. }
  185. type ModelResponse struct {
  186. Name string `json:"name"`
  187. Model string `json:"model"`
  188. ModifiedAt time.Time `json:"modified_at"`
  189. Size int64 `json:"size"`
  190. Digest string `json:"digest"`
  191. Details ModelDetails `json:"details,omitempty"`
  192. }
  193. type TokenResponse struct {
  194. Token string `json:"token"`
  195. }
  196. type GenerateResponse struct {
  197. Model string `json:"model"`
  198. CreatedAt time.Time `json:"created_at"`
  199. Response string `json:"response"`
  200. Done bool `json:"done"`
  201. Context []int `json:"context,omitempty"`
  202. Metrics
  203. }
  204. type ModelDetails struct {
  205. ParentModel string `json:"parent_model"`
  206. Format string `json:"format"`
  207. Family string `json:"family"`
  208. Families []string `json:"families"`
  209. ParameterSize string `json:"parameter_size"`
  210. QuantizationLevel string `json:"quantization_level"`
  211. }
  212. func (m *Metrics) Summary() {
  213. if m.TotalDuration > 0 {
  214. fmt.Fprintf(os.Stderr, "total duration: %v\n", m.TotalDuration)
  215. }
  216. if m.LoadDuration > 0 {
  217. fmt.Fprintf(os.Stderr, "load duration: %v\n", m.LoadDuration)
  218. }
  219. if m.PromptEvalCount > 0 {
  220. fmt.Fprintf(os.Stderr, "prompt eval count: %d token(s)\n", m.PromptEvalCount)
  221. }
  222. if m.PromptEvalDuration > 0 {
  223. fmt.Fprintf(os.Stderr, "prompt eval duration: %s\n", m.PromptEvalDuration)
  224. fmt.Fprintf(os.Stderr, "prompt eval rate: %.2f tokens/s\n", float64(m.PromptEvalCount)/m.PromptEvalDuration.Seconds())
  225. }
  226. if m.EvalCount > 0 {
  227. fmt.Fprintf(os.Stderr, "eval count: %d token(s)\n", m.EvalCount)
  228. }
  229. if m.EvalDuration > 0 {
  230. fmt.Fprintf(os.Stderr, "eval duration: %s\n", m.EvalDuration)
  231. fmt.Fprintf(os.Stderr, "eval rate: %.2f tokens/s\n", float64(m.EvalCount)/m.EvalDuration.Seconds())
  232. }
  233. }
  234. var ErrInvalidOpts = fmt.Errorf("invalid options")
  235. func (opts *Options) FromMap(m map[string]interface{}) error {
  236. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  237. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  238. // build map of json struct tags to their types
  239. jsonOpts := make(map[string]reflect.StructField)
  240. for _, field := range reflect.VisibleFields(typeOpts) {
  241. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  242. if jsonTag != "" {
  243. jsonOpts[jsonTag] = field
  244. }
  245. }
  246. invalidOpts := []string{}
  247. for key, val := range m {
  248. if opt, ok := jsonOpts[key]; ok {
  249. field := valueOpts.FieldByName(opt.Name)
  250. if field.IsValid() && field.CanSet() {
  251. if val == nil {
  252. continue
  253. }
  254. switch field.Kind() {
  255. case reflect.Int:
  256. switch t := val.(type) {
  257. case int64:
  258. field.SetInt(t)
  259. case float64:
  260. // when JSON unmarshals numbers, it uses float64, not int
  261. field.SetInt(int64(t))
  262. default:
  263. return fmt.Errorf("option %q must be of type integer", key)
  264. }
  265. case reflect.Bool:
  266. val, ok := val.(bool)
  267. if !ok {
  268. return fmt.Errorf("option %q must be of type boolean", key)
  269. }
  270. field.SetBool(val)
  271. case reflect.Float32:
  272. // JSON unmarshals to float64
  273. val, ok := val.(float64)
  274. if !ok {
  275. return fmt.Errorf("option %q must be of type float32", key)
  276. }
  277. field.SetFloat(val)
  278. case reflect.String:
  279. val, ok := val.(string)
  280. if !ok {
  281. return fmt.Errorf("option %q must be of type string", key)
  282. }
  283. field.SetString(val)
  284. case reflect.Slice:
  285. // JSON unmarshals to []interface{}, not []string
  286. val, ok := val.([]interface{})
  287. if !ok {
  288. return fmt.Errorf("option %q must be of type array", key)
  289. }
  290. // convert []interface{} to []string
  291. slice := make([]string, len(val))
  292. for i, item := range val {
  293. str, ok := item.(string)
  294. if !ok {
  295. return fmt.Errorf("option %q must be of an array of strings", key)
  296. }
  297. slice[i] = str
  298. }
  299. field.Set(reflect.ValueOf(slice))
  300. default:
  301. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  302. }
  303. }
  304. } else {
  305. invalidOpts = append(invalidOpts, key)
  306. }
  307. }
  308. if len(invalidOpts) > 0 {
  309. return fmt.Errorf("%w: %v", ErrInvalidOpts, strings.Join(invalidOpts, ", "))
  310. }
  311. return nil
  312. }
  313. func DefaultOptions() Options {
  314. return Options{
  315. // options set on request to runner
  316. NumPredict: -1,
  317. NumKeep: 0,
  318. Temperature: 0.8,
  319. TopK: 40,
  320. TopP: 0.9,
  321. TFSZ: 1.0,
  322. TypicalP: 1.0,
  323. RepeatLastN: 64,
  324. RepeatPenalty: 1.1,
  325. PresencePenalty: 0.0,
  326. FrequencyPenalty: 0.0,
  327. Mirostat: 0,
  328. MirostatTau: 5.0,
  329. MirostatEta: 0.1,
  330. PenalizeNewline: true,
  331. Seed: -1,
  332. Runner: Runner{
  333. // options set when the model is loaded
  334. NumCtx: 2048,
  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. },
  345. }
  346. }
  347. type Duration struct {
  348. time.Duration
  349. }
  350. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  351. var v any
  352. if err := json.Unmarshal(b, &v); err != nil {
  353. return err
  354. }
  355. d.Duration = 5 * time.Minute
  356. switch t := v.(type) {
  357. case float64:
  358. if t < 0 {
  359. d.Duration = time.Duration(math.MaxInt64)
  360. } else {
  361. d.Duration = time.Duration(t * float64(time.Second))
  362. }
  363. case string:
  364. d.Duration, err = time.ParseDuration(t)
  365. if err != nil {
  366. return err
  367. }
  368. if d.Duration < 0 {
  369. d.Duration = time.Duration(math.MaxInt64)
  370. }
  371. }
  372. return nil
  373. }
  374. // FormatParams converts specified parameter options to their correct types
  375. func FormatParams(params map[string][]string) (map[string]interface{}, error) {
  376. opts := Options{}
  377. valueOpts := reflect.ValueOf(&opts).Elem() // names of the fields in the options struct
  378. typeOpts := reflect.TypeOf(opts) // types of the fields in the options struct
  379. // build map of json struct tags to their types
  380. jsonOpts := make(map[string]reflect.StructField)
  381. for _, field := range reflect.VisibleFields(typeOpts) {
  382. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  383. if jsonTag != "" {
  384. jsonOpts[jsonTag] = field
  385. }
  386. }
  387. out := make(map[string]interface{})
  388. // iterate params and set values based on json struct tags
  389. for key, vals := range params {
  390. if opt, ok := jsonOpts[key]; !ok {
  391. return nil, fmt.Errorf("unknown parameter '%s'", key)
  392. } else {
  393. field := valueOpts.FieldByName(opt.Name)
  394. if field.IsValid() && field.CanSet() {
  395. switch field.Kind() {
  396. case reflect.Float32:
  397. floatVal, err := strconv.ParseFloat(vals[0], 32)
  398. if err != nil {
  399. return nil, fmt.Errorf("invalid float value %s", vals)
  400. }
  401. out[key] = float32(floatVal)
  402. case reflect.Int:
  403. intVal, err := strconv.ParseInt(vals[0], 10, 64)
  404. if err != nil {
  405. return nil, fmt.Errorf("invalid int value %s", vals)
  406. }
  407. out[key] = intVal
  408. case reflect.Bool:
  409. boolVal, err := strconv.ParseBool(vals[0])
  410. if err != nil {
  411. return nil, fmt.Errorf("invalid bool value %s", vals)
  412. }
  413. out[key] = boolVal
  414. case reflect.String:
  415. out[key] = vals[0]
  416. case reflect.Slice:
  417. // TODO: only string slices are supported right now
  418. out[key] = vals
  419. default:
  420. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  421. }
  422. }
  423. }
  424. }
  425. return out, nil
  426. }