client.go 6.4 KB

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