types.go 22 KB

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