types.go 13 KB

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