types.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math"
  6. "os"
  7. "reflect"
  8. "strings"
  9. "time"
  10. )
  11. type StatusError struct {
  12. StatusCode int
  13. Status string
  14. ErrorMessage string `json:"error"`
  15. }
  16. func (e StatusError) Error() string {
  17. switch {
  18. case e.Status != "" && e.ErrorMessage != "":
  19. return fmt.Sprintf("%s: %s", e.Status, e.ErrorMessage)
  20. case e.Status != "":
  21. return e.Status
  22. case e.ErrorMessage != "":
  23. return e.ErrorMessage
  24. default:
  25. // this should not happen
  26. return "something went wrong, please see the ollama server logs for details"
  27. }
  28. }
  29. type GenerateRequest struct {
  30. Model string `json:"model"`
  31. Prompt string `json:"prompt"`
  32. System string `json:"system"`
  33. Template string `json:"template"`
  34. Context []int `json:"context,omitempty"`
  35. Stream *bool `json:"stream,omitempty"`
  36. Raw bool `json:"raw,omitempty"`
  37. Format string `json:"format"`
  38. Options map[string]interface{} `json:"options"`
  39. }
  40. // Options specfied in GenerateRequest, if you add a new option here add it to the API docs also
  41. type Options struct {
  42. Runner
  43. // Predict options used at runtime
  44. NumKeep int `json:"num_keep,omitempty"`
  45. Seed int `json:"seed,omitempty"`
  46. NumPredict int `json:"num_predict,omitempty"`
  47. TopK int `json:"top_k,omitempty"`
  48. TopP float32 `json:"top_p,omitempty"`
  49. TFSZ float32 `json:"tfs_z,omitempty"`
  50. TypicalP float32 `json:"typical_p,omitempty"`
  51. RepeatLastN int `json:"repeat_last_n,omitempty"`
  52. Temperature float32 `json:"temperature,omitempty"`
  53. RepeatPenalty float32 `json:"repeat_penalty,omitempty"`
  54. PresencePenalty float32 `json:"presence_penalty,omitempty"`
  55. FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
  56. Mirostat int `json:"mirostat,omitempty"`
  57. MirostatTau float32 `json:"mirostat_tau,omitempty"`
  58. MirostatEta float32 `json:"mirostat_eta,omitempty"`
  59. PenalizeNewline bool `json:"penalize_newline,omitempty"`
  60. Stop []string `json:"stop,omitempty"`
  61. }
  62. // Runner options which must be set when the model is loaded into memory
  63. type Runner struct {
  64. UseNUMA bool `json:"numa,omitempty"`
  65. NumCtx int `json:"num_ctx,omitempty"`
  66. NumBatch int `json:"num_batch,omitempty"`
  67. NumGQA int `json:"num_gqa,omitempty"`
  68. NumGPU int `json:"num_gpu,omitempty"`
  69. MainGPU int `json:"main_gpu,omitempty"`
  70. LowVRAM bool `json:"low_vram,omitempty"`
  71. F16KV bool `json:"f16_kv,omitempty"`
  72. LogitsAll bool `json:"logits_all,omitempty"`
  73. VocabOnly bool `json:"vocab_only,omitempty"`
  74. UseMMap bool `json:"use_mmap,omitempty"`
  75. UseMLock bool `json:"use_mlock,omitempty"`
  76. EmbeddingOnly bool `json:"embedding_only,omitempty"`
  77. RopeFrequencyBase float32 `json:"rope_frequency_base,omitempty"`
  78. RopeFrequencyScale float32 `json:"rope_frequency_scale,omitempty"`
  79. NumThread int `json:"num_thread,omitempty"`
  80. }
  81. type EmbeddingRequest struct {
  82. Model string `json:"model"`
  83. Prompt string `json:"prompt"`
  84. Options map[string]interface{} `json:"options"`
  85. }
  86. type EmbeddingResponse struct {
  87. Embedding []float64 `json:"embedding"`
  88. }
  89. type CreateRequest struct {
  90. Name string `json:"name"`
  91. Path string `json:"path"`
  92. Modelfile string `json:"modelfile"`
  93. Stream *bool `json:"stream,omitempty"`
  94. }
  95. type DeleteRequest struct {
  96. Name string `json:"name"`
  97. }
  98. type ShowRequest struct {
  99. Name string `json:"name"`
  100. }
  101. type ShowResponse struct {
  102. License string `json:"license,omitempty"`
  103. Modelfile string `json:"modelfile,omitempty"`
  104. Parameters string `json:"parameters,omitempty"`
  105. Template string `json:"template,omitempty"`
  106. System string `json:"system,omitempty"`
  107. }
  108. type CopyRequest struct {
  109. Source string `json:"source"`
  110. Destination string `json:"destination"`
  111. }
  112. type PullRequest struct {
  113. Name string `json:"name"`
  114. Insecure bool `json:"insecure,omitempty"`
  115. Username string `json:"username"`
  116. Password string `json:"password"`
  117. Stream *bool `json:"stream,omitempty"`
  118. }
  119. type ProgressResponse struct {
  120. Status string `json:"status"`
  121. Digest string `json:"digest,omitempty"`
  122. Total int64 `json:"total,omitempty"`
  123. Completed int64 `json:"completed,omitempty"`
  124. }
  125. type PushRequest struct {
  126. Name string `json:"name"`
  127. Insecure bool `json:"insecure,omitempty"`
  128. Username string `json:"username"`
  129. Password string `json:"password"`
  130. Stream *bool `json:"stream,omitempty"`
  131. }
  132. type ListResponse struct {
  133. Models []ModelResponse `json:"models"`
  134. }
  135. type ModelResponse struct {
  136. Name string `json:"name"`
  137. ModifiedAt time.Time `json:"modified_at"`
  138. Size int64 `json:"size"`
  139. Digest string `json:"digest"`
  140. }
  141. type TokenResponse struct {
  142. Token string `json:"token"`
  143. }
  144. type GenerateResponse struct {
  145. Model string `json:"model"`
  146. CreatedAt time.Time `json:"created_at"`
  147. Response string `json:"response"`
  148. Done bool `json:"done"`
  149. Context []int `json:"context,omitempty"`
  150. TotalDuration time.Duration `json:"total_duration,omitempty"`
  151. LoadDuration time.Duration `json:"load_duration,omitempty"`
  152. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  153. PromptEvalDuration time.Duration `json:"prompt_eval_duration,omitempty"`
  154. EvalCount int `json:"eval_count,omitempty"`
  155. EvalDuration time.Duration `json:"eval_duration,omitempty"`
  156. }
  157. func (r *GenerateResponse) Summary() {
  158. if r.TotalDuration > 0 {
  159. fmt.Fprintf(os.Stderr, "total duration: %v\n", r.TotalDuration)
  160. }
  161. if r.LoadDuration > 0 {
  162. fmt.Fprintf(os.Stderr, "load duration: %v\n", r.LoadDuration)
  163. }
  164. if r.PromptEvalCount > 0 {
  165. fmt.Fprintf(os.Stderr, "prompt eval count: %d token(s)\n", r.PromptEvalCount)
  166. }
  167. if r.PromptEvalDuration > 0 {
  168. fmt.Fprintf(os.Stderr, "prompt eval duration: %s\n", r.PromptEvalDuration)
  169. fmt.Fprintf(os.Stderr, "prompt eval rate: %.2f tokens/s\n", float64(r.PromptEvalCount)/r.PromptEvalDuration.Seconds())
  170. }
  171. if r.EvalCount > 0 {
  172. fmt.Fprintf(os.Stderr, "eval count: %d token(s)\n", r.EvalCount)
  173. }
  174. if r.EvalDuration > 0 {
  175. fmt.Fprintf(os.Stderr, "eval duration: %s\n", r.EvalDuration)
  176. fmt.Fprintf(os.Stderr, "eval rate: %.2f tokens/s\n", float64(r.EvalCount)/r.EvalDuration.Seconds())
  177. }
  178. }
  179. var ErrInvalidOpts = fmt.Errorf("invalid options")
  180. func (opts *Options) FromMap(m map[string]interface{}) error {
  181. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  182. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  183. // build map of json struct tags to their types
  184. jsonOpts := make(map[string]reflect.StructField)
  185. for _, field := range reflect.VisibleFields(typeOpts) {
  186. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  187. if jsonTag != "" {
  188. jsonOpts[jsonTag] = field
  189. }
  190. }
  191. invalidOpts := []string{}
  192. for key, val := range m {
  193. if opt, ok := jsonOpts[key]; ok {
  194. field := valueOpts.FieldByName(opt.Name)
  195. if field.IsValid() && field.CanSet() {
  196. if val == nil {
  197. continue
  198. }
  199. switch field.Kind() {
  200. case reflect.Int:
  201. switch t := val.(type) {
  202. case int64:
  203. field.SetInt(t)
  204. case float64:
  205. // when JSON unmarshals numbers, it uses float64, not int
  206. field.SetInt(int64(t))
  207. default:
  208. return fmt.Errorf("option %q must be of type integer", key)
  209. }
  210. case reflect.Bool:
  211. val, ok := val.(bool)
  212. if !ok {
  213. return fmt.Errorf("option %q must be of type boolean", key)
  214. }
  215. field.SetBool(val)
  216. case reflect.Float32:
  217. // JSON unmarshals to float64
  218. val, ok := val.(float64)
  219. if !ok {
  220. return fmt.Errorf("option %q must be of type float32", key)
  221. }
  222. field.SetFloat(val)
  223. case reflect.String:
  224. val, ok := val.(string)
  225. if !ok {
  226. return fmt.Errorf("option %q must be of type string", key)
  227. }
  228. field.SetString(val)
  229. case reflect.Slice:
  230. // JSON unmarshals to []interface{}, not []string
  231. val, ok := val.([]interface{})
  232. if !ok {
  233. return fmt.Errorf("option %q must be of type array", key)
  234. }
  235. // convert []interface{} to []string
  236. slice := make([]string, len(val))
  237. for i, item := range val {
  238. str, ok := item.(string)
  239. if !ok {
  240. return fmt.Errorf("option %q must be of an array of strings", key)
  241. }
  242. slice[i] = str
  243. }
  244. field.Set(reflect.ValueOf(slice))
  245. default:
  246. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  247. }
  248. }
  249. } else {
  250. invalidOpts = append(invalidOpts, key)
  251. }
  252. }
  253. if len(invalidOpts) > 0 {
  254. return fmt.Errorf("%w: %v", ErrInvalidOpts, strings.Join(invalidOpts, ", "))
  255. }
  256. return nil
  257. }
  258. func DefaultOptions() Options {
  259. return Options{
  260. // options set on request to runner
  261. NumPredict: -1,
  262. NumKeep: 0,
  263. Temperature: 0.8,
  264. TopK: 40,
  265. TopP: 0.9,
  266. TFSZ: 1.0,
  267. TypicalP: 1.0,
  268. RepeatLastN: 64,
  269. RepeatPenalty: 1.1,
  270. PresencePenalty: 0.0,
  271. FrequencyPenalty: 0.0,
  272. Mirostat: 0,
  273. MirostatTau: 5.0,
  274. MirostatEta: 0.1,
  275. PenalizeNewline: true,
  276. Seed: -1,
  277. Runner: Runner{
  278. // options set when the model is loaded
  279. NumCtx: 2048,
  280. RopeFrequencyBase: 10000.0,
  281. RopeFrequencyScale: 1.0,
  282. NumBatch: 512,
  283. NumGPU: -1, // -1 here indicates that NumGPU should be set dynamically
  284. NumGQA: 1,
  285. NumThread: 0, // let the runtime decide
  286. LowVRAM: false,
  287. F16KV: true,
  288. UseMLock: false,
  289. UseMMap: true,
  290. UseNUMA: false,
  291. EmbeddingOnly: true,
  292. },
  293. }
  294. }
  295. type Duration struct {
  296. time.Duration
  297. }
  298. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  299. var v any
  300. if err := json.Unmarshal(b, &v); err != nil {
  301. return err
  302. }
  303. d.Duration = 5 * time.Minute
  304. switch t := v.(type) {
  305. case float64:
  306. if t < 0 {
  307. t = math.MaxFloat64
  308. }
  309. d.Duration = time.Duration(t)
  310. case string:
  311. d.Duration, err = time.ParseDuration(t)
  312. if err != nil {
  313. return err
  314. }
  315. }
  316. return nil
  317. }