types.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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"`
  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. }
  94. type Tools []Tool
  95. func (t Tools) String() string {
  96. bts, _ := json.Marshal(t)
  97. return string(bts)
  98. }
  99. func (t Tool) String() string {
  100. bts, _ := json.Marshal(t)
  101. return string(bts)
  102. }
  103. // Message is a single message in a chat sequence. The message contains the
  104. // role ("system", "user", or "assistant"), the content and an optional list
  105. // of images.
  106. type Message struct {
  107. Role string `json:"role"`
  108. Content string `json:"content"`
  109. Images []ImageData `json:"images,omitempty"`
  110. ToolCalls []ToolCall `json:"tool_calls,omitempty"`
  111. Audio string `json:"audio,omitempty"`
  112. }
  113. func (m *Message) UnmarshalJSON(b []byte) error {
  114. type Alias Message
  115. var a Alias
  116. if err := json.Unmarshal(b, &a); err != nil {
  117. return err
  118. }
  119. *m = Message(a)
  120. m.Role = strings.ToLower(m.Role)
  121. return nil
  122. }
  123. type ToolCall struct {
  124. Function ToolCallFunction `json:"function"`
  125. }
  126. type ToolCallFunction struct {
  127. Name string `json:"name"`
  128. Arguments ToolCallFunctionArguments `json:"arguments"`
  129. }
  130. type ToolCallFunctionArguments map[string]any
  131. func (t *ToolCallFunctionArguments) String() string {
  132. bts, _ := json.Marshal(t)
  133. return string(bts)
  134. }
  135. type Tool struct {
  136. Type string `json:"type"`
  137. Function ToolFunction `json:"function"`
  138. }
  139. type ToolFunction struct {
  140. Name string `json:"name"`
  141. Description string `json:"description"`
  142. Parameters struct {
  143. Type string `json:"type"`
  144. Required []string `json:"required"`
  145. Properties map[string]struct {
  146. Type string `json:"type"`
  147. Description string `json:"description"`
  148. Enum []string `json:"enum,omitempty"`
  149. } `json:"properties"`
  150. } `json:"parameters"`
  151. }
  152. func (t *ToolFunction) String() string {
  153. bts, _ := json.Marshal(t)
  154. return string(bts)
  155. }
  156. // ChatResponse is the response returned by [Client.Chat]. Its fields are
  157. // similar to [GenerateResponse].
  158. type ChatResponse struct {
  159. Model string `json:"model"`
  160. CreatedAt time.Time `json:"created_at"`
  161. Message Message `json:"message"`
  162. DoneReason string `json:"done_reason,omitempty"`
  163. Done bool `json:"done"`
  164. Metrics
  165. }
  166. type Metrics struct {
  167. TotalDuration time.Duration `json:"total_duration,omitempty"`
  168. LoadDuration time.Duration `json:"load_duration,omitempty"`
  169. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  170. PromptEvalDuration time.Duration `json:"prompt_eval_duration,omitempty"`
  171. EvalCount int `json:"eval_count,omitempty"`
  172. EvalDuration time.Duration `json:"eval_duration,omitempty"`
  173. }
  174. // Options specified in [GenerateRequest], if you add a new option here add it
  175. // to the API docs also.
  176. type Options struct {
  177. Runner
  178. // Predict options used at runtime
  179. NumKeep int `json:"num_keep,omitempty"`
  180. Seed int `json:"seed,omitempty"`
  181. NumPredict int `json:"num_predict,omitempty"`
  182. TopK int `json:"top_k,omitempty"`
  183. TopP float32 `json:"top_p,omitempty"`
  184. MinP float32 `json:"min_p,omitempty"`
  185. TFSZ float32 `json:"tfs_z,omitempty"`
  186. TypicalP float32 `json:"typical_p,omitempty"`
  187. RepeatLastN int `json:"repeat_last_n,omitempty"`
  188. Temperature float32 `json:"temperature,omitempty"`
  189. RepeatPenalty float32 `json:"repeat_penalty,omitempty"`
  190. PresencePenalty float32 `json:"presence_penalty,omitempty"`
  191. FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
  192. Mirostat int `json:"mirostat,omitempty"`
  193. MirostatTau float32 `json:"mirostat_tau,omitempty"`
  194. MirostatEta float32 `json:"mirostat_eta,omitempty"`
  195. PenalizeNewline bool `json:"penalize_newline,omitempty"`
  196. Stop []string `json:"stop,omitempty"`
  197. }
  198. // Runner options which must be set when the model is loaded into memory
  199. type Runner struct {
  200. NumCtx int `json:"num_ctx,omitempty"`
  201. NumBatch int `json:"num_batch,omitempty"`
  202. NumGPU int `json:"num_gpu,omitempty"`
  203. MainGPU int `json:"main_gpu,omitempty"`
  204. LowVRAM bool `json:"low_vram,omitempty"`
  205. F16KV bool `json:"f16_kv,omitempty"`
  206. LogitsAll bool `json:"logits_all,omitempty"`
  207. VocabOnly bool `json:"vocab_only,omitempty"`
  208. UseMMap *bool `json:"use_mmap,omitempty"`
  209. UseMLock bool `json:"use_mlock,omitempty"`
  210. NumThread int `json:"num_thread,omitempty"`
  211. }
  212. // EmbedRequest is the request passed to [Client.Embed].
  213. type EmbedRequest struct {
  214. // Model is the model name.
  215. Model string `json:"model"`
  216. // Input is the input to embed.
  217. Input any `json:"input"`
  218. // KeepAlive controls how long the model will stay loaded in memory following
  219. // this request.
  220. KeepAlive *Duration `json:"keep_alive,omitempty"`
  221. Truncate *bool `json:"truncate,omitempty"`
  222. // Options lists model-specific options.
  223. Options map[string]interface{} `json:"options"`
  224. }
  225. // EmbedResponse is the response from [Client.Embed].
  226. type EmbedResponse struct {
  227. Model string `json:"model"`
  228. Embeddings [][]float32 `json:"embeddings"`
  229. TotalDuration time.Duration `json:"total_duration,omitempty"`
  230. LoadDuration time.Duration `json:"load_duration,omitempty"`
  231. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  232. }
  233. // EmbeddingRequest is the request passed to [Client.Embeddings].
  234. type EmbeddingRequest struct {
  235. // Model is the model name.
  236. Model string `json:"model"`
  237. // Prompt is the textual prompt to embed.
  238. Prompt string `json:"prompt"`
  239. // KeepAlive controls how long the model will stay loaded in memory following
  240. // this request.
  241. KeepAlive *Duration `json:"keep_alive,omitempty"`
  242. // Options lists model-specific options.
  243. Options map[string]interface{} `json:"options"`
  244. }
  245. // EmbeddingResponse is the response from [Client.Embeddings].
  246. type EmbeddingResponse struct {
  247. Embedding []float64 `json:"embedding"`
  248. }
  249. // CreateRequest is the request passed to [Client.Create].
  250. type CreateRequest struct {
  251. Model string `json:"model"`
  252. Path string `json:"path"`
  253. Modelfile string `json:"modelfile"`
  254. Stream *bool `json:"stream,omitempty"`
  255. Quantize string `json:"quantize,omitempty"`
  256. // Name is deprecated, see Model
  257. Name string `json:"name"`
  258. // Quantization is deprecated, see Quantize
  259. Quantization string `json:"quantization,omitempty"`
  260. }
  261. // DeleteRequest is the request passed to [Client.Delete].
  262. type DeleteRequest struct {
  263. Model string `json:"model"`
  264. // Name is deprecated, see Model
  265. Name string `json:"name"`
  266. }
  267. // ShowRequest is the request passed to [Client.Show].
  268. type ShowRequest struct {
  269. Model string `json:"model"`
  270. System string `json:"system"`
  271. // Template is deprecated
  272. Template string `json:"template"`
  273. Verbose bool `json:"verbose"`
  274. Options map[string]interface{} `json:"options"`
  275. // Name is deprecated, see Model
  276. Name string `json:"name"`
  277. }
  278. // ShowResponse is the response returned from [Client.Show].
  279. type ShowResponse struct {
  280. License string `json:"license,omitempty"`
  281. Modelfile string `json:"modelfile,omitempty"`
  282. Parameters string `json:"parameters,omitempty"`
  283. Template string `json:"template,omitempty"`
  284. System string `json:"system,omitempty"`
  285. Details ModelDetails `json:"details,omitempty"`
  286. Messages []Message `json:"messages,omitempty"`
  287. ModelInfo map[string]any `json:"model_info,omitempty"`
  288. ProjectorInfo map[string]any `json:"projector_info,omitempty"`
  289. ModifiedAt time.Time `json:"modified_at,omitempty"`
  290. }
  291. // CopyRequest is the request passed to [Client.Copy].
  292. type CopyRequest struct {
  293. Source string `json:"source"`
  294. Destination string `json:"destination"`
  295. }
  296. // PullRequest is the request passed to [Client.Pull].
  297. type PullRequest struct {
  298. Model string `json:"model"`
  299. Insecure bool `json:"insecure,omitempty"`
  300. Username string `json:"username"`
  301. Password string `json:"password"`
  302. Stream *bool `json:"stream,omitempty"`
  303. // Name is deprecated, see Model
  304. Name string `json:"name"`
  305. }
  306. // ProgressResponse is the response passed to progress functions like
  307. // [PullProgressFunc] and [PushProgressFunc].
  308. type ProgressResponse struct {
  309. Status string `json:"status"`
  310. Digest string `json:"digest,omitempty"`
  311. Total int64 `json:"total,omitempty"`
  312. Completed int64 `json:"completed,omitempty"`
  313. }
  314. // PushRequest is the request passed to [Client.Push].
  315. type PushRequest struct {
  316. Model string `json:"model"`
  317. Insecure bool `json:"insecure,omitempty"`
  318. Username string `json:"username"`
  319. Password string `json:"password"`
  320. Stream *bool `json:"stream,omitempty"`
  321. // Name is deprecated, see Model
  322. Name string `json:"name"`
  323. }
  324. // ListResponse is the response from [Client.List].
  325. type ListResponse struct {
  326. Models []ListModelResponse `json:"models"`
  327. }
  328. // ProcessResponse is the response from [Client.Process].
  329. type ProcessResponse struct {
  330. Models []ProcessModelResponse `json:"models"`
  331. }
  332. // ListModelResponse is a single model description in [ListResponse].
  333. type ListModelResponse struct {
  334. Name string `json:"name"`
  335. Model string `json:"model"`
  336. ModifiedAt time.Time `json:"modified_at"`
  337. Size int64 `json:"size"`
  338. Digest string `json:"digest"`
  339. Details ModelDetails `json:"details,omitempty"`
  340. }
  341. // ProcessModelResponse is a single model description in [ProcessResponse].
  342. type ProcessModelResponse struct {
  343. Name string `json:"name"`
  344. Model string `json:"model"`
  345. Size int64 `json:"size"`
  346. Digest string `json:"digest"`
  347. Details ModelDetails `json:"details,omitempty"`
  348. ExpiresAt time.Time `json:"expires_at"`
  349. SizeVRAM int64 `json:"size_vram"`
  350. }
  351. type RetrieveModelResponse struct {
  352. Id string `json:"id"`
  353. Object string `json:"object"`
  354. Created int64 `json:"created"`
  355. OwnedBy string `json:"owned_by"`
  356. }
  357. type TokenResponse struct {
  358. Token string `json:"token"`
  359. }
  360. // GenerateResponse is the response passed into [GenerateResponseFunc].
  361. type GenerateResponse struct {
  362. // Model is the model name that generated the response.
  363. Model string `json:"model"`
  364. // CreatedAt is the timestamp of the response.
  365. CreatedAt time.Time `json:"created_at"`
  366. // Response is the textual response itself.
  367. Response string `json:"response"`
  368. // Done specifies if the response is complete.
  369. Done bool `json:"done"`
  370. // DoneReason is the reason the model stopped generating text.
  371. DoneReason string `json:"done_reason,omitempty"`
  372. // Context is an encoding of the conversation used in this response; this
  373. // can be sent in the next request to keep a conversational memory.
  374. Context []int `json:"context,omitempty"`
  375. Metrics
  376. }
  377. type WhisperCompletion struct {
  378. Text string `json:"text"`
  379. Error string `json:"error,omitempty"`
  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. TFSZ: 1.0,
  510. TypicalP: 1.0,
  511. RepeatLastN: 64,
  512. RepeatPenalty: 1.1,
  513. PresencePenalty: 0.0,
  514. FrequencyPenalty: 0.0,
  515. Mirostat: 0,
  516. MirostatTau: 5.0,
  517. MirostatEta: 0.1,
  518. PenalizeNewline: true,
  519. Seed: -1,
  520. Runner: Runner{
  521. // options set when the model is loaded
  522. NumCtx: 2048,
  523. NumBatch: 512,
  524. NumGPU: -1, // -1 here indicates that NumGPU should be set dynamically
  525. NumThread: 0, // let the runtime decide
  526. LowVRAM: false,
  527. F16KV: true,
  528. UseMLock: false,
  529. UseMMap: nil,
  530. },
  531. }
  532. }
  533. type Duration struct {
  534. time.Duration
  535. }
  536. func (d Duration) MarshalJSON() ([]byte, error) {
  537. if d.Duration < 0 {
  538. return []byte("-1"), nil
  539. }
  540. return []byte("\"" + d.Duration.String() + "\""), nil
  541. }
  542. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  543. var v any
  544. if err := json.Unmarshal(b, &v); err != nil {
  545. return err
  546. }
  547. d.Duration = 5 * time.Minute
  548. switch t := v.(type) {
  549. case float64:
  550. if t < 0 {
  551. d.Duration = time.Duration(math.MaxInt64)
  552. } else {
  553. d.Duration = time.Duration(int(t) * int(time.Second))
  554. }
  555. case string:
  556. d.Duration, err = time.ParseDuration(t)
  557. if err != nil {
  558. return err
  559. }
  560. if d.Duration < 0 {
  561. d.Duration = time.Duration(math.MaxInt64)
  562. }
  563. default:
  564. return fmt.Errorf("Unsupported type: '%s'", reflect.TypeOf(v))
  565. }
  566. return nil
  567. }
  568. // FormatParams converts specified parameter options to their correct types
  569. func FormatParams(params map[string][]string) (map[string]interface{}, error) {
  570. opts := Options{}
  571. valueOpts := reflect.ValueOf(&opts).Elem() // names of the fields in the options struct
  572. typeOpts := reflect.TypeOf(opts) // types of the fields in the options struct
  573. // build map of json struct tags to their types
  574. jsonOpts := make(map[string]reflect.StructField)
  575. for _, field := range reflect.VisibleFields(typeOpts) {
  576. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  577. if jsonTag != "" {
  578. jsonOpts[jsonTag] = field
  579. }
  580. }
  581. out := make(map[string]interface{})
  582. // iterate params and set values based on json struct tags
  583. for key, vals := range params {
  584. if opt, ok := jsonOpts[key]; !ok {
  585. return nil, fmt.Errorf("unknown parameter '%s'", key)
  586. } else {
  587. field := valueOpts.FieldByName(opt.Name)
  588. if field.IsValid() && field.CanSet() {
  589. switch field.Kind() {
  590. case reflect.Float32:
  591. floatVal, err := strconv.ParseFloat(vals[0], 32)
  592. if err != nil {
  593. return nil, fmt.Errorf("invalid float value %s", vals)
  594. }
  595. out[key] = float32(floatVal)
  596. case reflect.Int:
  597. intVal, err := strconv.ParseInt(vals[0], 10, 64)
  598. if err != nil {
  599. return nil, fmt.Errorf("invalid int value %s", vals)
  600. }
  601. out[key] = intVal
  602. case reflect.Bool:
  603. boolVal, err := strconv.ParseBool(vals[0])
  604. if err != nil {
  605. return nil, fmt.Errorf("invalid bool value %s", vals)
  606. }
  607. out[key] = boolVal
  608. case reflect.String:
  609. out[key] = vals[0]
  610. case reflect.Slice:
  611. // TODO: only string slices are supported right now
  612. out[key] = vals
  613. case reflect.Pointer:
  614. var b bool
  615. if field.Type() == reflect.TypeOf(&b) {
  616. boolVal, err := strconv.ParseBool(vals[0])
  617. if err != nil {
  618. return nil, fmt.Errorf("invalid bool value %s", vals)
  619. }
  620. out[key] = &boolVal
  621. } else {
  622. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  623. }
  624. default:
  625. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  626. }
  627. }
  628. }
  629. }
  630. return out, nil
  631. }