types.go 9.7 KB

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