types.go 17 KB

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