types.go 15 KB

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