types.go 22 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 an HTTP status code and message.
  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. // [Client.Generate]. 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 json.RawMessage `json:"format,omitempty"`
  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 enables streaming of returned responses; true by default.
  75. Stream *bool `json:"stream,omitempty"`
  76. // Format is the format to return the response in (e.g. "json").
  77. Format json.RawMessage `json:"format,omitempty"`
  78. // KeepAlive controls how long the model will stay loaded into memory
  79. // following 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. Debug *Debug `json:"debug,omitempty"`
  84. Dry bool `json:"dry,omitempty"`
  85. // Options lists model-specific options.
  86. Options map[string]interface{} `json:"options"`
  87. }
  88. type Debug struct {
  89. Include []string `json:"include,omitempty"`
  90. }
  91. type Tools []Tool
  92. func (t Tools) String() string {
  93. bts, _ := json.Marshal(t)
  94. return string(bts)
  95. }
  96. func (t Tool) String() string {
  97. bts, _ := json.Marshal(t)
  98. return string(bts)
  99. }
  100. // Message is a single message in a chat sequence. The message contains the
  101. // role ("system", "user", or "assistant"), the content and an optional list
  102. // of images.
  103. type Message struct {
  104. Role string `json:"role"`
  105. Content string `json:"content"`
  106. Images []ImageData `json:"images,omitempty"`
  107. ToolCalls []ToolCall `json:"tool_calls,omitempty"`
  108. }
  109. func (m *Message) UnmarshalJSON(b []byte) error {
  110. type Alias Message
  111. var a Alias
  112. if err := json.Unmarshal(b, &a); err != nil {
  113. return err
  114. }
  115. *m = Message(a)
  116. m.Role = strings.ToLower(m.Role)
  117. return nil
  118. }
  119. type ToolCall struct {
  120. Function ToolCallFunction `json:"function"`
  121. }
  122. type ToolCallFunction struct {
  123. Index int `json:"index,omitempty"`
  124. Name string `json:"name"`
  125. Arguments ToolCallFunctionArguments `json:"arguments"`
  126. }
  127. type ToolCallFunctionArguments map[string]any
  128. func (t *ToolCallFunctionArguments) String() string {
  129. bts, _ := json.Marshal(t)
  130. return string(bts)
  131. }
  132. type Tool struct {
  133. Type string `json:"type"`
  134. Function ToolFunction `json:"function"`
  135. }
  136. type ToolFunction struct {
  137. Name string `json:"name"`
  138. Description string `json:"description"`
  139. Parameters struct {
  140. Type string `json:"type"`
  141. Required []string `json:"required"`
  142. Properties map[string]struct {
  143. Type string `json:"type"`
  144. Description string `json:"description"`
  145. Enum []string `json:"enum,omitempty"`
  146. } `json:"properties"`
  147. } `json:"parameters"`
  148. }
  149. func (t *ToolFunction) String() string {
  150. bts, _ := json.Marshal(t)
  151. return string(bts)
  152. }
  153. // ChatResponse is the response returned by [Client.Chat]. Its fields are
  154. // similar to [GenerateResponse].
  155. type ChatResponse struct {
  156. Model string `json:"model"`
  157. CreatedAt time.Time `json:"created_at"`
  158. Message Message `json:"message"`
  159. DoneReason string `json:"done_reason,omitempty"`
  160. Debug map[string]any `json:"debug,omitempty"`
  161. Done bool `json:"done"`
  162. Metrics
  163. }
  164. type Metrics struct {
  165. TotalDuration time.Duration `json:"total_duration,omitempty"`
  166. LoadDuration time.Duration `json:"load_duration,omitempty"`
  167. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  168. PromptEvalDuration time.Duration `json:"prompt_eval_duration,omitempty"`
  169. EvalCount int `json:"eval_count,omitempty"`
  170. EvalDuration time.Duration `json:"eval_duration,omitempty"`
  171. }
  172. // Options specified in [GenerateRequest]. If you add a new option here, also
  173. // add it to the API docs.
  174. type Options struct {
  175. Runner
  176. // Predict options used at runtime
  177. NumKeep int `json:"num_keep,omitempty"`
  178. Seed int `json:"seed,omitempty"`
  179. NumPredict int `json:"num_predict,omitempty"`
  180. TopK int `json:"top_k,omitempty"`
  181. TopP float32 `json:"top_p,omitempty"`
  182. MinP float32 `json:"min_p,omitempty"`
  183. TypicalP float32 `json:"typical_p,omitempty"`
  184. RepeatLastN int `json:"repeat_last_n,omitempty"`
  185. Temperature float32 `json:"temperature,omitempty"`
  186. RepeatPenalty float32 `json:"repeat_penalty,omitempty"`
  187. PresencePenalty float32 `json:"presence_penalty,omitempty"`
  188. FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
  189. Mirostat int `json:"mirostat,omitempty"`
  190. MirostatTau float32 `json:"mirostat_tau,omitempty"`
  191. MirostatEta float32 `json:"mirostat_eta,omitempty"`
  192. PenalizeNewline bool `json:"penalize_newline,omitempty"`
  193. Stop []string `json:"stop,omitempty"`
  194. }
  195. // Runner options which must be set when the model is loaded into memory
  196. type Runner struct {
  197. NumCtx int `json:"num_ctx,omitempty"`
  198. NumBatch int `json:"num_batch,omitempty"`
  199. NumGPU int `json:"num_gpu,omitempty"`
  200. MainGPU int `json:"main_gpu,omitempty"`
  201. LowVRAM bool `json:"low_vram,omitempty"`
  202. F16KV bool `json:"f16_kv,omitempty"` // Deprecated: This option is ignored
  203. LogitsAll bool `json:"logits_all,omitempty"`
  204. VocabOnly bool `json:"vocab_only,omitempty"`
  205. UseMMap *bool `json:"use_mmap,omitempty"`
  206. UseMLock bool `json:"use_mlock,omitempty"`
  207. NumThread int `json:"num_thread,omitempty"`
  208. }
  209. // EmbedRequest is the request passed to [Client.Embed].
  210. type EmbedRequest struct {
  211. // Model is the model name.
  212. Model string `json:"model"`
  213. // Input is the input to embed.
  214. Input any `json:"input"`
  215. // KeepAlive controls how long the model will stay loaded in memory following
  216. // this request.
  217. KeepAlive *Duration `json:"keep_alive,omitempty"`
  218. Truncate *bool `json:"truncate,omitempty"`
  219. // Options lists model-specific options.
  220. Options map[string]interface{} `json:"options"`
  221. }
  222. // EmbedResponse is the response from [Client.Embed].
  223. type EmbedResponse struct {
  224. Model string `json:"model"`
  225. Embeddings [][]float32 `json:"embeddings"`
  226. TotalDuration time.Duration `json:"total_duration,omitempty"`
  227. LoadDuration time.Duration `json:"load_duration,omitempty"`
  228. PromptEvalCount int `json:"prompt_eval_count,omitempty"`
  229. }
  230. // EmbeddingRequest is the request passed to [Client.Embeddings].
  231. type EmbeddingRequest struct {
  232. // Model is the model name.
  233. Model string `json:"model"`
  234. // Prompt is the textual prompt to embed.
  235. Prompt string `json:"prompt"`
  236. // KeepAlive controls how long the model will stay loaded in memory following
  237. // this request.
  238. KeepAlive *Duration `json:"keep_alive,omitempty"`
  239. // Options lists model-specific options.
  240. Options map[string]interface{} `json:"options"`
  241. }
  242. // EmbeddingResponse is the response from [Client.Embeddings].
  243. type EmbeddingResponse struct {
  244. Embedding []float64 `json:"embedding"`
  245. }
  246. // CreateRequest is the request passed to [Client.Create].
  247. type CreateRequest struct {
  248. Model string `json:"model"`
  249. Modelfile string `json:"modelfile"`
  250. Stream *bool `json:"stream,omitempty"`
  251. Quantize string `json:"quantize,omitempty"`
  252. // Deprecated: set the model name with Model instead
  253. Name string `json:"name"`
  254. // Deprecated: set the file content with Modelfile instead
  255. Path string `json:"path"`
  256. // Deprecated: use Quantize instead
  257. Quantization string `json:"quantization,omitempty"`
  258. }
  259. // DeleteRequest is the request passed to [Client.Delete].
  260. type DeleteRequest struct {
  261. Model string `json:"model"`
  262. // Deprecated: set the model name with Model instead
  263. Name string `json:"name"`
  264. }
  265. // ShowRequest is the request passed to [Client.Show].
  266. type ShowRequest struct {
  267. Model string `json:"model"`
  268. System string `json:"system"`
  269. // Template is deprecated
  270. Template string `json:"template"`
  271. Verbose bool `json:"verbose"`
  272. Options map[string]interface{} `json:"options"`
  273. // Deprecated: set the model name with Model instead
  274. Name string `json:"name"`
  275. }
  276. // ShowResponse is the response returned from [Client.Show].
  277. type ShowResponse struct {
  278. License string `json:"license,omitempty"`
  279. Modelfile string `json:"modelfile,omitempty"`
  280. Parameters string `json:"parameters,omitempty"`
  281. Template string `json:"template,omitempty"`
  282. System string `json:"system,omitempty"`
  283. Details ModelDetails `json:"details,omitempty"`
  284. Messages []Message `json:"messages,omitempty"`
  285. ModelInfo map[string]any `json:"model_info,omitempty"`
  286. ProjectorInfo map[string]any `json:"projector_info,omitempty"`
  287. ModifiedAt time.Time `json:"modified_at,omitempty"`
  288. }
  289. // CopyRequest is the request passed to [Client.Copy].
  290. type CopyRequest struct {
  291. Source string `json:"source"`
  292. Destination string `json:"destination"`
  293. }
  294. // PullRequest is the request passed to [Client.Pull].
  295. type PullRequest struct {
  296. Model string `json:"model"`
  297. Insecure bool `json:"insecure,omitempty"`
  298. Username string `json:"username"`
  299. Password string `json:"password"`
  300. Stream *bool `json:"stream,omitempty"`
  301. // Deprecated: set the model name with Model instead
  302. Name string `json:"name"`
  303. }
  304. // ProgressResponse is the response passed to progress functions like
  305. // [PullProgressFunc] and [PushProgressFunc].
  306. type ProgressResponse struct {
  307. Status string `json:"status"`
  308. Digest string `json:"digest,omitempty"`
  309. Total int64 `json:"total,omitempty"`
  310. Completed int64 `json:"completed,omitempty"`
  311. }
  312. // PushRequest is the request passed to [Client.Push].
  313. type PushRequest struct {
  314. Model string `json:"model"`
  315. Insecure bool `json:"insecure,omitempty"`
  316. Username string `json:"username"`
  317. Password string `json:"password"`
  318. Stream *bool `json:"stream,omitempty"`
  319. // Deprecated: set the model name with Model instead
  320. Name string `json:"name"`
  321. }
  322. // ListResponse is the response from [Client.List].
  323. type ListResponse struct {
  324. Models []ListModelResponse `json:"models"`
  325. }
  326. // ProcessResponse is the response from [Client.Process].
  327. type ProcessResponse struct {
  328. Models []ProcessModelResponse `json:"models"`
  329. }
  330. // ListModelResponse is a single model description in [ListResponse].
  331. type ListModelResponse struct {
  332. Name string `json:"name"`
  333. Model string `json:"model"`
  334. ModifiedAt time.Time `json:"modified_at"`
  335. Size int64 `json:"size"`
  336. Digest string `json:"digest"`
  337. Details ModelDetails `json:"details,omitempty"`
  338. }
  339. // ProcessModelResponse is a single model description in [ProcessResponse].
  340. type ProcessModelResponse struct {
  341. Name string `json:"name"`
  342. Model string `json:"model"`
  343. Size int64 `json:"size"`
  344. Digest string `json:"digest"`
  345. Details ModelDetails `json:"details,omitempty"`
  346. ExpiresAt time.Time `json:"expires_at"`
  347. SizeVRAM int64 `json:"size_vram"`
  348. }
  349. type RetrieveModelResponse struct {
  350. Id string `json:"id"`
  351. Object string `json:"object"`
  352. Created int64 `json:"created"`
  353. OwnedBy string `json:"owned_by"`
  354. }
  355. type TokenResponse struct {
  356. Token string `json:"token"`
  357. }
  358. // GenerateResponse is the response passed into [GenerateResponseFunc].
  359. type GenerateResponse struct {
  360. // Model is the model name that generated the response.
  361. Model string `json:"model"`
  362. // CreatedAt is the timestamp of the response.
  363. CreatedAt time.Time `json:"created_at"`
  364. // Response is the textual response itself.
  365. Response string `json:"response"`
  366. // Done specifies if the response is complete.
  367. Done bool `json:"done"`
  368. // DoneReason is the reason the model stopped generating text.
  369. DoneReason string `json:"done_reason,omitempty"`
  370. // Context is an encoding of the conversation used in this response; this
  371. // can be sent in the next request to keep a conversational memory.
  372. Context []int `json:"context,omitempty"`
  373. Metrics
  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. 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. UseMLock: false,
  521. UseMMap: nil,
  522. },
  523. }
  524. }
  525. type Duration struct {
  526. time.Duration
  527. }
  528. func (d Duration) MarshalJSON() ([]byte, error) {
  529. if d.Duration < 0 {
  530. return []byte("-1"), nil
  531. }
  532. return []byte("\"" + d.Duration.String() + "\""), nil
  533. }
  534. func (d *Duration) UnmarshalJSON(b []byte) (err error) {
  535. var v any
  536. if err := json.Unmarshal(b, &v); err != nil {
  537. return err
  538. }
  539. d.Duration = 5 * time.Minute
  540. switch t := v.(type) {
  541. case float64:
  542. if t < 0 {
  543. d.Duration = time.Duration(math.MaxInt64)
  544. } else {
  545. d.Duration = time.Duration(int(t) * int(time.Second))
  546. }
  547. case string:
  548. d.Duration, err = time.ParseDuration(t)
  549. if err != nil {
  550. return err
  551. }
  552. if d.Duration < 0 {
  553. d.Duration = time.Duration(math.MaxInt64)
  554. }
  555. default:
  556. return fmt.Errorf("Unsupported type: '%s'", reflect.TypeOf(v))
  557. }
  558. return nil
  559. }
  560. // FormatParams converts specified parameter options to their correct types
  561. func FormatParams(params map[string][]string) (map[string]interface{}, error) {
  562. opts := Options{}
  563. valueOpts := reflect.ValueOf(&opts).Elem() // names of the fields in the options struct
  564. typeOpts := reflect.TypeOf(opts) // types of the fields in the options struct
  565. // build map of json struct tags to their types
  566. jsonOpts := make(map[string]reflect.StructField)
  567. for _, field := range reflect.VisibleFields(typeOpts) {
  568. jsonTag := strings.Split(field.Tag.Get("json"), ",")[0]
  569. if jsonTag != "" {
  570. jsonOpts[jsonTag] = field
  571. }
  572. }
  573. out := make(map[string]interface{})
  574. // iterate params and set values based on json struct tags
  575. for key, vals := range params {
  576. if opt, ok := jsonOpts[key]; !ok {
  577. return nil, fmt.Errorf("unknown parameter '%s'", key)
  578. } else {
  579. field := valueOpts.FieldByName(opt.Name)
  580. if field.IsValid() && field.CanSet() {
  581. switch field.Kind() {
  582. case reflect.Float32:
  583. floatVal, err := strconv.ParseFloat(vals[0], 32)
  584. if err != nil {
  585. return nil, fmt.Errorf("invalid float value %s", vals)
  586. }
  587. out[key] = float32(floatVal)
  588. case reflect.Int:
  589. intVal, err := strconv.ParseInt(vals[0], 10, 64)
  590. if err != nil {
  591. return nil, fmt.Errorf("invalid int value %s", vals)
  592. }
  593. out[key] = intVal
  594. case reflect.Bool:
  595. boolVal, err := strconv.ParseBool(vals[0])
  596. if err != nil {
  597. return nil, fmt.Errorf("invalid bool value %s", vals)
  598. }
  599. out[key] = boolVal
  600. case reflect.String:
  601. out[key] = vals[0]
  602. case reflect.Slice:
  603. // TODO: only string slices are supported right now
  604. out[key] = vals
  605. case reflect.Pointer:
  606. var b bool
  607. if field.Type() == reflect.TypeOf(&b) {
  608. boolVal, err := strconv.ParseBool(vals[0])
  609. if err != nil {
  610. return nil, fmt.Errorf("invalid bool value %s", vals)
  611. }
  612. out[key] = &boolVal
  613. } else {
  614. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  615. }
  616. default:
  617. return nil, fmt.Errorf("unknown type %s for %s", field.Kind(), key)
  618. }
  619. }
  620. }
  621. }
  622. return out, nil
  623. }