types.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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 an HTTP status code and message.
  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. // Suffix is the text that comes after the inserted text.
  44. Suffix string `json:"suffix"`
  45. // System overrides the model's default system message/prompt.
  46. System string `json:"system"`
  47. // Template overrides the model's default prompt template.
  48. Template string `json:"template"`
  49. // Context is the context parameter returned from a previous call to
  50. // [Client.Generate]. It can be used to keep a short conversational memory.
  51. Context []int `json:"context,omitempty"`
  52. // Stream specifies whether the response is streaming; it is true by default.
  53. Stream *bool `json:"stream,omitempty"`
  54. // Raw set to true means that no formatting will be applied to the prompt.
  55. Raw bool `json:"raw,omitempty"`
  56. // Format specifies the format to return a response in.
  57. Format json.RawMessage `json:"format,omitempty"`
  58. // KeepAlive controls how long the model will stay loaded in memory following
  59. // this request.
  60. KeepAlive *Duration `json:"keep_alive,omitempty"`
  61. // Images is an optional list of base64-encoded images accompanying this
  62. // request, for multimodal models.
  63. Images []ImageData `json:"images,omitempty"`
  64. // Options lists model-specific options. For example, temperature can be
  65. // set through this field, if the model supports it.
  66. Options map[string]interface{} `json:"options"`
  67. ReturnLogits bool `json:"return_logits,omitempty"`
  68. }
  69. // ChatRequest describes a request sent by [Client.Chat].
  70. type ChatRequest struct {
  71. // Model is the model name, as in [GenerateRequest].
  72. Model string `json:"model"`
  73. // Messages is the messages of the chat - can be used to keep a chat memory.
  74. Messages []Message `json:"messages"`
  75. // Stream enables streaming of returned responses; true by default.
  76. Stream *bool `json:"stream,omitempty"`
  77. // Format is the format to return the response in (e.g. "json").
  78. Format json.RawMessage `json:"format,omitempty"`
  79. // KeepAlive controls how long the model will stay loaded into memory
  80. // following the request.
  81. KeepAlive *Duration `json:"keep_alive,omitempty"`
  82. // Tools is an optional list of tools the model has access to.
  83. Tools `json:"tools,omitempty"`
  84. // Options lists model-specific options.
  85. Options map[string]interface{} `json:"options"`
  86. ReturnLogits bool `json:"return_logits,omitempty"`
  87. }
  88. type Tools []Tool
  89. func (t Tools) String() string {
  90. bts, _ := json.Marshal(t)
  91. return string(bts)
  92. }
  93. func (t Tool) String() string {
  94. bts, _ := json.Marshal(t)
  95. return string(bts)
  96. }
  97. // Message is a single message in a chat sequence. The message contains the
  98. // role ("system", "user", or "assistant"), the content and an optional list
  99. // of images.
  100. type Message struct {
  101. Role string `json:"role"`
  102. Content string `json:"content"`
  103. Images []ImageData `json:"images,omitempty"`
  104. ToolCalls []ToolCall `json:"tool_calls,omitempty"`
  105. }
  106. func (m *Message) UnmarshalJSON(b []byte) error {
  107. type Alias Message
  108. var a Alias
  109. if err := json.Unmarshal(b, &a); err != nil {
  110. return err
  111. }
  112. *m = Message(a)
  113. m.Role = strings.ToLower(m.Role)
  114. return nil
  115. }
  116. type ToolCall struct {
  117. Function ToolCallFunction `json:"function"`
  118. }
  119. type ToolCallFunction struct {
  120. Index int `json:"index,omitempty"`
  121. Name string `json:"name"`
  122. Arguments ToolCallFunctionArguments `json:"arguments"`
  123. }
  124. type ToolCallFunctionArguments map[string]any
  125. func (t *ToolCallFunctionArguments) String() string {
  126. bts, _ := json.Marshal(t)
  127. return string(bts)
  128. }
  129. type Tool struct {
  130. Type string `json:"type"`
  131. Function ToolFunction `json:"function"`
  132. }
  133. type ToolFunction struct {
  134. Name string `json:"name"`
  135. Description string `json:"description"`
  136. Parameters struct {
  137. Type string `json:"type"`
  138. Required []string `json:"required"`
  139. Properties map[string]struct {
  140. Type string `json:"type"`
  141. Description string `json:"description"`
  142. Enum []string `json:"enum,omitempty"`
  143. } `json:"properties"`
  144. } `json:"parameters"`
  145. }
  146. func (t *ToolFunction) String() string {
  147. bts, _ := json.Marshal(t)
  148. return string(bts)
  149. }
  150. // ChatResponse is the response returned by [Client.Chat]. Its fields are
  151. // similar to [GenerateResponse].
  152. type ChatResponse struct {
  153. Model string `json:"model"`
  154. CreatedAt time.Time `json:"created_at"`
  155. Message Message `json:"message"`
  156. DoneReason string `json:"done_reason,omitempty"`
  157. Logits []float32 `json:"logits"`
  158. Done bool `json:"done"`
  159. Metrics
  160. }
  161. type Metrics struct {
  162. TotalDuration time.Duration `json:"total_duration,omitempty"`
  163. LoadDuration time.Duration `json:"load_duration,omitempty"`
  164. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  165. PromptEvalDuration time.Duration `json:"prompt_eval_duration,omitempty"`
  166. EvalCount int `json:"eval_count,omitempty"`
  167. EvalDuration time.Duration `json:"eval_duration,omitempty"`
  168. }
  169. type TokenLogprob struct {
  170. Token string `json:"token"`
  171. Logprob float32 `json:"logprob"`
  172. }
  173. type LogProbs struct {
  174. TopLogprobs []TokenLogprob `json:"top_logprobs"`
  175. }
  176. // Options specified in [GenerateRequest]. If you add a new option here, also
  177. // add it to the API docs.
  178. type Options struct {
  179. Runner
  180. // Predict options used at runtime
  181. NumKeep int `json:"num_keep,omitempty"`
  182. Seed int `json:"seed,omitempty"`
  183. NumPredict int `json:"num_predict,omitempty"`
  184. TopK int `json:"top_k,omitempty"`
  185. TopP float32 `json:"top_p,omitempty"`
  186. MinP float32 `json:"min_p,omitempty"`
  187. TypicalP float32 `json:"typical_p,omitempty"`
  188. RepeatLastN int `json:"repeat_last_n,omitempty"`
  189. Temperature float32 `json:"temperature,omitempty"`
  190. RepeatPenalty float32 `json:"repeat_penalty,omitempty"`
  191. PresencePenalty float32 `json:"presence_penalty,omitempty"`
  192. FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
  193. Mirostat int `json:"mirostat,omitempty"`
  194. MirostatTau float32 `json:"mirostat_tau,omitempty"`
  195. MirostatEta float32 `json:"mirostat_eta,omitempty"`
  196. PenalizeNewline bool `json:"penalize_newline,omitempty"`
  197. Stop []string `json:"stop,omitempty"`
  198. }
  199. // Runner options which must be set when the model is loaded into memory
  200. type Runner struct {
  201. NumCtx int `json:"num_ctx,omitempty"`
  202. NumBatch int `json:"num_batch,omitempty"`
  203. NumGPU int `json:"num_gpu,omitempty"`
  204. MainGPU int `json:"main_gpu,omitempty"`
  205. LowVRAM bool `json:"low_vram,omitempty"`
  206. F16KV bool `json:"f16_kv,omitempty"` // Deprecated: This option is ignored
  207. LogitsAll bool `json:"logits_all,omitempty"`
  208. VocabOnly bool `json:"vocab_only,omitempty"`
  209. UseMMap *bool `json:"use_mmap,omitempty"`
  210. UseMLock bool `json:"use_mlock,omitempty"`
  211. NumThread int `json:"num_thread,omitempty"`
  212. }
  213. // EmbedRequest is the request passed to [Client.Embed].
  214. type EmbedRequest struct {
  215. // Model is the model name.
  216. Model string `json:"model"`
  217. // Input is the input to embed.
  218. Input any `json:"input"`
  219. // KeepAlive controls how long the model will stay loaded in memory following
  220. // this request.
  221. KeepAlive *Duration `json:"keep_alive,omitempty"`
  222. Truncate *bool `json:"truncate,omitempty"`
  223. // Options lists model-specific options.
  224. Options map[string]interface{} `json:"options"`
  225. }
  226. // EmbedResponse is the response from [Client.Embed].
  227. type EmbedResponse struct {
  228. Model string `json:"model"`
  229. Embeddings [][]float32 `json:"embeddings"`
  230. TotalDuration time.Duration `json:"total_duration,omitempty"`
  231. LoadDuration time.Duration `json:"load_duration,omitempty"`
  232. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  233. }
  234. // EmbeddingRequest is the request passed to [Client.Embeddings].
  235. type EmbeddingRequest struct {
  236. // Model is the model name.
  237. Model string `json:"model"`
  238. // Prompt is the textual prompt to embed.
  239. Prompt string `json:"prompt"`
  240. // KeepAlive controls how long the model will stay loaded in memory following
  241. // this request.
  242. KeepAlive *Duration `json:"keep_alive,omitempty"`
  243. // Options lists model-specific options.
  244. Options map[string]interface{} `json:"options"`
  245. }
  246. // EmbeddingResponse is the response from [Client.Embeddings].
  247. type EmbeddingResponse struct {
  248. Embedding []float64 `json:"embedding"`
  249. }
  250. // CreateRequest is the request passed to [Client.Create].
  251. type CreateRequest struct {
  252. Model string `json:"model"`
  253. Modelfile string `json:"modelfile"`
  254. Stream *bool `json:"stream,omitempty"`
  255. Quantize string `json:"quantize,omitempty"`
  256. // Deprecated: set the model name with Model instead
  257. Name string `json:"name"`
  258. // Deprecated: set the file content with Modelfile instead
  259. Path string `json:"path"`
  260. // Deprecated: use Quantize instead
  261. Quantization string `json:"quantization,omitempty"`
  262. }
  263. // DeleteRequest is the request passed to [Client.Delete].
  264. type DeleteRequest struct {
  265. Model string `json:"model"`
  266. // Deprecated: set the model name with Model instead
  267. Name string `json:"name"`
  268. }
  269. // ShowRequest is the request passed to [Client.Show].
  270. type ShowRequest struct {
  271. Model string `json:"model"`
  272. System string `json:"system"`
  273. // Template is deprecated
  274. Template string `json:"template"`
  275. Verbose bool `json:"verbose"`
  276. Options map[string]interface{} `json:"options"`
  277. // Deprecated: set the model name with Model instead
  278. Name string `json:"name"`
  279. }
  280. // ShowResponse is the response returned from [Client.Show].
  281. type ShowResponse struct {
  282. License string `json:"license,omitempty"`
  283. Modelfile string `json:"modelfile,omitempty"`
  284. Parameters string `json:"parameters,omitempty"`
  285. Template string `json:"template,omitempty"`
  286. System string `json:"system,omitempty"`
  287. Details ModelDetails `json:"details,omitempty"`
  288. Messages []Message `json:"messages,omitempty"`
  289. ModelInfo map[string]any `json:"model_info,omitempty"`
  290. ProjectorInfo map[string]any `json:"projector_info,omitempty"`
  291. ModifiedAt time.Time `json:"modified_at,omitempty"`
  292. }
  293. // CopyRequest is the request passed to [Client.Copy].
  294. type CopyRequest struct {
  295. Source string `json:"source"`
  296. Destination string `json:"destination"`
  297. }
  298. // PullRequest is the request passed to [Client.Pull].
  299. type PullRequest struct {
  300. Model string `json:"model"`
  301. Insecure bool `json:"insecure,omitempty"`
  302. Username string `json:"username"`
  303. Password string `json:"password"`
  304. Stream *bool `json:"stream,omitempty"`
  305. // Deprecated: set the model name with Model instead
  306. Name string `json:"name"`
  307. }
  308. // ProgressResponse is the response passed to progress functions like
  309. // [PullProgressFunc] and [PushProgressFunc].
  310. type ProgressResponse struct {
  311. Status string `json:"status"`
  312. Digest string `json:"digest,omitempty"`
  313. Total int64 `json:"total,omitempty"`
  314. Completed int64 `json:"completed,omitempty"`
  315. }
  316. // PushRequest is the request passed to [Client.Push].
  317. type PushRequest struct {
  318. Model string `json:"model"`
  319. Insecure bool `json:"insecure,omitempty"`
  320. Username string `json:"username"`
  321. Password string `json:"password"`
  322. Stream *bool `json:"stream,omitempty"`
  323. // Deprecated: set the model name with Model instead
  324. Name string `json:"name"`
  325. }
  326. // ListResponse is the response from [Client.List].
  327. type ListResponse struct {
  328. Models []ListModelResponse `json:"models"`
  329. }
  330. // ProcessResponse is the response from [Client.Process].
  331. type ProcessResponse struct {
  332. Models []ProcessModelResponse `json:"models"`
  333. }
  334. // ListModelResponse is a single model description in [ListResponse].
  335. type ListModelResponse struct {
  336. Name string `json:"name"`
  337. Model string `json:"model"`
  338. ModifiedAt time.Time `json:"modified_at"`
  339. Size int64 `json:"size"`
  340. Digest string `json:"digest"`
  341. Details ModelDetails `json:"details,omitempty"`
  342. }
  343. // ProcessModelResponse is a single model description in [ProcessResponse].
  344. type ProcessModelResponse struct {
  345. Name string `json:"name"`
  346. Model string `json:"model"`
  347. Size int64 `json:"size"`
  348. Digest string `json:"digest"`
  349. Details ModelDetails `json:"details,omitempty"`
  350. ExpiresAt time.Time `json:"expires_at"`
  351. SizeVRAM int64 `json:"size_vram"`
  352. }
  353. type RetrieveModelResponse struct {
  354. Id string `json:"id"`
  355. Object string `json:"object"`
  356. Created int64 `json:"created"`
  357. OwnedBy string `json:"owned_by"`
  358. }
  359. type TokenResponse struct {
  360. Token string `json:"token"`
  361. }
  362. // GenerateResponse is the response passed into [GenerateResponseFunc].
  363. type GenerateResponse struct {
  364. // Model is the model name that generated the response.
  365. Model string `json:"model"`
  366. // CreatedAt is the timestamp of the response.
  367. CreatedAt time.Time `json:"created_at"`
  368. // Response is the textual response itself.
  369. Response string `json:"response"`
  370. // Done specifies if the response is complete.
  371. Done bool `json:"done"`
  372. // DoneReason is the reason the model stopped generating text.
  373. DoneReason string `json:"done_reason,omitempty"`
  374. // Context is an encoding of the conversation used in this response; this
  375. // can be sent in the next request to keep a conversational memory.
  376. Context []int `json:"context,omitempty"`
  377. Metrics
  378. Logits []float32 `json:"logits"`
  379. }
  380. // ModelDetails provides details about a model.
  381. type ModelDetails struct {
  382. ParentModel string `json:"parent_model"`
  383. Format string `json:"format"`
  384. Family string `json:"family"`
  385. Families []string `json:"families"`
  386. ParameterSize string `json:"parameter_size"`
  387. QuantizationLevel string `json:"quantization_level"`
  388. }
  389. func (m *Metrics) Summary() {
  390. if m.TotalDuration > 0 {
  391. fmt.Fprintf(os.Stderr, "total duration: %v\n", m.TotalDuration)
  392. }
  393. if m.LoadDuration > 0 {
  394. fmt.Fprintf(os.Stderr, "load duration: %v\n", m.LoadDuration)
  395. }
  396. if m.PromptEvalCount > 0 {
  397. fmt.Fprintf(os.Stderr, "prompt eval count: %d token(s)\n", m.PromptEvalCount)
  398. }
  399. if m.PromptEvalDuration > 0 {
  400. fmt.Fprintf(os.Stderr, "prompt eval duration: %s\n", m.PromptEvalDuration)
  401. fmt.Fprintf(os.Stderr, "prompt eval rate: %.2f tokens/s\n", float64(m.PromptEvalCount)/m.PromptEvalDuration.Seconds())
  402. }
  403. if m.EvalCount > 0 {
  404. fmt.Fprintf(os.Stderr, "eval count: %d token(s)\n", m.EvalCount)
  405. }
  406. if m.EvalDuration > 0 {
  407. fmt.Fprintf(os.Stderr, "eval duration: %s\n", m.EvalDuration)
  408. fmt.Fprintf(os.Stderr, "eval rate: %.2f tokens/s\n", float64(m.EvalCount)/m.EvalDuration.Seconds())
  409. }
  410. }
  411. func (opts *Options) FromMap(m map[string]interface{}) error {
  412. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  413. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  414. // build map of json struct tags to their types
  415. jsonOpts := make(map[string]reflect.StructField)
  416. for _, field := range reflect.VisibleFields(typeOpts) {
  417. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  418. if jsonTag != "" {
  419. jsonOpts[jsonTag] = field
  420. }
  421. }
  422. for key, val := range m {
  423. opt, ok := jsonOpts[key]
  424. if !ok {
  425. slog.Warn("invalid option provided", "option", key)
  426. continue
  427. }
  428. field := valueOpts.FieldByName(opt.Name)
  429. if field.IsValid() && field.CanSet() {
  430. if val == nil {
  431. continue
  432. }
  433. switch field.Kind() {
  434. case reflect.Int:
  435. switch t := val.(type) {
  436. case int64:
  437. field.SetInt(t)
  438. case float64:
  439. // when JSON unmarshals numbers, it uses float64, not int
  440. field.SetInt(int64(t))
  441. default:
  442. return fmt.Errorf("option %q must be of type integer", key)
  443. }
  444. case reflect.Bool:
  445. val, ok := val.(bool)
  446. if !ok {
  447. return fmt.Errorf("option %q must be of type boolean", key)
  448. }
  449. field.SetBool(val)
  450. case reflect.Float32:
  451. // JSON unmarshals to float64
  452. val, ok := val.(float64)
  453. if !ok {
  454. return fmt.Errorf("option %q must be of type float32", key)
  455. }
  456. field.SetFloat(val)
  457. case reflect.String:
  458. val, ok := val.(string)
  459. if !ok {
  460. return fmt.Errorf("option %q must be of type string", key)
  461. }
  462. field.SetString(val)
  463. case reflect.Slice:
  464. // JSON unmarshals to []interface{}, not []string
  465. val, ok := val.([]interface{})
  466. if !ok {
  467. return fmt.Errorf("option %q must be of type array", key)
  468. }
  469. // convert []interface{} to []string
  470. slice := make([]string, len(val))
  471. for i, item := range val {
  472. str, ok := item.(string)
  473. if !ok {
  474. return fmt.Errorf("option %q must be of an array of strings", key)
  475. }
  476. slice[i] = str
  477. }
  478. field.Set(reflect.ValueOf(slice))
  479. case reflect.Pointer:
  480. var b bool
  481. if field.Type() == reflect.TypeOf(&b) {
  482. val, ok := val.(bool)
  483. if !ok {
  484. return fmt.Errorf("option %q must be of type boolean", key)
  485. }
  486. field.Set(reflect.ValueOf(&val))
  487. } else {
  488. return fmt.Errorf("unknown type loading config params: %v %v", field.Kind(), field.Type())
  489. }
  490. default:
  491. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  492. }
  493. }
  494. }
  495. return nil
  496. }
  497. // DefaultOptions is the default set of options for [GenerateRequest]; these
  498. // values are used unless the user specifies other values explicitly.
  499. func DefaultOptions() Options {
  500. return Options{
  501. // options set on request to runner
  502. NumPredict: -1,
  503. // set a minimal num_keep to avoid issues on context shifts
  504. NumKeep: 4,
  505. Temperature: 0.8,
  506. TopK: 40,
  507. TopP: 0.9,
  508. TypicalP: 1.0,
  509. RepeatLastN: 64,
  510. RepeatPenalty: 1.1,
  511. PresencePenalty: 0.0,
  512. FrequencyPenalty: 0.0,
  513. Mirostat: 0,
  514. MirostatTau: 5.0,
  515. MirostatEta: 0.1,
  516. PenalizeNewline: true,
  517. Seed: -1,
  518. Runner: Runner{
  519. // options set when the model is loaded
  520. NumCtx: 2048,
  521. NumBatch: 512,
  522. NumGPU: -1, // -1 here indicates that NumGPU should be set dynamically
  523. NumThread: 0, // let the runtime decide
  524. LowVRAM: false,
  525. UseMLock: false,
  526. UseMMap: nil,
  527. },
  528. }
  529. }
  530. type Duration struct {
  531. time.Duration
  532. }
  533. func (d Duration) MarshalJSON() ([]byte, error) {
  534. if d.Duration < 0 {
  535. return []byte("-1"), nil
  536. }
  537. return []byte("\"" + d.Duration.String() + "\""), nil
  538. }
  539. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  540. var v any
  541. if err := json.Unmarshal(b, &v); err != nil {
  542. return err
  543. }
  544. d.Duration = 5 * time.Minute
  545. switch t := v.(type) {
  546. case float64:
  547. if t < 0 {
  548. d.Duration = time.Duration(math.MaxInt64)
  549. } else {
  550. d.Duration = time.Duration(int(t) * int(time.Second))
  551. }
  552. case string:
  553. d.Duration, err = time.ParseDuration(t)
  554. if err != nil {
  555. return err
  556. }
  557. if d.Duration < 0 {
  558. d.Duration = time.Duration(math.MaxInt64)
  559. }
  560. default:
  561. return fmt.Errorf("Unsupported type: '%s'", reflect.TypeOf(v))
  562. }
  563. return nil
  564. }
  565. // FormatParams converts specified parameter options to their correct types
  566. func FormatParams(params map[string][]string) (map[string]interface{}, error) {
  567. opts := Options{}
  568. valueOpts := reflect.ValueOf(&opts).Elem() // names of the fields in the options struct
  569. typeOpts := reflect.TypeOf(opts) // types of the fields in the options struct
  570. // build map of json struct tags to their types
  571. jsonOpts := make(map[string]reflect.StructField)
  572. for _, field := range reflect.VisibleFields(typeOpts) {
  573. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  574. if jsonTag != "" {
  575. jsonOpts[jsonTag] = field
  576. }
  577. }
  578. out := make(map[string]interface{})
  579. // iterate params and set values based on json struct tags
  580. for key, vals := range params {
  581. if opt, ok := jsonOpts[key]; !ok {
  582. return nil, fmt.Errorf("unknown parameter '%s'", key)
  583. } else {
  584. field := valueOpts.FieldByName(opt.Name)
  585. if field.IsValid() && field.CanSet() {
  586. switch field.Kind() {
  587. case reflect.Float32:
  588. floatVal, err := strconv.ParseFloat(vals[0], 32)
  589. if err != nil {
  590. return nil, fmt.Errorf("invalid float value %s", vals)
  591. }
  592. out[key] = float32(floatVal)
  593. case reflect.Int:
  594. intVal, err := strconv.ParseInt(vals[0], 10, 64)
  595. if err != nil {
  596. return nil, fmt.Errorf("invalid int value %s", vals)
  597. }
  598. out[key] = intVal
  599. case reflect.Bool:
  600. boolVal, err := strconv.ParseBool(vals[0])
  601. if err != nil {
  602. return nil, fmt.Errorf("invalid bool value %s", vals)
  603. }
  604. out[key] = boolVal
  605. case reflect.String:
  606. out[key] = vals[0]
  607. case reflect.Slice:
  608. // TODO: only string slices are supported right now
  609. out[key] = vals
  610. case reflect.Pointer:
  611. var b bool
  612. if field.Type() == reflect.TypeOf(&b) {
  613. boolVal, err := strconv.ParseBool(vals[0])
  614. if err != nil {
  615. return nil, fmt.Errorf("invalid bool value %s", vals)
  616. }
  617. out[key] = &boolVal
  618. } else {
  619. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  620. }
  621. default:
  622. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  623. }
  624. }
  625. }
  626. }
  627. return out, nil
  628. }