types.go 13 KB

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