types.go 13 KB

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