types.go 19 KB

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