types.go 9.3 KB

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