types.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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 []ListModelResponse `json:"models"`
  236. }
  237. // ProcessResponse is the response from [Client.Process].
  238. type ProcessResponse struct {
  239. Models []ProcessModelResponse `json:"models"`
  240. }
  241. // ListModelResponse is a single model description in [ListResponse].
  242. type ListModelResponse struct {
  243. Name string `json:"name"`
  244. Model string `json:"model"`
  245. ModifiedAt time.Time `json:"modified_at"`
  246. Size int64 `json:"size"`
  247. Digest string `json:"digest"`
  248. Details ModelDetails `json:"details,omitempty"`
  249. }
  250. // ProcessModelResponse is a single model description in [ProcessResponse].
  251. type ProcessModelResponse struct {
  252. Name string `json:"name"`
  253. Model string `json:"model"`
  254. Size int64 `json:"size"`
  255. Digest string `json:"digest"`
  256. Details ModelDetails `json:"details,omitempty"`
  257. ExpiresAt time.Time `json:"expires_at"`
  258. SizeVRAM int64 `json:"size_vram"`
  259. }
  260. type TokenResponse struct {
  261. Token string `json:"token"`
  262. }
  263. // GenerateResponse is the response passed into [GenerateResponseFunc].
  264. type GenerateResponse struct {
  265. // Model is the model name that generated the response.
  266. Model string `json:"model"`
  267. // CreatedAt is the timestamp of the response.
  268. CreatedAt time.Time `json:"created_at"`
  269. // Response is the textual response itself.
  270. Response string `json:"response"`
  271. // Done specifies if the response is complete.
  272. Done bool `json:"done"`
  273. // DoneReason is the reason the model stopped generating text.
  274. DoneReason string `json:"done_reason,omitempty"`
  275. // Context is an encoding of the conversation used in this response; this
  276. // can be sent in the next request to keep a conversational memory.
  277. Context []int `json:"context,omitempty"`
  278. Metrics
  279. }
  280. // ModelDetails provides details about a model.
  281. type ModelDetails struct {
  282. ParentModel string `json:"parent_model"`
  283. Format string `json:"format"`
  284. Family string `json:"family"`
  285. Families []string `json:"families"`
  286. ParameterSize string `json:"parameter_size"`
  287. QuantizationLevel string `json:"quantization_level"`
  288. }
  289. func (m *Metrics) Summary() {
  290. if m.TotalDuration > 0 {
  291. fmt.Fprintf(os.Stderr, "total duration: %v\n", m.TotalDuration)
  292. }
  293. if m.LoadDuration > 0 {
  294. fmt.Fprintf(os.Stderr, "load duration: %v\n", m.LoadDuration)
  295. }
  296. if m.PromptEvalCount > 0 {
  297. fmt.Fprintf(os.Stderr, "prompt eval count: %d token(s)\n", m.PromptEvalCount)
  298. }
  299. if m.PromptEvalDuration > 0 {
  300. fmt.Fprintf(os.Stderr, "prompt eval duration: %s\n", m.PromptEvalDuration)
  301. fmt.Fprintf(os.Stderr, "prompt eval rate: %.2f tokens/s\n", float64(m.PromptEvalCount)/m.PromptEvalDuration.Seconds())
  302. }
  303. if m.EvalCount > 0 {
  304. fmt.Fprintf(os.Stderr, "eval count: %d token(s)\n", m.EvalCount)
  305. }
  306. if m.EvalDuration > 0 {
  307. fmt.Fprintf(os.Stderr, "eval duration: %s\n", m.EvalDuration)
  308. fmt.Fprintf(os.Stderr, "eval rate: %.2f tokens/s\n", float64(m.EvalCount)/m.EvalDuration.Seconds())
  309. }
  310. }
  311. var ErrInvalidHostPort = errors.New("invalid port specified in OLLAMA_HOST")
  312. func (opts *Options) FromMap(m map[string]interface{}) error {
  313. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  314. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  315. // build map of json struct tags to their types
  316. jsonOpts := make(map[string]reflect.StructField)
  317. for _, field := range reflect.VisibleFields(typeOpts) {
  318. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  319. if jsonTag != "" {
  320. jsonOpts[jsonTag] = field
  321. }
  322. }
  323. for key, val := range m {
  324. opt, ok := jsonOpts[key]
  325. if !ok {
  326. slog.Warn("invalid option provided", "option", opt.Name)
  327. continue
  328. }
  329. field := valueOpts.FieldByName(opt.Name)
  330. if field.IsValid() && field.CanSet() {
  331. if val == nil {
  332. continue
  333. }
  334. switch field.Kind() {
  335. case reflect.Int:
  336. switch t := val.(type) {
  337. case int64:
  338. field.SetInt(t)
  339. case float64:
  340. // when JSON unmarshals numbers, it uses float64, not int
  341. field.SetInt(int64(t))
  342. default:
  343. return fmt.Errorf("option %q must be of type integer", key)
  344. }
  345. case reflect.Bool:
  346. val, ok := val.(bool)
  347. if !ok {
  348. return fmt.Errorf("option %q must be of type boolean", key)
  349. }
  350. field.SetBool(val)
  351. case reflect.Float32:
  352. // JSON unmarshals to float64
  353. val, ok := val.(float64)
  354. if !ok {
  355. return fmt.Errorf("option %q must be of type float32", key)
  356. }
  357. field.SetFloat(val)
  358. case reflect.String:
  359. val, ok := val.(string)
  360. if !ok {
  361. return fmt.Errorf("option %q must be of type string", key)
  362. }
  363. field.SetString(val)
  364. case reflect.Slice:
  365. // JSON unmarshals to []interface{}, not []string
  366. val, ok := val.([]interface{})
  367. if !ok {
  368. return fmt.Errorf("option %q must be of type array", key)
  369. }
  370. // convert []interface{} to []string
  371. slice := make([]string, len(val))
  372. for i, item := range val {
  373. str, ok := item.(string)
  374. if !ok {
  375. return fmt.Errorf("option %q must be of an array of strings", key)
  376. }
  377. slice[i] = str
  378. }
  379. field.Set(reflect.ValueOf(slice))
  380. default:
  381. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  382. }
  383. }
  384. }
  385. return nil
  386. }
  387. // DefaultOptions is the default set of options for [GenerateRequest]; these
  388. // values are used unless the user specifies other values explicitly.
  389. func DefaultOptions() Options {
  390. return Options{
  391. // options set on request to runner
  392. NumPredict: -1,
  393. // set a minimal num_keep to avoid issues on context shifts
  394. NumKeep: 4,
  395. Temperature: 0.8,
  396. TopK: 40,
  397. TopP: 0.9,
  398. TFSZ: 1.0,
  399. TypicalP: 1.0,
  400. RepeatLastN: 64,
  401. RepeatPenalty: 1.1,
  402. PresencePenalty: 0.0,
  403. FrequencyPenalty: 0.0,
  404. Mirostat: 0,
  405. MirostatTau: 5.0,
  406. MirostatEta: 0.1,
  407. PenalizeNewline: true,
  408. Seed: -1,
  409. Runner: Runner{
  410. // options set when the model is loaded
  411. NumCtx: 2048,
  412. NumBatch: 512,
  413. NumGPU: -1, // -1 here indicates that NumGPU should be set dynamically
  414. NumThread: 0, // let the runtime decide
  415. LowVRAM: false,
  416. F16KV: true,
  417. UseMLock: false,
  418. UseMMap: true,
  419. UseNUMA: false,
  420. },
  421. }
  422. }
  423. type Duration struct {
  424. time.Duration
  425. }
  426. func (d Duration) MarshalJSON() ([]byte, error) {
  427. if d.Duration < 0 {
  428. return []byte("-1"), nil
  429. }
  430. return []byte("\"" + d.Duration.String() + "\""), nil
  431. }
  432. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  433. var v any
  434. if err := json.Unmarshal(b, &v); err != nil {
  435. return err
  436. }
  437. d.Duration = 5 * time.Minute
  438. switch t := v.(type) {
  439. case float64:
  440. if t < 0 {
  441. d.Duration = time.Duration(math.MaxInt64)
  442. } else {
  443. d.Duration = time.Duration(int(t) * int(time.Second))
  444. }
  445. case string:
  446. d.Duration, err = time.ParseDuration(t)
  447. if err != nil {
  448. return err
  449. }
  450. if d.Duration < 0 {
  451. d.Duration = time.Duration(math.MaxInt64)
  452. }
  453. default:
  454. return fmt.Errorf("Unsupported type: '%s'", reflect.TypeOf(v))
  455. }
  456. return nil
  457. }
  458. // FormatParams converts specified parameter options to their correct types
  459. func FormatParams(params map[string][]string) (map[string]interface{}, error) {
  460. opts := Options{}
  461. valueOpts := reflect.ValueOf(&opts).Elem() // names of the fields in the options struct
  462. typeOpts := reflect.TypeOf(opts) // types of the fields in the options struct
  463. // build map of json struct tags to their types
  464. jsonOpts := make(map[string]reflect.StructField)
  465. for _, field := range reflect.VisibleFields(typeOpts) {
  466. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  467. if jsonTag != "" {
  468. jsonOpts[jsonTag] = field
  469. }
  470. }
  471. out := make(map[string]interface{})
  472. // iterate params and set values based on json struct tags
  473. for key, vals := range params {
  474. if opt, ok := jsonOpts[key]; !ok {
  475. return nil, fmt.Errorf("unknown parameter '%s'", key)
  476. } else {
  477. field := valueOpts.FieldByName(opt.Name)
  478. if field.IsValid() && field.CanSet() {
  479. switch field.Kind() {
  480. case reflect.Float32:
  481. floatVal, err := strconv.ParseFloat(vals[0], 32)
  482. if err != nil {
  483. return nil, fmt.Errorf("invalid float value %s", vals)
  484. }
  485. out[key] = float32(floatVal)
  486. case reflect.Int:
  487. intVal, err := strconv.ParseInt(vals[0], 10, 64)
  488. if err != nil {
  489. return nil, fmt.Errorf("invalid int value %s", vals)
  490. }
  491. out[key] = intVal
  492. case reflect.Bool:
  493. boolVal, err := strconv.ParseBool(vals[0])
  494. if err != nil {
  495. return nil, fmt.Errorf("invalid bool value %s", vals)
  496. }
  497. out[key] = boolVal
  498. case reflect.String:
  499. out[key] = vals[0]
  500. case reflect.Slice:
  501. // TODO: only string slices are supported right now
  502. out[key] = vals
  503. default:
  504. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  505. }
  506. }
  507. }
  508. }
  509. return out, nil
  510. }