types.go 14 KB

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