types.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "math"
  7. "os"
  8. "reflect"
  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. 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. type Options struct {
  137. Seed int `json:"seed,omitempty"`
  138. // Backend options
  139. UseNUMA bool `json:"numa,omitempty"`
  140. // Model options
  141. NumCtx int `json:"num_ctx,omitempty"`
  142. NumKeep int `json:"num_keep,omitempty"`
  143. NumBatch int `json:"num_batch,omitempty"`
  144. NumGQA int `json:"num_gqa,omitempty"`
  145. NumGPU int `json:"num_gpu,omitempty"`
  146. MainGPU int `json:"main_gpu,omitempty"`
  147. LowVRAM bool `json:"low_vram,omitempty"`
  148. F16KV bool `json:"f16_kv,omitempty"`
  149. LogitsAll bool `json:"logits_all,omitempty"`
  150. VocabOnly bool `json:"vocab_only,omitempty"`
  151. UseMMap bool `json:"use_mmap,omitempty"`
  152. UseMLock bool `json:"use_mlock,omitempty"`
  153. EmbeddingOnly bool `json:"embedding_only,omitempty"`
  154. RopeFrequencyBase float32 `json:"rope_frequency_base,omitempty"`
  155. RopeFrequencyScale float32 `json:"rope_frequency_scale,omitempty"`
  156. // Predict options
  157. NumPredict int `json:"num_predict,omitempty"`
  158. TopK int `json:"top_k,omitempty"`
  159. TopP float32 `json:"top_p,omitempty"`
  160. TFSZ float32 `json:"tfs_z,omitempty"`
  161. TypicalP float32 `json:"typical_p,omitempty"`
  162. RepeatLastN int `json:"repeat_last_n,omitempty"`
  163. Temperature float32 `json:"temperature,omitempty"`
  164. RepeatPenalty float32 `json:"repeat_penalty,omitempty"`
  165. PresencePenalty float32 `json:"presence_penalty,omitempty"`
  166. FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
  167. Mirostat int `json:"mirostat,omitempty"`
  168. MirostatTau float32 `json:"mirostat_tau,omitempty"`
  169. MirostatEta float32 `json:"mirostat_eta,omitempty"`
  170. PenalizeNewline bool `json:"penalize_newline,omitempty"`
  171. Stop []string `json:"stop,omitempty"`
  172. NumThread int `json:"num_thread,omitempty"`
  173. }
  174. var ErrInvalidOpts = fmt.Errorf("invalid options")
  175. func (opts *Options) FromMap(m map[string]interface{}) error {
  176. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  177. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  178. // build map of json struct tags to their types
  179. jsonOpts := make(map[string]reflect.StructField)
  180. for _, field := range reflect.VisibleFields(typeOpts) {
  181. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  182. if jsonTag != "" {
  183. jsonOpts[jsonTag] = field
  184. }
  185. }
  186. invalidOpts := []string{}
  187. for key, val := range m {
  188. if opt, ok := jsonOpts[key]; ok {
  189. field := valueOpts.FieldByName(opt.Name)
  190. if field.IsValid() && field.CanSet() {
  191. if val == nil {
  192. continue
  193. }
  194. switch field.Kind() {
  195. case reflect.Int:
  196. switch t := val.(type) {
  197. case int64:
  198. field.SetInt(t)
  199. case float64:
  200. // when JSON unmarshals numbers, it uses float64, not int
  201. field.SetInt(int64(t))
  202. default:
  203. log.Printf("could not convert model parameter %v of type %T to int, skipped", key, val)
  204. }
  205. case reflect.Bool:
  206. val, ok := val.(bool)
  207. if !ok {
  208. log.Printf("could not convert model parameter %v of type %T to bool, skipped", key, val)
  209. continue
  210. }
  211. field.SetBool(val)
  212. case reflect.Float32:
  213. // JSON unmarshals to float64
  214. val, ok := val.(float64)
  215. if !ok {
  216. log.Printf("could not convert model parameter %v of type %T to float32, skipped", key, val)
  217. continue
  218. }
  219. field.SetFloat(val)
  220. case reflect.String:
  221. val, ok := val.(string)
  222. if !ok {
  223. log.Printf("could not convert model parameter %v of type %T to string, skipped", key, val)
  224. continue
  225. }
  226. field.SetString(val)
  227. case reflect.Slice:
  228. // JSON unmarshals to []interface{}, not []string
  229. val, ok := val.([]interface{})
  230. if !ok {
  231. log.Printf("could not convert model parameter %v of type %T to slice, skipped", key, val)
  232. continue
  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. log.Printf("could not convert model parameter %v of type %T to slice of strings, skipped", key, item)
  240. continue
  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: -1,
  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. // 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. type Duration struct {
  294. time.Duration
  295. }
  296. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  297. var v any
  298. if err := json.Unmarshal(b, &v); err != nil {
  299. return err
  300. }
  301. d.Duration = 5 * time.Minute
  302. switch t := v.(type) {
  303. case float64:
  304. if t < 0 {
  305. t = math.MaxFloat64
  306. }
  307. d.Duration = time.Duration(t)
  308. case string:
  309. d.Duration, err = time.ParseDuration(t)
  310. if err != nil {
  311. return err
  312. }
  313. }
  314. return nil
  315. }