types.go 21 KB

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