types.go 13 KB

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