types.go 21 KB

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