client.go 7.2 KB

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