types.go 22 KB

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