client.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. package api
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "runtime"
  14. "strings"
  15. "github.com/jmorganca/ollama/format"
  16. "github.com/jmorganca/ollama/version"
  17. )
  18. type Client struct {
  19. base *url.URL
  20. http http.Client
  21. }
  22. func checkError(resp *http.Response, body []byte) error {
  23. if resp.StatusCode < http.StatusBadRequest {
  24. return nil
  25. }
  26. apiError := StatusError{StatusCode: resp.StatusCode}
  27. err := json.Unmarshal(body, &apiError)
  28. if err != nil {
  29. // Use the full body as the message if we fail to decode a response.
  30. apiError.ErrorMessage = string(body)
  31. }
  32. return apiError
  33. }
  34. func ClientFromEnvironment() (*Client, error) {
  35. defaultPort := "11434"
  36. scheme, hostport, ok := strings.Cut(os.Getenv("OLLAMA_HOST"), "://")
  37. switch {
  38. case !ok:
  39. scheme, hostport = "http", os.Getenv("OLLAMA_HOST")
  40. case scheme == "http":
  41. defaultPort = "80"
  42. case scheme == "https":
  43. defaultPort = "443"
  44. }
  45. // trim trailing slashes
  46. hostport = strings.TrimRight(hostport, "/")
  47. host, port, err := net.SplitHostPort(hostport)
  48. if err != nil {
  49. host, port = "127.0.0.1", defaultPort
  50. if ip := net.ParseIP(strings.Trim(hostport, "[]")); ip != nil {
  51. host = ip.String()
  52. } else if hostport != "" {
  53. host = hostport
  54. }
  55. }
  56. client := Client{
  57. base: &url.URL{
  58. Scheme: scheme,
  59. Host: net.JoinHostPort(host, port),
  60. },
  61. }
  62. mockRequest, err := http.NewRequest(http.MethodHead, client.base.String(), nil)
  63. if err != nil {
  64. return nil, err
  65. }
  66. proxyURL, err := http.ProxyFromEnvironment(mockRequest)
  67. if err != nil {
  68. return nil, err
  69. }
  70. client.http = http.Client{
  71. Transport: &http.Transport{
  72. Proxy: http.ProxyURL(proxyURL),
  73. },
  74. }
  75. return &client, nil
  76. }
  77. func (c *Client) do(ctx context.Context, method, path string, reqData, respData any) error {
  78. var reqBody io.Reader
  79. var data []byte
  80. var err error
  81. if reqData != nil {
  82. data, err = json.Marshal(reqData)
  83. if err != nil {
  84. return err
  85. }
  86. reqBody = bytes.NewReader(data)
  87. }
  88. requestURL := c.base.JoinPath(path)
  89. request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), reqBody)
  90. if err != nil {
  91. return err
  92. }
  93. request.Header.Set("Content-Type", "application/json")
  94. request.Header.Set("Accept", "application/json")
  95. request.Header.Set("User-Agent", fmt.Sprintf("ollama/%s (%s %s) Go/%s", version.Version, runtime.GOARCH, runtime.GOOS, runtime.Version()))
  96. respObj, err := c.http.Do(request)
  97. if err != nil {
  98. return err
  99. }
  100. defer respObj.Body.Close()
  101. respBody, err := io.ReadAll(respObj.Body)
  102. if err != nil {
  103. return err
  104. }
  105. if err := checkError(respObj, respBody); err != nil {
  106. return err
  107. }
  108. if len(respBody) > 0 && respData != nil {
  109. if err := json.Unmarshal(respBody, respData); err != nil {
  110. return err
  111. }
  112. }
  113. return nil
  114. }
  115. const maxBufferSize = 512 * format.KiloByte
  116. func (c *Client) stream(ctx context.Context, method, path string, data any, fn func([]byte) error) error {
  117. var buf *bytes.Buffer
  118. if data != nil {
  119. bts, err := json.Marshal(data)
  120. if err != nil {
  121. return err
  122. }
  123. buf = bytes.NewBuffer(bts)
  124. }
  125. requestURL := c.base.JoinPath(path)
  126. request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), buf)
  127. if err != nil {
  128. return err
  129. }
  130. request.Header.Set("Content-Type", "application/json")
  131. request.Header.Set("Accept", "application/x-ndjson")
  132. request.Header.Set("User-Agent", fmt.Sprintf("ollama/%s (%s %s) Go/%s", version.Version, runtime.GOARCH, runtime.GOOS, runtime.Version()))
  133. response, err := c.http.Do(request)
  134. if err != nil {
  135. return err
  136. }
  137. defer response.Body.Close()
  138. scanner := bufio.NewScanner(response.Body)
  139. // increase the buffer size to avoid running out of space
  140. scanBuf := make([]byte, 0, maxBufferSize)
  141. scanner.Buffer(scanBuf, maxBufferSize)
  142. for scanner.Scan() {
  143. var errorResponse struct {
  144. Error string `json:"error,omitempty"`
  145. }
  146. bts := scanner.Bytes()
  147. if err := json.Unmarshal(bts, &errorResponse); err != nil {
  148. return fmt.Errorf("unmarshal: %w", err)
  149. }
  150. if errorResponse.Error != "" {
  151. return fmt.Errorf(errorResponse.Error)
  152. }
  153. if response.StatusCode >= http.StatusBadRequest {
  154. return StatusError{
  155. StatusCode: response.StatusCode,
  156. Status: response.Status,
  157. ErrorMessage: errorResponse.Error,
  158. }
  159. }
  160. if err := fn(bts); err != nil {
  161. return err
  162. }
  163. }
  164. return nil
  165. }
  166. type GenerateResponseFunc func(GenerateResponse) error
  167. func (c *Client) Generate(ctx context.Context, req *GenerateRequest, fn GenerateResponseFunc) error {
  168. return c.stream(ctx, http.MethodPost, "/api/generate", req, func(bts []byte) error {
  169. var resp GenerateResponse
  170. if err := json.Unmarshal(bts, &resp); err != nil {
  171. return err
  172. }
  173. return fn(resp)
  174. })
  175. }
  176. type PullProgressFunc func(ProgressResponse) error
  177. func (c *Client) Pull(ctx context.Context, req *PullRequest, fn PullProgressFunc) error {
  178. return c.stream(ctx, http.MethodPost, "/api/pull", req, func(bts []byte) error {
  179. var resp ProgressResponse
  180. if err := json.Unmarshal(bts, &resp); err != nil {
  181. return err
  182. }
  183. return fn(resp)
  184. })
  185. }
  186. type PushProgressFunc func(ProgressResponse) error
  187. func (c *Client) Push(ctx context.Context, req *PushRequest, fn PushProgressFunc) error {
  188. return c.stream(ctx, http.MethodPost, "/api/push", req, func(bts []byte) error {
  189. var resp ProgressResponse
  190. if err := json.Unmarshal(bts, &resp); err != nil {
  191. return err
  192. }
  193. return fn(resp)
  194. })
  195. }
  196. type CreateProgressFunc func(ProgressResponse) error
  197. func (c *Client) Create(ctx context.Context, req *CreateRequest, fn CreateProgressFunc) error {
  198. return c.stream(ctx, http.MethodPost, "/api/create", req, func(bts []byte) error {
  199. var resp ProgressResponse
  200. if err := json.Unmarshal(bts, &resp); err != nil {
  201. return err
  202. }
  203. return fn(resp)
  204. })
  205. }
  206. func (c *Client) List(ctx context.Context) (*ListResponse, error) {
  207. var lr ListResponse
  208. if err := c.do(ctx, http.MethodGet, "/api/tags", nil, &lr); err != nil {
  209. return nil, err
  210. }
  211. return &lr, nil
  212. }
  213. func (c *Client) Copy(ctx context.Context, req *CopyRequest) error {
  214. if err := c.do(ctx, http.MethodPost, "/api/copy", req, nil); err != nil {
  215. return err
  216. }
  217. return nil
  218. }
  219. func (c *Client) Delete(ctx context.Context, req *DeleteRequest) error {
  220. if err := c.do(ctx, http.MethodDelete, "/api/delete", req, nil); err != nil {
  221. return err
  222. }
  223. return nil
  224. }
  225. func (c *Client) Show(ctx context.Context, req *ShowRequest) (*ShowResponse, error) {
  226. var resp ShowResponse
  227. if err := c.do(ctx, http.MethodPost, "/api/show", req, &resp); err != nil {
  228. return nil, err
  229. }
  230. return &resp, nil
  231. }
  232. func (c *Client) Heartbeat(ctx context.Context) error {
  233. if err := c.do(ctx, http.MethodHead, "/", nil, nil); err != nil {
  234. return err
  235. }
  236. return nil
  237. }