types.go 14 KB

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