types.go 12 KB

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