types.go 22 KB

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