types.go 21 KB

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