types.go 13 KB

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