types.go 13 KB

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