types.go 17 KB

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