types.go 22 KB

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