types.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math"
  6. "os"
  7. "reflect"
  8. "strconv"
  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 ImageData []byte
  31. // GenerateRequest describes a request sent by [Client.Generate]. While you
  32. // have to specify the Model and Prompt fields, all the other fields have
  33. // reasonable defaults for basic uses.
  34. type GenerateRequest struct {
  35. // Model is the model name; it should be a name familiar to Ollama from
  36. // the library at https://ollama.com/library
  37. Model string `json:"model"`
  38. // Prompt is the textual prompt to send to the model.
  39. Prompt string `json:"prompt"`
  40. // System overrides the model's default system message/prompt.
  41. System string `json:"system"`
  42. // Template overrides the model's default prompt template.
  43. Template string `json:"template"`
  44. // Context is the context parameter returned from a previous call to
  45. // Generate call. It can be used to keep a short conversational memory.
  46. Context []int `json:"context,omitempty"`
  47. // Stream specifies whether the response is streaming; it is true by default.
  48. Stream *bool `json:"stream,omitempty"`
  49. // Raw set to true means that no formatting will be applied to the prompt.
  50. Raw bool `json:"raw,omitempty"`
  51. // Format specifies the format to return a response in.
  52. Format string `json:"format"`
  53. // KeepAlive controls how long the model will stay loaded in memory following
  54. // this request.
  55. KeepAlive *Duration `json:"keep_alive,omitempty"`
  56. // Images is an optional list of base64-encoded images accompanying this
  57. // request, for multimodal models.
  58. Images []ImageData `json:"images,omitempty"`
  59. // Options lists model-specific options. For example, temperature can be
  60. // set through this field, if the model supports it.
  61. Options map[string]interface{} `json:"options"`
  62. }
  63. type ChatRequest struct {
  64. Model string `json:"model"`
  65. Messages []Message `json:"messages"`
  66. Stream *bool `json:"stream,omitempty"`
  67. Format string `json:"format"`
  68. KeepAlive *Duration `json:"keep_alive,omitempty"`
  69. Options map[string]interface{} `json:"options"`
  70. }
  71. type Message struct {
  72. Role string `json:"role"` // one of ["system", "user", "assistant"]
  73. Content string `json:"content"`
  74. Images []ImageData `json:"images,omitempty"`
  75. }
  76. type ChatResponse struct {
  77. Model string `json:"model"`
  78. CreatedAt time.Time `json:"created_at"`
  79. Message Message `json:"message"`
  80. Done bool `json:"done"`
  81. Metrics
  82. }
  83. type Metrics struct {
  84. TotalDuration time.Duration `json:"total_duration,omitempty"`
  85. LoadDuration time.Duration `json:"load_duration,omitempty"`
  86. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  87. PromptEvalDuration time.Duration `json:"prompt_eval_duration,omitempty"`
  88. EvalCount int `json:"eval_count,omitempty"`
  89. EvalDuration time.Duration `json:"eval_duration,omitempty"`
  90. }
  91. // Options specified in GenerateRequest, if you add a new option here add it to the API docs also
  92. type Options struct {
  93. Runner
  94. // Predict options used at runtime
  95. NumKeep int `json:"num_keep,omitempty"`
  96. Seed int `json:"seed,omitempty"`
  97. NumPredict int `json:"num_predict,omitempty"`
  98. TopK int `json:"top_k,omitempty"`
  99. TopP float32 `json:"top_p,omitempty"`
  100. TFSZ float32 `json:"tfs_z,omitempty"`
  101. TypicalP float32 `json:"typical_p,omitempty"`
  102. RepeatLastN int `json:"repeat_last_n,omitempty"`
  103. Temperature float32 `json:"temperature,omitempty"`
  104. RepeatPenalty float32 `json:"repeat_penalty,omitempty"`
  105. PresencePenalty float32 `json:"presence_penalty,omitempty"`
  106. FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
  107. Mirostat int `json:"mirostat,omitempty"`
  108. MirostatTau float32 `json:"mirostat_tau,omitempty"`
  109. MirostatEta float32 `json:"mirostat_eta,omitempty"`
  110. PenalizeNewline bool `json:"penalize_newline,omitempty"`
  111. Stop []string `json:"stop,omitempty"`
  112. }
  113. // Runner options which must be set when the model is loaded into memory
  114. type Runner struct {
  115. UseNUMA bool `json:"numa,omitempty"`
  116. NumCtx int `json:"num_ctx,omitempty"`
  117. NumBatch int `json:"num_batch,omitempty"`
  118. NumGQA int `json:"num_gqa,omitempty"`
  119. NumGPU int `json:"num_gpu,omitempty"`
  120. MainGPU int `json:"main_gpu,omitempty"`
  121. LowVRAM bool `json:"low_vram,omitempty"`
  122. F16KV bool `json:"f16_kv,omitempty"`
  123. LogitsAll bool `json:"logits_all,omitempty"`
  124. VocabOnly bool `json:"vocab_only,omitempty"`
  125. UseMMap bool `json:"use_mmap,omitempty"`
  126. UseMLock bool `json:"use_mlock,omitempty"`
  127. NumThread int `json:"num_thread,omitempty"`
  128. // Unused: RopeFrequencyBase is ignored. Instead the value in the model will be used
  129. RopeFrequencyBase float32 `json:"rope_frequency_base,omitempty"`
  130. // Unused: RopeFrequencyScale is ignored. Instead the value in the model will be used
  131. RopeFrequencyScale float32 `json:"rope_frequency_scale,omitempty"`
  132. }
  133. type EmbeddingRequest struct {
  134. Model string `json:"model"`
  135. Prompt string `json:"prompt"`
  136. KeepAlive *Duration `json:"keep_alive,omitempty"`
  137. Options map[string]interface{} `json:"options"`
  138. }
  139. type EmbeddingResponse struct {
  140. Embedding []float64 `json:"embedding"`
  141. }
  142. type CreateRequest struct {
  143. Model string `json:"model"`
  144. Path string `json:"path"`
  145. Modelfile string `json:"modelfile"`
  146. Stream *bool `json:"stream,omitempty"`
  147. Quantization string `json:"quantization,omitempty"`
  148. // Name is deprecated, see Model
  149. Name string `json:"name"`
  150. }
  151. type DeleteRequest struct {
  152. Model string `json:"model"`
  153. // Name is deprecated, see Model
  154. Name string `json:"name"`
  155. }
  156. type ShowRequest struct {
  157. Model string `json:"model"`
  158. System string `json:"system"`
  159. Template string `json:"template"`
  160. Options map[string]interface{} `json:"options"`
  161. // Name is deprecated, see Model
  162. Name string `json:"name"`
  163. }
  164. type ShowResponse struct {
  165. License string `json:"license,omitempty"`
  166. Modelfile string `json:"modelfile,omitempty"`
  167. Parameters string `json:"parameters,omitempty"`
  168. Template string `json:"template,omitempty"`
  169. System string `json:"system,omitempty"`
  170. Details ModelDetails `json:"details,omitempty"`
  171. Messages []Message `json:"messages,omitempty"`
  172. }
  173. type CopyRequest struct {
  174. Source string `json:"source"`
  175. Destination string `json:"destination"`
  176. }
  177. type PullRequest struct {
  178. Model string `json:"model"`
  179. Insecure bool `json:"insecure,omitempty"`
  180. Username string `json:"username"`
  181. Password string `json:"password"`
  182. Stream *bool `json:"stream,omitempty"`
  183. // Name is deprecated, see Model
  184. Name string `json:"name"`
  185. }
  186. type ProgressResponse struct {
  187. Status string `json:"status"`
  188. Digest string `json:"digest,omitempty"`
  189. Total int64 `json:"total,omitempty"`
  190. Completed int64 `json:"completed,omitempty"`
  191. }
  192. type PushRequest struct {
  193. Model string `json:"model"`
  194. Insecure bool `json:"insecure,omitempty"`
  195. Username string `json:"username"`
  196. Password string `json:"password"`
  197. Stream *bool `json:"stream,omitempty"`
  198. // Name is deprecated, see Model
  199. Name string `json:"name"`
  200. }
  201. type ListResponse struct {
  202. Models []ModelResponse `json:"models"`
  203. }
  204. type ModelResponse struct {
  205. Name string `json:"name"`
  206. Model string `json:"model"`
  207. ModifiedAt time.Time `json:"modified_at"`
  208. Size int64 `json:"size"`
  209. Digest string `json:"digest"`
  210. Details ModelDetails `json:"details,omitempty"`
  211. }
  212. type TokenResponse struct {
  213. Token string `json:"token"`
  214. }
  215. type GenerateResponse struct {
  216. Model string `json:"model"`
  217. CreatedAt time.Time `json:"created_at"`
  218. Response string `json:"response"`
  219. Done bool `json:"done"`
  220. Context []int `json:"context,omitempty"`
  221. Metrics
  222. }
  223. type ModelDetails struct {
  224. ParentModel string `json:"parent_model"`
  225. Format string `json:"format"`
  226. Family string `json:"family"`
  227. Families []string `json:"families"`
  228. ParameterSize string `json:"parameter_size"`
  229. QuantizationLevel string `json:"quantization_level"`
  230. }
  231. func (m *Metrics) Summary() {
  232. if m.TotalDuration > 0 {
  233. fmt.Fprintf(os.Stderr, "total duration: %v\n", m.TotalDuration)
  234. }
  235. if m.LoadDuration > 0 {
  236. fmt.Fprintf(os.Stderr, "load duration: %v\n", m.LoadDuration)
  237. }
  238. if m.PromptEvalCount > 0 {
  239. fmt.Fprintf(os.Stderr, "prompt eval count: %d token(s)\n", m.PromptEvalCount)
  240. }
  241. if m.PromptEvalDuration > 0 {
  242. fmt.Fprintf(os.Stderr, "prompt eval duration: %s\n", m.PromptEvalDuration)
  243. fmt.Fprintf(os.Stderr, "prompt eval rate: %.2f tokens/s\n", float64(m.PromptEvalCount)/m.PromptEvalDuration.Seconds())
  244. }
  245. if m.EvalCount > 0 {
  246. fmt.Fprintf(os.Stderr, "eval count: %d token(s)\n", m.EvalCount)
  247. }
  248. if m.EvalDuration > 0 {
  249. fmt.Fprintf(os.Stderr, "eval duration: %s\n", m.EvalDuration)
  250. fmt.Fprintf(os.Stderr, "eval rate: %.2f tokens/s\n", float64(m.EvalCount)/m.EvalDuration.Seconds())
  251. }
  252. }
  253. var ErrInvalidOpts = fmt.Errorf("invalid options")
  254. func (opts *Options) FromMap(m map[string]interface{}) error {
  255. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  256. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  257. // build map of json struct tags to their types
  258. jsonOpts := make(map[string]reflect.StructField)
  259. for _, field := range reflect.VisibleFields(typeOpts) {
  260. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  261. if jsonTag != "" {
  262. jsonOpts[jsonTag] = field
  263. }
  264. }
  265. invalidOpts := []string{}
  266. for key, val := range m {
  267. if opt, ok := jsonOpts[key]; ok {
  268. field := valueOpts.FieldByName(opt.Name)
  269. if field.IsValid() && field.CanSet() {
  270. if val == nil {
  271. continue
  272. }
  273. switch field.Kind() {
  274. case reflect.Int:
  275. switch t := val.(type) {
  276. case int64:
  277. field.SetInt(t)
  278. case float64:
  279. // when JSON unmarshals numbers, it uses float64, not int
  280. field.SetInt(int64(t))
  281. default:
  282. return fmt.Errorf("option %q must be of type integer", key)
  283. }
  284. case reflect.Bool:
  285. val, ok := val.(bool)
  286. if !ok {
  287. return fmt.Errorf("option %q must be of type boolean", key)
  288. }
  289. field.SetBool(val)
  290. case reflect.Float32:
  291. // JSON unmarshals to float64
  292. val, ok := val.(float64)
  293. if !ok {
  294. return fmt.Errorf("option %q must be of type float32", key)
  295. }
  296. field.SetFloat(val)
  297. case reflect.String:
  298. val, ok := val.(string)
  299. if !ok {
  300. return fmt.Errorf("option %q must be of type string", key)
  301. }
  302. field.SetString(val)
  303. case reflect.Slice:
  304. // JSON unmarshals to []interface{}, not []string
  305. val, ok := val.([]interface{})
  306. if !ok {
  307. return fmt.Errorf("option %q must be of type array", key)
  308. }
  309. // convert []interface{} to []string
  310. slice := make([]string, len(val))
  311. for i, item := range val {
  312. str, ok := item.(string)
  313. if !ok {
  314. return fmt.Errorf("option %q must be of an array of strings", key)
  315. }
  316. slice[i] = str
  317. }
  318. field.Set(reflect.ValueOf(slice))
  319. default:
  320. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  321. }
  322. }
  323. } else {
  324. invalidOpts = append(invalidOpts, key)
  325. }
  326. }
  327. if len(invalidOpts) > 0 {
  328. return fmt.Errorf("%w: %v", ErrInvalidOpts, strings.Join(invalidOpts, ", "))
  329. }
  330. return nil
  331. }
  332. func DefaultOptions() Options {
  333. return Options{
  334. // options set on request to runner
  335. NumPredict: -1,
  336. NumKeep: 0,
  337. Temperature: 0.8,
  338. TopK: 40,
  339. TopP: 0.9,
  340. TFSZ: 1.0,
  341. TypicalP: 1.0,
  342. RepeatLastN: 64,
  343. RepeatPenalty: 1.1,
  344. PresencePenalty: 0.0,
  345. FrequencyPenalty: 0.0,
  346. Mirostat: 0,
  347. MirostatTau: 5.0,
  348. MirostatEta: 0.1,
  349. PenalizeNewline: true,
  350. Seed: -1,
  351. Runner: Runner{
  352. // options set when the model is loaded
  353. NumCtx: 2048,
  354. NumBatch: 512,
  355. NumGPU: -1, // -1 here indicates that NumGPU should be set dynamically
  356. NumGQA: 1,
  357. NumThread: 0, // let the runtime decide
  358. LowVRAM: false,
  359. F16KV: true,
  360. UseMLock: false,
  361. UseMMap: true,
  362. UseNUMA: false,
  363. },
  364. }
  365. }
  366. type Duration struct {
  367. time.Duration
  368. }
  369. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  370. var v any
  371. if err := json.Unmarshal(b, &v); err != nil {
  372. return err
  373. }
  374. d.Duration = 5 * time.Minute
  375. switch t := v.(type) {
  376. case float64:
  377. if t < 0 {
  378. d.Duration = time.Duration(math.MaxInt64)
  379. } else {
  380. d.Duration = time.Duration(t * float64(time.Second))
  381. }
  382. case string:
  383. d.Duration, err = time.ParseDuration(t)
  384. if err != nil {
  385. return err
  386. }
  387. if d.Duration < 0 {
  388. d.Duration = time.Duration(math.MaxInt64)
  389. }
  390. }
  391. return nil
  392. }
  393. // FormatParams converts specified parameter options to their correct types
  394. func FormatParams(params map[string][]string) (map[string]interface{}, error) {
  395. opts := Options{}
  396. valueOpts := reflect.ValueOf(&opts).Elem() // names of the fields in the options struct
  397. typeOpts := reflect.TypeOf(opts) // types of the fields in the options struct
  398. // build map of json struct tags to their types
  399. jsonOpts := make(map[string]reflect.StructField)
  400. for _, field := range reflect.VisibleFields(typeOpts) {
  401. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  402. if jsonTag != "" {
  403. jsonOpts[jsonTag] = field
  404. }
  405. }
  406. out := make(map[string]interface{})
  407. // iterate params and set values based on json struct tags
  408. for key, vals := range params {
  409. if opt, ok := jsonOpts[key]; !ok {
  410. return nil, fmt.Errorf("unknown parameter '%s'", key)
  411. } else {
  412. field := valueOpts.FieldByName(opt.Name)
  413. if field.IsValid() && field.CanSet() {
  414. switch field.Kind() {
  415. case reflect.Float32:
  416. floatVal, err := strconv.ParseFloat(vals[0], 32)
  417. if err != nil {
  418. return nil, fmt.Errorf("invalid float value %s", vals)
  419. }
  420. out[key] = float32(floatVal)
  421. case reflect.Int:
  422. intVal, err := strconv.ParseInt(vals[0], 10, 64)
  423. if err != nil {
  424. return nil, fmt.Errorf("invalid int value %s", vals)
  425. }
  426. out[key] = intVal
  427. case reflect.Bool:
  428. boolVal, err := strconv.ParseBool(vals[0])
  429. if err != nil {
  430. return nil, fmt.Errorf("invalid bool value %s", vals)
  431. }
  432. out[key] = boolVal
  433. case reflect.String:
  434. out[key] = vals[0]
  435. case reflect.Slice:
  436. // TODO: only string slices are supported right now
  437. out[key] = vals
  438. default:
  439. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  440. }
  441. }
  442. }
  443. }
  444. return out, nil
  445. }