types.go 13 KB

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