types.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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. Error string `json:"error,omitempty"`
  374. }
  375. // ModelDetails provides details about a model.
  376. type ModelDetails struct {
  377. ParentModel string `json:"parent_model"`
  378. Format string `json:"format"`
  379. Family string `json:"family"`
  380. Families []string `json:"families"`
  381. ParameterSize string `json:"parameter_size"`
  382. QuantizationLevel string `json:"quantization_level"`
  383. }
  384. func (m *Metrics) Summary() {
  385. if m.TotalDuration > 0 {
  386. fmt.Fprintf(os.Stderr, "total duration: %v\n", m.TotalDuration)
  387. }
  388. if m.LoadDuration > 0 {
  389. fmt.Fprintf(os.Stderr, "load duration: %v\n", m.LoadDuration)
  390. }
  391. if m.PromptEvalCount > 0 {
  392. fmt.Fprintf(os.Stderr, "prompt eval count: %d token(s)\n", m.PromptEvalCount)
  393. }
  394. if m.PromptEvalDuration > 0 {
  395. fmt.Fprintf(os.Stderr, "prompt eval duration: %s\n", m.PromptEvalDuration)
  396. fmt.Fprintf(os.Stderr, "prompt eval rate: %.2f tokens/s\n", float64(m.PromptEvalCount)/m.PromptEvalDuration.Seconds())
  397. }
  398. if m.EvalCount > 0 {
  399. fmt.Fprintf(os.Stderr, "eval count: %d token(s)\n", m.EvalCount)
  400. }
  401. if m.EvalDuration > 0 {
  402. fmt.Fprintf(os.Stderr, "eval duration: %s\n", m.EvalDuration)
  403. fmt.Fprintf(os.Stderr, "eval rate: %.2f tokens/s\n", float64(m.EvalCount)/m.EvalDuration.Seconds())
  404. }
  405. }
  406. func (opts *Options) FromMap(m map[string]interface{}) error {
  407. valueOpts := reflect.ValueOf(opts).Elem() // names of the fields in the options struct
  408. typeOpts := reflect.TypeOf(opts).Elem() // types of the fields in the options struct
  409. // build map of json struct tags to their types
  410. jsonOpts := make(map[string]reflect.StructField)
  411. for _, field := range reflect.VisibleFields(typeOpts) {
  412. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  413. if jsonTag != "" {
  414. jsonOpts[jsonTag] = field
  415. }
  416. }
  417. for key, val := range m {
  418. opt, ok := jsonOpts[key]
  419. if !ok {
  420. slog.Warn("invalid option provided", "option", key)
  421. continue
  422. }
  423. field := valueOpts.FieldByName(opt.Name)
  424. if field.IsValid() && field.CanSet() {
  425. if val == nil {
  426. continue
  427. }
  428. switch field.Kind() {
  429. case reflect.Int:
  430. switch t := val.(type) {
  431. case int64:
  432. field.SetInt(t)
  433. case float64:
  434. // when JSON unmarshals numbers, it uses float64, not int
  435. field.SetInt(int64(t))
  436. default:
  437. return fmt.Errorf("option %q must be of type integer", key)
  438. }
  439. case reflect.Bool:
  440. val, ok := val.(bool)
  441. if !ok {
  442. return fmt.Errorf("option %q must be of type boolean", key)
  443. }
  444. field.SetBool(val)
  445. case reflect.Float32:
  446. // JSON unmarshals to float64
  447. val, ok := val.(float64)
  448. if !ok {
  449. return fmt.Errorf("option %q must be of type float32", key)
  450. }
  451. field.SetFloat(val)
  452. case reflect.String:
  453. val, ok := val.(string)
  454. if !ok {
  455. return fmt.Errorf("option %q must be of type string", key)
  456. }
  457. field.SetString(val)
  458. case reflect.Slice:
  459. // JSON unmarshals to []interface{}, not []string
  460. val, ok := val.([]interface{})
  461. if !ok {
  462. return fmt.Errorf("option %q must be of type array", key)
  463. }
  464. // convert []interface{} to []string
  465. slice := make([]string, len(val))
  466. for i, item := range val {
  467. str, ok := item.(string)
  468. if !ok {
  469. return fmt.Errorf("option %q must be of an array of strings", key)
  470. }
  471. slice[i] = str
  472. }
  473. field.Set(reflect.ValueOf(slice))
  474. case reflect.Pointer:
  475. var b bool
  476. if field.Type() == reflect.TypeOf(&b) {
  477. val, ok := val.(bool)
  478. if !ok {
  479. return fmt.Errorf("option %q must be of type boolean", key)
  480. }
  481. field.Set(reflect.ValueOf(&val))
  482. } else {
  483. return fmt.Errorf("unknown type loading config params: %v %v", field.Kind(), field.Type())
  484. }
  485. default:
  486. return fmt.Errorf("unknown type loading config params: %v", field.Kind())
  487. }
  488. }
  489. }
  490. return nil
  491. }
  492. // DefaultOptions is the default set of options for [GenerateRequest]; these
  493. // values are used unless the user specifies other values explicitly.
  494. func DefaultOptions() Options {
  495. return Options{
  496. // options set on request to runner
  497. NumPredict: -1,
  498. // set a minimal num_keep to avoid issues on context shifts
  499. NumKeep: 4,
  500. Temperature: 0.8,
  501. TopK: 40,
  502. TopP: 0.9,
  503. TFSZ: 1.0,
  504. TypicalP: 1.0,
  505. RepeatLastN: 64,
  506. RepeatPenalty: 1.1,
  507. PresencePenalty: 0.0,
  508. FrequencyPenalty: 0.0,
  509. Mirostat: 0,
  510. MirostatTau: 5.0,
  511. MirostatEta: 0.1,
  512. PenalizeNewline: true,
  513. Seed: -1,
  514. Runner: Runner{
  515. // options set when the model is loaded
  516. NumCtx: 2048,
  517. NumBatch: 512,
  518. NumGPU: -1, // -1 here indicates that NumGPU should be set dynamically
  519. NumThread: 0, // let the runtime decide
  520. LowVRAM: false,
  521. F16KV: true,
  522. UseMLock: false,
  523. UseMMap: nil,
  524. },
  525. }
  526. }
  527. type Duration struct {
  528. time.Duration
  529. }
  530. func (d Duration) MarshalJSON() ([]byte, error) {
  531. if d.Duration < 0 {
  532. return []byte("-1"), nil
  533. }
  534. return []byte("\"" + d.Duration.String() + "\""), nil
  535. }
  536. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  537. var v any
  538. if err := json.Unmarshal(b, &v); err != nil {
  539. return err
  540. }
  541. d.Duration = 5 * time.Minute
  542. switch t := v.(type) {
  543. case float64:
  544. if t < 0 {
  545. d.Duration = time.Duration(math.MaxInt64)
  546. } else {
  547. d.Duration = time.Duration(int(t) * int(time.Second))
  548. }
  549. case string:
  550. d.Duration, err = time.ParseDuration(t)
  551. if err != nil {
  552. return err
  553. }
  554. if d.Duration < 0 {
  555. d.Duration = time.Duration(math.MaxInt64)
  556. }
  557. default:
  558. return fmt.Errorf("Unsupported type: '%s'", reflect.TypeOf(v))
  559. }
  560. return nil
  561. }
  562. // FormatParams converts specified parameter options to their correct types
  563. func FormatParams(params map[string][]string) (map[string]interface{}, error) {
  564. opts := Options{}
  565. valueOpts := reflect.ValueOf(&opts).Elem() // names of the fields in the options struct
  566. typeOpts := reflect.TypeOf(opts) // types of the fields in the options struct
  567. // build map of json struct tags to their types
  568. jsonOpts := make(map[string]reflect.StructField)
  569. for _, field := range reflect.VisibleFields(typeOpts) {
  570. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  571. if jsonTag != "" {
  572. jsonOpts[jsonTag] = field
  573. }
  574. }
  575. out := make(map[string]interface{})
  576. // iterate params and set values based on json struct tags
  577. for key, vals := range params {
  578. if opt, ok := jsonOpts[key]; !ok {
  579. return nil, fmt.Errorf("unknown parameter '%s'", key)
  580. } else {
  581. field := valueOpts.FieldByName(opt.Name)
  582. if field.IsValid() && field.CanSet() {
  583. switch field.Kind() {
  584. case reflect.Float32:
  585. floatVal, err := strconv.ParseFloat(vals[0], 32)
  586. if err != nil {
  587. return nil, fmt.Errorf("invalid float value %s", vals)
  588. }
  589. out[key] = float32(floatVal)
  590. case reflect.Int:
  591. intVal, err := strconv.ParseInt(vals[0], 10, 64)
  592. if err != nil {
  593. return nil, fmt.Errorf("invalid int value %s", vals)
  594. }
  595. out[key] = intVal
  596. case reflect.Bool:
  597. boolVal, err := strconv.ParseBool(vals[0])
  598. if err != nil {
  599. return nil, fmt.Errorf("invalid bool value %s", vals)
  600. }
  601. out[key] = boolVal
  602. case reflect.String:
  603. out[key] = vals[0]
  604. case reflect.Slice:
  605. // TODO: only string slices are supported right now
  606. out[key] = vals
  607. case reflect.Pointer:
  608. var b bool
  609. if field.Type() == reflect.TypeOf(&b) {
  610. boolVal, err := strconv.ParseBool(vals[0])
  611. if err != nil {
  612. return nil, fmt.Errorf("invalid bool value %s", vals)
  613. }
  614. out[key] = &boolVal
  615. } else {
  616. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  617. }
  618. default:
  619. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  620. }
  621. }
  622. }
  623. }
  624. return out, nil
  625. }