types.go 20 KB

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