types.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. Model string `json:"model"`
  182. ModifiedAt time.Time `json:"modified_at"`
  183. Size int64 `json:"size"`
  184. Digest string `json:"digest"`
  185. Details ModelDetails `json:"details,omitempty"`
  186. }
  187. type TokenResponse struct {
  188. Token string `json:"token"`
  189. }
  190. type GenerateResponse struct {
  191. Model string `json:"model"`
  192. CreatedAt time.Time `json:"created_at"`
  193. Response string `json:"response"`
  194. Done bool `json:"done"`
  195. Context []int `json:"context,omitempty"`
  196. Metrics
  197. }
  198. type ModelDetails struct {
  199. Format string `json:"format"`
  200. Family string `json:"family"`
  201. Families []string `json:"families"`
  202. ParameterSize string `json:"parameter_size"`
  203. QuantizationLevel string `json:"quantization_level"`
  204. }
  205. func (m *Metrics) Summary() {
  206. if m.TotalDuration > 0 {
  207. fmt.Fprintf(os.Stderr, "total duration: %v\n", m.TotalDuration)
  208. }
  209. if m.LoadDuration > 0 {
  210. fmt.Fprintf(os.Stderr, "load duration: %v\n", m.LoadDuration)
  211. }
  212. if m.PromptEvalCount > 0 {
  213. fmt.Fprintf(os.Stderr, "prompt eval count: %d token(s)\n", m.PromptEvalCount)
  214. }
  215. if m.PromptEvalDuration > 0 {
  216. fmt.Fprintf(os.Stderr, "prompt eval duration: %s\n", m.PromptEvalDuration)
  217. fmt.Fprintf(os.Stderr, "prompt eval rate: %.2f tokens/s\n", float64(m.PromptEvalCount)/m.PromptEvalDuration.Seconds())
  218. }
  219. if m.EvalCount > 0 {
  220. fmt.Fprintf(os.Stderr, "eval count: %d token(s)\n", m.EvalCount)
  221. }
  222. if m.EvalDuration > 0 {
  223. fmt.Fprintf(os.Stderr, "eval duration: %s\n", m.EvalDuration)
  224. fmt.Fprintf(os.Stderr, "eval rate: %.2f tokens/s\n", float64(m.EvalCount)/m.EvalDuration.Seconds())
  225. }
  226. }
  227. var ErrInvalidOpts = fmt.Errorf("invalid options")
  228. func (opts *Options) FromMap(m map[string]interface{}) error {
  229. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  230. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  231. // build map of json struct tags to their types
  232. jsonOpts := make(map[string]reflect.StructField)
  233. for _, field := range reflect.VisibleFields(typeOpts) {
  234. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  235. if jsonTag != "" {
  236. jsonOpts[jsonTag] = field
  237. }
  238. }
  239. invalidOpts := []string{}
  240. for key, val := range m {
  241. if opt, ok := jsonOpts[key]; ok {
  242. field := valueOpts.FieldByName(opt.Name)
  243. if field.IsValid() && field.CanSet() {
  244. if val == nil {
  245. continue
  246. }
  247. switch field.Kind() {
  248. case reflect.Int:
  249. switch t := val.(type) {
  250. case int64:
  251. field.SetInt(t)
  252. case float64:
  253. // when JSON unmarshals numbers, it uses float64, not int
  254. field.SetInt(int64(t))
  255. default:
  256. return fmt.Errorf("option %q must be of type integer", key)
  257. }
  258. case reflect.Bool:
  259. val, ok := val.(bool)
  260. if !ok {
  261. return fmt.Errorf("option %q must be of type boolean", key)
  262. }
  263. field.SetBool(val)
  264. case reflect.Float32:
  265. // JSON unmarshals to float64
  266. val, ok := val.(float64)
  267. if !ok {
  268. return fmt.Errorf("option %q must be of type float32", key)
  269. }
  270. field.SetFloat(val)
  271. case reflect.String:
  272. val, ok := val.(string)
  273. if !ok {
  274. return fmt.Errorf("option %q must be of type string", key)
  275. }
  276. field.SetString(val)
  277. case reflect.Slice:
  278. // JSON unmarshals to []interface{}, not []string
  279. val, ok := val.([]interface{})
  280. if !ok {
  281. return fmt.Errorf("option %q must be of type array", key)
  282. }
  283. // convert []interface{} to []string
  284. slice := make([]string, len(val))
  285. for i, item := range val {
  286. str, ok := item.(string)
  287. if !ok {
  288. return fmt.Errorf("option %q must be of an array of strings", key)
  289. }
  290. slice[i] = str
  291. }
  292. field.Set(reflect.ValueOf(slice))
  293. default:
  294. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  295. }
  296. }
  297. } else {
  298. invalidOpts = append(invalidOpts, key)
  299. }
  300. }
  301. if len(invalidOpts) > 0 {
  302. return fmt.Errorf("%w: %v", ErrInvalidOpts, strings.Join(invalidOpts, ", "))
  303. }
  304. return nil
  305. }
  306. func DefaultOptions() Options {
  307. return Options{
  308. // options set on request to runner
  309. NumPredict: -1,
  310. NumKeep: 0,
  311. Temperature: 0.8,
  312. TopK: 40,
  313. TopP: 0.9,
  314. TFSZ: 1.0,
  315. TypicalP: 1.0,
  316. RepeatLastN: 64,
  317. RepeatPenalty: 1.1,
  318. PresencePenalty: 0.0,
  319. FrequencyPenalty: 0.0,
  320. Mirostat: 0,
  321. MirostatTau: 5.0,
  322. MirostatEta: 0.1,
  323. PenalizeNewline: true,
  324. Seed: -1,
  325. Runner: Runner{
  326. // options set when the model is loaded
  327. NumCtx: 2048,
  328. RopeFrequencyBase: 10000.0,
  329. RopeFrequencyScale: 1.0,
  330. NumBatch: 512,
  331. NumGPU: -1, // -1 here indicates that NumGPU should be set dynamically
  332. NumGQA: 1,
  333. NumThread: 0, // let the runtime decide
  334. LowVRAM: false,
  335. F16KV: true,
  336. UseMLock: false,
  337. UseMMap: true,
  338. UseNUMA: false,
  339. EmbeddingOnly: true,
  340. },
  341. }
  342. }
  343. type Duration struct {
  344. time.Duration
  345. }
  346. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  347. var v any
  348. if err := json.Unmarshal(b, &v); err != nil {
  349. return err
  350. }
  351. d.Duration = 5 * time.Minute
  352. switch t := v.(type) {
  353. case float64:
  354. if t < 0 {
  355. t = math.MaxFloat64
  356. }
  357. d.Duration = time.Duration(t)
  358. case string:
  359. d.Duration, err = time.ParseDuration(t)
  360. if err != nil {
  361. return err
  362. }
  363. }
  364. return nil
  365. }
  366. // FormatParams converts specified parameter options to their correct types
  367. func FormatParams(params map[string][]string) (map[string]interface{}, error) {
  368. opts := Options{}
  369. valueOpts := reflect.ValueOf(&opts).Elem() // names of the fields in the options struct
  370. typeOpts := reflect.TypeOf(opts) // types of the fields in the options struct
  371. // build map of json struct tags to their types
  372. jsonOpts := make(map[string]reflect.StructField)
  373. for _, field := range reflect.VisibleFields(typeOpts) {
  374. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  375. if jsonTag != "" {
  376. jsonOpts[jsonTag] = field
  377. }
  378. }
  379. out := make(map[string]interface{})
  380. // iterate params and set values based on json struct tags
  381. for key, vals := range params {
  382. if opt, ok := jsonOpts[key]; !ok {
  383. return nil, fmt.Errorf("unknown parameter '%s'", key)
  384. } else {
  385. field := valueOpts.FieldByName(opt.Name)
  386. if field.IsValid() && field.CanSet() {
  387. switch field.Kind() {
  388. case reflect.Float32:
  389. floatVal, err := strconv.ParseFloat(vals[0], 32)
  390. if err != nil {
  391. return nil, fmt.Errorf("invalid float value %s", vals)
  392. }
  393. out[key] = float32(floatVal)
  394. case reflect.Int:
  395. intVal, err := strconv.ParseInt(vals[0], 10, 64)
  396. if err != nil {
  397. return nil, fmt.Errorf("invalid int value %s", vals)
  398. }
  399. out[key] = intVal
  400. case reflect.Bool:
  401. boolVal, err := strconv.ParseBool(vals[0])
  402. if err != nil {
  403. return nil, fmt.Errorf("invalid bool value %s", vals)
  404. }
  405. out[key] = boolVal
  406. case reflect.String:
  407. out[key] = vals[0]
  408. case reflect.Slice:
  409. // TODO: only string slices are supported right now
  410. out[key] = vals
  411. default:
  412. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  413. }
  414. }
  415. }
  416. }
  417. return out, nil
  418. }