types.go 21 KB

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