types.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. var ErrInvalidHostPort = errors.New("invalid port specified in OLLAMA_HOST")
  256. func (opts *Options) FromMap(m map[string]interface{}) error {
  257. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  258. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  259. // build map of json struct tags to their types
  260. jsonOpts := make(map[string]reflect.StructField)
  261. for _, field := range reflect.VisibleFields(typeOpts) {
  262. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  263. if jsonTag != "" {
  264. jsonOpts[jsonTag] = field
  265. }
  266. }
  267. invalidOpts := []string{}
  268. for key, val := range m {
  269. if opt, ok := jsonOpts[key]; ok {
  270. field := valueOpts.FieldByName(opt.Name)
  271. if field.IsValid() && field.CanSet() {
  272. if val == nil {
  273. continue
  274. }
  275. switch field.Kind() {
  276. case reflect.Int:
  277. switch t := val.(type) {
  278. case int64:
  279. field.SetInt(t)
  280. case float64:
  281. // when JSON unmarshals numbers, it uses float64, not int
  282. field.SetInt(int64(t))
  283. default:
  284. return fmt.Errorf("option %q must be of type integer", key)
  285. }
  286. case reflect.Bool:
  287. val, ok := val.(bool)
  288. if !ok {
  289. return fmt.Errorf("option %q must be of type boolean", key)
  290. }
  291. field.SetBool(val)
  292. case reflect.Float32:
  293. // JSON unmarshals to float64
  294. val, ok := val.(float64)
  295. if !ok {
  296. return fmt.Errorf("option %q must be of type float32", key)
  297. }
  298. field.SetFloat(val)
  299. case reflect.String:
  300. val, ok := val.(string)
  301. if !ok {
  302. return fmt.Errorf("option %q must be of type string", key)
  303. }
  304. field.SetString(val)
  305. case reflect.Slice:
  306. // JSON unmarshals to []interface{}, not []string
  307. val, ok := val.([]interface{})
  308. if !ok {
  309. return fmt.Errorf("option %q must be of type array", key)
  310. }
  311. // convert []interface{} to []string
  312. slice := make([]string, len(val))
  313. for i, item := range val {
  314. str, ok := item.(string)
  315. if !ok {
  316. return fmt.Errorf("option %q must be of an array of strings", key)
  317. }
  318. slice[i] = str
  319. }
  320. field.Set(reflect.ValueOf(slice))
  321. default:
  322. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  323. }
  324. }
  325. } else {
  326. invalidOpts = append(invalidOpts, key)
  327. }
  328. }
  329. if len(invalidOpts) > 0 {
  330. return fmt.Errorf("%w: %v", ErrInvalidOpts, strings.Join(invalidOpts, ", "))
  331. }
  332. return nil
  333. }
  334. func DefaultOptions() Options {
  335. return Options{
  336. // options set on request to runner
  337. NumPredict: -1,
  338. // set a minimal num_keep to avoid issues on context shifts
  339. NumKeep: 4,
  340. Temperature: 0.8,
  341. TopK: 40,
  342. TopP: 0.9,
  343. TFSZ: 1.0,
  344. TypicalP: 1.0,
  345. RepeatLastN: 64,
  346. RepeatPenalty: 1.1,
  347. PresencePenalty: 0.0,
  348. FrequencyPenalty: 0.0,
  349. Mirostat: 0,
  350. MirostatTau: 5.0,
  351. MirostatEta: 0.1,
  352. PenalizeNewline: true,
  353. Seed: -1,
  354. Runner: Runner{
  355. // options set when the model is loaded
  356. NumCtx: 2048,
  357. NumBatch: 512,
  358. NumGPU: -1, // -1 here indicates that NumGPU should be set dynamically
  359. NumGQA: 1,
  360. NumThread: 0, // let the runtime decide
  361. LowVRAM: false,
  362. F16KV: true,
  363. UseMLock: false,
  364. UseMMap: true,
  365. UseNUMA: false,
  366. },
  367. }
  368. }
  369. type Duration struct {
  370. time.Duration
  371. }
  372. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  373. var v any
  374. if err := json.Unmarshal(b, &v); err != nil {
  375. return err
  376. }
  377. d.Duration = 5 * time.Minute
  378. switch t := v.(type) {
  379. case float64:
  380. if t < 0 {
  381. d.Duration = time.Duration(math.MaxInt64)
  382. } else {
  383. d.Duration = time.Duration(t * float64(time.Second))
  384. }
  385. case string:
  386. d.Duration, err = time.ParseDuration(t)
  387. if err != nil {
  388. return err
  389. }
  390. if d.Duration < 0 {
  391. d.Duration = time.Duration(math.MaxInt64)
  392. }
  393. }
  394. return nil
  395. }
  396. // FormatParams converts specified parameter options to their correct types
  397. func FormatParams(params map[string][]string) (map[string]interface{}, error) {
  398. opts := Options{}
  399. valueOpts := reflect.ValueOf(&opts).Elem() // names of the fields in the options struct
  400. typeOpts := reflect.TypeOf(opts) // types of the fields in the options struct
  401. // build map of json struct tags to their types
  402. jsonOpts := make(map[string]reflect.StructField)
  403. for _, field := range reflect.VisibleFields(typeOpts) {
  404. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  405. if jsonTag != "" {
  406. jsonOpts[jsonTag] = field
  407. }
  408. }
  409. out := make(map[string]interface{})
  410. // iterate params and set values based on json struct tags
  411. for key, vals := range params {
  412. if opt, ok := jsonOpts[key]; !ok {
  413. return nil, fmt.Errorf("unknown parameter '%s'", key)
  414. } else {
  415. field := valueOpts.FieldByName(opt.Name)
  416. if field.IsValid() && field.CanSet() {
  417. switch field.Kind() {
  418. case reflect.Float32:
  419. floatVal, err := strconv.ParseFloat(vals[0], 32)
  420. if err != nil {
  421. return nil, fmt.Errorf("invalid float value %s", vals)
  422. }
  423. out[key] = float32(floatVal)
  424. case reflect.Int:
  425. intVal, err := strconv.ParseInt(vals[0], 10, 64)
  426. if err != nil {
  427. return nil, fmt.Errorf("invalid int value %s", vals)
  428. }
  429. out[key] = intVal
  430. case reflect.Bool:
  431. boolVal, err := strconv.ParseBool(vals[0])
  432. if err != nil {
  433. return nil, fmt.Errorf("invalid bool value %s", vals)
  434. }
  435. out[key] = boolVal
  436. case reflect.String:
  437. out[key] = vals[0]
  438. case reflect.Slice:
  439. // TODO: only string slices are supported right now
  440. out[key] = vals
  441. default:
  442. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  443. }
  444. }
  445. }
  446. }
  447. return out, nil
  448. }