client.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package api
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. )
  11. type Client struct {
  12. base url.URL
  13. }
  14. func NewClient(hosts ...string) *Client {
  15. host := "127.0.0.1:11434"
  16. if len(hosts) > 0 {
  17. host = hosts[0]
  18. }
  19. return &Client{
  20. base: url.URL{Scheme: "http", Host: host},
  21. }
  22. }
  23. type options struct {
  24. requestBody io.Reader
  25. responseFunc func(bts []byte) error
  26. }
  27. func OptionRequestBody(data any) func(*options) {
  28. bts, err := json.Marshal(data)
  29. if err != nil {
  30. panic(err)
  31. }
  32. return func(opts *options) {
  33. opts.requestBody = bytes.NewReader(bts)
  34. }
  35. }
  36. func OptionResponseFunc(fn func([]byte) error) func(*options) {
  37. return func(opts *options) {
  38. opts.responseFunc = fn
  39. }
  40. }
  41. func (c *Client) stream(ctx context.Context, method, path string, fns ...func(*options)) error {
  42. var opts options
  43. for _, fn := range fns {
  44. fn(&opts)
  45. }
  46. request, err := http.NewRequestWithContext(ctx, method, c.base.JoinPath(path).String(), opts.requestBody)
  47. if err != nil {
  48. return err
  49. }
  50. request.Header.Set("Content-Type", "application/json")
  51. request.Header.Set("Accept", "application/json")
  52. response, err := http.DefaultClient.Do(request)
  53. if err != nil {
  54. return err
  55. }
  56. defer response.Body.Close()
  57. if opts.responseFunc != nil {
  58. scanner := bufio.NewScanner(response.Body)
  59. for scanner.Scan() {
  60. if err := opts.responseFunc(scanner.Bytes()); err != nil {
  61. return err
  62. }
  63. }
  64. }
  65. return nil
  66. }
  67. type GenerateResponseFunc func(GenerateResponse) error
  68. func (c *Client) Generate(ctx context.Context, req *GenerateRequest, fn GenerateResponseFunc) error {
  69. return c.stream(ctx, http.MethodPost, "/api/generate",
  70. OptionRequestBody(req),
  71. OptionResponseFunc(func(bts []byte) error {
  72. var resp GenerateResponse
  73. if err := json.Unmarshal(bts, &resp); err != nil {
  74. return err
  75. }
  76. return fn(resp)
  77. }),
  78. )
  79. }
  80. type PullProgressFunc func(PullProgress) error
  81. func (c *Client) Pull(ctx context.Context, req *PullRequest, fn PullProgressFunc) error {
  82. return c.stream(ctx, http.MethodPost, "/api/pull",
  83. OptionRequestBody(req),
  84. OptionResponseFunc(func(bts []byte) error {
  85. var resp PullProgress
  86. if err := json.Unmarshal(bts, &resp); err != nil {
  87. return err
  88. }
  89. return fn(resp)
  90. }),
  91. )
  92. }