types.go 22 KB

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