types.go 9.9 KB

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