types.go 17 KB

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