types.go 21 KB

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