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. DoneReason string `json:"done_reason,omitempty"`
  83. Metrics
  84. }
  85. type Metrics struct {
  86. TotalDuration time.Duration `json:"total_duration,omitempty"`
  87. LoadDuration time.Duration `json:"load_duration,omitempty"`
  88. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  89. PromptEvalDuration time.Duration `json:"prompt_eval_duration,omitempty"`
  90. EvalCount int `json:"eval_count,omitempty"`
  91. EvalDuration time.Duration `json:"eval_duration,omitempty"`
  92. }
  93. // Options specified in GenerateRequest, if you add a new option here add it to the API docs also
  94. type Options struct {
  95. Runner
  96. // Predict options used at runtime
  97. NumKeep int `json:"num_keep,omitempty"`
  98. Seed int `json:"seed,omitempty"`
  99. NumPredict int `json:"num_predict,omitempty"`
  100. TopK int `json:"top_k,omitempty"`
  101. TopP float32 `json:"top_p,omitempty"`
  102. TFSZ float32 `json:"tfs_z,omitempty"`
  103. TypicalP float32 `json:"typical_p,omitempty"`
  104. RepeatLastN int `json:"repeat_last_n,omitempty"`
  105. Temperature float32 `json:"temperature,omitempty"`
  106. RepeatPenalty float32 `json:"repeat_penalty,omitempty"`
  107. PresencePenalty float32 `json:"presence_penalty,omitempty"`
  108. FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
  109. Mirostat int `json:"mirostat,omitempty"`
  110. MirostatTau float32 `json:"mirostat_tau,omitempty"`
  111. MirostatEta float32 `json:"mirostat_eta,omitempty"`
  112. PenalizeNewline bool `json:"penalize_newline,omitempty"`
  113. Stop []string `json:"stop,omitempty"`
  114. }
  115. // Runner options which must be set when the model is loaded into memory
  116. type Runner struct {
  117. UseNUMA bool `json:"numa,omitempty"`
  118. NumCtx int `json:"num_ctx,omitempty"`
  119. NumBatch int `json:"num_batch,omitempty"`
  120. NumGQA int `json:"num_gqa,omitempty"`
  121. NumGPU int `json:"num_gpu,omitempty"`
  122. MainGPU int `json:"main_gpu,omitempty"`
  123. LowVRAM bool `json:"low_vram,omitempty"`
  124. F16KV bool `json:"f16_kv,omitempty"`
  125. LogitsAll bool `json:"logits_all,omitempty"`
  126. VocabOnly bool `json:"vocab_only,omitempty"`
  127. UseMMap bool `json:"use_mmap,omitempty"`
  128. UseMLock bool `json:"use_mlock,omitempty"`
  129. NumThread int `json:"num_thread,omitempty"`
  130. // Unused: RopeFrequencyBase is ignored. Instead the value in the model will be used
  131. RopeFrequencyBase float32 `json:"rope_frequency_base,omitempty"`
  132. // Unused: RopeFrequencyScale is ignored. Instead the value in the model will be used
  133. RopeFrequencyScale float32 `json:"rope_frequency_scale,omitempty"`
  134. }
  135. type EmbeddingRequest struct {
  136. Model string `json:"model"`
  137. Prompt string `json:"prompt"`
  138. KeepAlive *Duration `json:"keep_alive,omitempty"`
  139. Options map[string]interface{} `json:"options"`
  140. }
  141. type EmbeddingResponse struct {
  142. Embedding []float64 `json:"embedding"`
  143. }
  144. type CreateRequest struct {
  145. Model string `json:"model"`
  146. Path string `json:"path"`
  147. Modelfile string `json:"modelfile"`
  148. Stream *bool `json:"stream,omitempty"`
  149. Quantization string `json:"quantization,omitempty"`
  150. // Name is deprecated, see Model
  151. Name string `json:"name"`
  152. }
  153. type DeleteRequest struct {
  154. Model string `json:"model"`
  155. // Name is deprecated, see Model
  156. Name string `json:"name"`
  157. }
  158. type ShowRequest struct {
  159. Model string `json:"model"`
  160. System string `json:"system"`
  161. Template string `json:"template"`
  162. Options map[string]interface{} `json:"options"`
  163. // Name is deprecated, see Model
  164. Name string `json:"name"`
  165. }
  166. type ShowResponse struct {
  167. License string `json:"license,omitempty"`
  168. Modelfile string `json:"modelfile,omitempty"`
  169. Parameters string `json:"parameters,omitempty"`
  170. Template string `json:"template,omitempty"`
  171. System string `json:"system,omitempty"`
  172. Details ModelDetails `json:"details,omitempty"`
  173. Messages []Message `json:"messages,omitempty"`
  174. }
  175. type CopyRequest struct {
  176. Source string `json:"source"`
  177. Destination string `json:"destination"`
  178. }
  179. type PullRequest struct {
  180. Model string `json:"model"`
  181. Insecure bool `json:"insecure,omitempty"`
  182. Username string `json:"username"`
  183. Password string `json:"password"`
  184. Stream *bool `json:"stream,omitempty"`
  185. // Name is deprecated, see Model
  186. Name string `json:"name"`
  187. }
  188. type ProgressResponse struct {
  189. Status string `json:"status"`
  190. Digest string `json:"digest,omitempty"`
  191. Total int64 `json:"total,omitempty"`
  192. Completed int64 `json:"completed,omitempty"`
  193. }
  194. type PushRequest struct {
  195. Model string `json:"model"`
  196. Insecure bool `json:"insecure,omitempty"`
  197. Username string `json:"username"`
  198. Password string `json:"password"`
  199. Stream *bool `json:"stream,omitempty"`
  200. // Name is deprecated, see Model
  201. Name string `json:"name"`
  202. }
  203. type ListResponse struct {
  204. Models []ModelResponse `json:"models"`
  205. }
  206. type ModelResponse struct {
  207. Name string `json:"name"`
  208. Model string `json:"model"`
  209. ModifiedAt time.Time `json:"modified_at"`
  210. Size int64 `json:"size"`
  211. Digest string `json:"digest"`
  212. Details ModelDetails `json:"details,omitempty"`
  213. }
  214. type TokenResponse struct {
  215. Token string `json:"token"`
  216. }
  217. type GenerateResponse struct {
  218. Model string `json:"model"`
  219. CreatedAt time.Time `json:"created_at"`
  220. Response string `json:"response"`
  221. Done bool `json:"done"`
  222. DoneReason string `json:"done_reason,omitempty"`
  223. Context []int `json:"context,omitempty"`
  224. Metrics
  225. }
  226. type ModelDetails struct {
  227. ParentModel string `json:"parent_model"`
  228. Format string `json:"format"`
  229. Family string `json:"family"`
  230. Families []string `json:"families"`
  231. ParameterSize string `json:"parameter_size"`
  232. QuantizationLevel string `json:"quantization_level"`
  233. }
  234. func (m *Metrics) Summary() {
  235. if m.TotalDuration > 0 {
  236. fmt.Fprintf(os.Stderr, "total duration: %v\n", m.TotalDuration)
  237. }
  238. if m.LoadDuration > 0 {
  239. fmt.Fprintf(os.Stderr, "load duration: %v\n", m.LoadDuration)
  240. }
  241. if m.PromptEvalCount > 0 {
  242. fmt.Fprintf(os.Stderr, "prompt eval count: %d token(s)\n", m.PromptEvalCount)
  243. }
  244. if m.PromptEvalDuration > 0 {
  245. fmt.Fprintf(os.Stderr, "prompt eval duration: %s\n", m.PromptEvalDuration)
  246. fmt.Fprintf(os.Stderr, "prompt eval rate: %.2f tokens/s\n", float64(m.PromptEvalCount)/m.PromptEvalDuration.Seconds())
  247. }
  248. if m.EvalCount > 0 {
  249. fmt.Fprintf(os.Stderr, "eval count: %d token(s)\n", m.EvalCount)
  250. }
  251. if m.EvalDuration > 0 {
  252. fmt.Fprintf(os.Stderr, "eval duration: %s\n", m.EvalDuration)
  253. fmt.Fprintf(os.Stderr, "eval rate: %.2f tokens/s\n", float64(m.EvalCount)/m.EvalDuration.Seconds())
  254. }
  255. }
  256. var ErrInvalidOpts = errors.New("invalid options")
  257. func (opts *Options) FromMap(m map[string]interface{}) error {
  258. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  259. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  260. // build map of json struct tags to their types
  261. jsonOpts := make(map[string]reflect.StructField)
  262. for _, field := range reflect.VisibleFields(typeOpts) {
  263. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  264. if jsonTag != "" {
  265. jsonOpts[jsonTag] = field
  266. }
  267. }
  268. invalidOpts := []string{}
  269. for key, val := range m {
  270. if opt, ok := jsonOpts[key]; ok {
  271. field := valueOpts.FieldByName(opt.Name)
  272. if field.IsValid() && field.CanSet() {
  273. if val == nil {
  274. continue
  275. }
  276. switch field.Kind() {
  277. case reflect.Int:
  278. switch t := val.(type) {
  279. case int64:
  280. field.SetInt(t)
  281. case float64:
  282. // when JSON unmarshals numbers, it uses float64, not int
  283. field.SetInt(int64(t))
  284. default:
  285. return fmt.Errorf("option %q must be of type integer", key)
  286. }
  287. case reflect.Bool:
  288. val, ok := val.(bool)
  289. if !ok {
  290. return fmt.Errorf("option %q must be of type boolean", key)
  291. }
  292. field.SetBool(val)
  293. case reflect.Float32:
  294. // JSON unmarshals to float64
  295. val, ok := val.(float64)
  296. if !ok {
  297. return fmt.Errorf("option %q must be of type float32", key)
  298. }
  299. field.SetFloat(val)
  300. case reflect.String:
  301. val, ok := val.(string)
  302. if !ok {
  303. return fmt.Errorf("option %q must be of type string", key)
  304. }
  305. field.SetString(val)
  306. case reflect.Slice:
  307. // JSON unmarshals to []interface{}, not []string
  308. val, ok := val.([]interface{})
  309. if !ok {
  310. return fmt.Errorf("option %q must be of type array", key)
  311. }
  312. // convert []interface{} to []string
  313. slice := make([]string, len(val))
  314. for i, item := range val {
  315. str, ok := item.(string)
  316. if !ok {
  317. return fmt.Errorf("option %q must be of an array of strings", key)
  318. }
  319. slice[i] = str
  320. }
  321. field.Set(reflect.ValueOf(slice))
  322. default:
  323. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  324. }
  325. }
  326. } else {
  327. invalidOpts = append(invalidOpts, key)
  328. }
  329. }
  330. if len(invalidOpts) > 0 {
  331. return fmt.Errorf("%w: %v", ErrInvalidOpts, strings.Join(invalidOpts, ", "))
  332. }
  333. return nil
  334. }
  335. func DefaultOptions() Options {
  336. return Options{
  337. // options set on request to runner
  338. NumPredict: -1,
  339. NumKeep: 0,
  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. }