types.go 18 KB

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