types.go 13 KB

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