types.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. Stream *bool `json:"stream,omitempty"`
  93. }
  94. type DeleteRequest struct {
  95. Name string `json:"name"`
  96. }
  97. type ShowRequest struct {
  98. Name string `json:"name"`
  99. }
  100. type ShowResponse struct {
  101. License string `json:"license,omitempty"`
  102. Modelfile string `json:"modelfile,omitempty"`
  103. Parameters string `json:"parameters,omitempty"`
  104. Template string `json:"template,omitempty"`
  105. System string `json:"system,omitempty"`
  106. }
  107. type CopyRequest struct {
  108. Source string `json:"source"`
  109. Destination string `json:"destination"`
  110. }
  111. type PullRequest struct {
  112. Name string `json:"name"`
  113. Insecure bool `json:"insecure,omitempty"`
  114. Username string `json:"username"`
  115. Password string `json:"password"`
  116. Stream *bool `json:"stream,omitempty"`
  117. }
  118. type ProgressResponse struct {
  119. Status string `json:"status"`
  120. Digest string `json:"digest,omitempty"`
  121. Total int64 `json:"total,omitempty"`
  122. Completed int64 `json:"completed,omitempty"`
  123. }
  124. type PushRequest struct {
  125. Name string `json:"name"`
  126. Insecure bool `json:"insecure,omitempty"`
  127. Username string `json:"username"`
  128. Password string `json:"password"`
  129. Stream *bool `json:"stream,omitempty"`
  130. }
  131. type ListResponse struct {
  132. Models []ModelResponse `json:"models"`
  133. }
  134. type ModelResponse struct {
  135. Name string `json:"name"`
  136. ModifiedAt time.Time `json:"modified_at"`
  137. Size int64 `json:"size"`
  138. Digest string `json:"digest"`
  139. }
  140. type TokenResponse struct {
  141. Token string `json:"token"`
  142. }
  143. type GenerateResponse struct {
  144. Model string `json:"model"`
  145. CreatedAt time.Time `json:"created_at"`
  146. Response string `json:"response"`
  147. Done bool `json:"done"`
  148. Context []int `json:"context,omitempty"`
  149. TotalDuration time.Duration `json:"total_duration,omitempty"`
  150. LoadDuration time.Duration `json:"load_duration,omitempty"`
  151. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  152. PromptEvalDuration time.Duration `json:"prompt_eval_duration,omitempty"`
  153. EvalCount int `json:"eval_count,omitempty"`
  154. EvalDuration time.Duration `json:"eval_duration,omitempty"`
  155. }
  156. func (r *GenerateResponse) Summary() {
  157. if r.TotalDuration > 0 {
  158. fmt.Fprintf(os.Stderr, "total duration: %v\n", r.TotalDuration)
  159. }
  160. if r.LoadDuration > 0 {
  161. fmt.Fprintf(os.Stderr, "load duration: %v\n", r.LoadDuration)
  162. }
  163. if r.PromptEvalCount > 0 {
  164. fmt.Fprintf(os.Stderr, "prompt eval count: %d token(s)\n", r.PromptEvalCount)
  165. }
  166. if r.PromptEvalDuration > 0 {
  167. fmt.Fprintf(os.Stderr, "prompt eval duration: %s\n", r.PromptEvalDuration)
  168. fmt.Fprintf(os.Stderr, "prompt eval rate: %.2f tokens/s\n", float64(r.PromptEvalCount)/r.PromptEvalDuration.Seconds())
  169. }
  170. if r.EvalCount > 0 {
  171. fmt.Fprintf(os.Stderr, "eval count: %d token(s)\n", r.EvalCount)
  172. }
  173. if r.EvalDuration > 0 {
  174. fmt.Fprintf(os.Stderr, "eval duration: %s\n", r.EvalDuration)
  175. fmt.Fprintf(os.Stderr, "eval rate: %.2f tokens/s\n", float64(r.EvalCount)/r.EvalDuration.Seconds())
  176. }
  177. }
  178. var ErrInvalidOpts = fmt.Errorf("invalid options")
  179. func (opts *Options) FromMap(m map[string]interface{}) error {
  180. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  181. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  182. // build map of json struct tags to their types
  183. jsonOpts := make(map[string]reflect.StructField)
  184. for _, field := range reflect.VisibleFields(typeOpts) {
  185. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  186. if jsonTag != "" {
  187. jsonOpts[jsonTag] = field
  188. }
  189. }
  190. invalidOpts := []string{}
  191. for key, val := range m {
  192. if opt, ok := jsonOpts[key]; ok {
  193. field := valueOpts.FieldByName(opt.Name)
  194. if field.IsValid() && field.CanSet() {
  195. if val == nil {
  196. continue
  197. }
  198. switch field.Kind() {
  199. case reflect.Int:
  200. switch t := val.(type) {
  201. case int64:
  202. field.SetInt(t)
  203. case float64:
  204. // when JSON unmarshals numbers, it uses float64, not int
  205. field.SetInt(int64(t))
  206. default:
  207. return fmt.Errorf("option %q must be of type integer", key)
  208. }
  209. case reflect.Bool:
  210. val, ok := val.(bool)
  211. if !ok {
  212. return fmt.Errorf("option %q must be of type boolean", key)
  213. }
  214. field.SetBool(val)
  215. case reflect.Float32:
  216. // JSON unmarshals to float64
  217. val, ok := val.(float64)
  218. if !ok {
  219. return fmt.Errorf("option %q must be of type float32", key)
  220. }
  221. field.SetFloat(val)
  222. case reflect.String:
  223. val, ok := val.(string)
  224. if !ok {
  225. return fmt.Errorf("option %q must be of type string", key)
  226. }
  227. field.SetString(val)
  228. case reflect.Slice:
  229. // JSON unmarshals to []interface{}, not []string
  230. val, ok := val.([]interface{})
  231. if !ok {
  232. return fmt.Errorf("option %q must be of type array", key)
  233. }
  234. // convert []interface{} to []string
  235. slice := make([]string, len(val))
  236. for i, item := range val {
  237. str, ok := item.(string)
  238. if !ok {
  239. return fmt.Errorf("option %q must be of an array of strings", key)
  240. }
  241. slice[i] = str
  242. }
  243. field.Set(reflect.ValueOf(slice))
  244. default:
  245. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  246. }
  247. }
  248. } else {
  249. invalidOpts = append(invalidOpts, key)
  250. }
  251. }
  252. if len(invalidOpts) > 0 {
  253. return fmt.Errorf("%w: %v", ErrInvalidOpts, strings.Join(invalidOpts, ", "))
  254. }
  255. return nil
  256. }
  257. func DefaultOptions() Options {
  258. return Options{
  259. // options set on request to runner
  260. NumPredict: -1,
  261. NumKeep: 0,
  262. Temperature: 0.8,
  263. TopK: 40,
  264. TopP: 0.9,
  265. TFSZ: 1.0,
  266. TypicalP: 1.0,
  267. RepeatLastN: 64,
  268. RepeatPenalty: 1.1,
  269. PresencePenalty: 0.0,
  270. FrequencyPenalty: 0.0,
  271. Mirostat: 0,
  272. MirostatTau: 5.0,
  273. MirostatEta: 0.1,
  274. PenalizeNewline: true,
  275. Seed: -1,
  276. Runner: Runner{
  277. // options set when the model is loaded
  278. NumCtx: 2048,
  279. RopeFrequencyBase: 10000.0,
  280. RopeFrequencyScale: 1.0,
  281. NumBatch: 512,
  282. NumGPU: -1, // -1 here indicates that NumGPU should be set dynamically
  283. NumGQA: 1,
  284. NumThread: 0, // let the runtime decide
  285. LowVRAM: false,
  286. F16KV: true,
  287. UseMLock: false,
  288. UseMMap: true,
  289. UseNUMA: false,
  290. EmbeddingOnly: true,
  291. },
  292. }
  293. }
  294. type Duration struct {
  295. time.Duration
  296. }
  297. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  298. var v any
  299. if err := json.Unmarshal(b, &v); err != nil {
  300. return err
  301. }
  302. d.Duration = 5 * time.Minute
  303. switch t := v.(type) {
  304. case float64:
  305. if t < 0 {
  306. t = math.MaxFloat64
  307. }
  308. d.Duration = time.Duration(t)
  309. case string:
  310. d.Duration, err = time.ParseDuration(t)
  311. if err != nil {
  312. return err
  313. }
  314. }
  315. return nil
  316. }