client.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. // Package api implements the client-side API for code wishing to interact
  2. // with the ollama service. The methods of the [Client] type correspond to
  3. // the ollama REST API as described in [the API documentation].
  4. // The ollama command-line client itself uses this package to interact with
  5. // the backend service.
  6. //
  7. // # Examples
  8. //
  9. // Several examples of using this package are available [in the GitHub
  10. // repository].
  11. //
  12. // [the API documentation]: https://github.com/ollama/ollama/blob/main/docs/api.md
  13. // [in the GitHub repository]: https://github.com/ollama/ollama/tree/main/examples
  14. package api
  15. import (
  16. "bufio"
  17. "bytes"
  18. "context"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "net/http"
  24. "net/url"
  25. "runtime"
  26. "github.com/ollama/ollama/envconfig"
  27. "github.com/ollama/ollama/format"
  28. "github.com/ollama/ollama/version"
  29. )
  30. // Client encapsulates client state for interacting with the ollama
  31. // service. Use [ClientFromEnvironment] to create new Clients.
  32. type Client struct {
  33. base *url.URL
  34. http *http.Client
  35. }
  36. func checkError(resp *http.Response, body []byte) error {
  37. if resp.StatusCode < http.StatusBadRequest {
  38. return nil
  39. }
  40. apiError := StatusError{StatusCode: resp.StatusCode}
  41. err := json.Unmarshal(body, &apiError)
  42. if err != nil {
  43. // Use the full body as the message if we fail to decode a response.
  44. apiError.ErrorMessage = string(body)
  45. }
  46. return apiError
  47. }
  48. // ClientFromEnvironment creates a new [Client] using configuration from the
  49. // environment variable OLLAMA_HOST, which points to the network host and
  50. // port on which the ollama service is listenting. The format of this variable
  51. // is:
  52. //
  53. // <scheme>://<host>:<port>
  54. //
  55. // If the variable is not specified, a default ollama host and port will be
  56. // used.
  57. func ClientFromEnvironment() (*Client, error) {
  58. return &Client{
  59. base: envconfig.Host(),
  60. http: http.DefaultClient,
  61. }, nil
  62. }
  63. func NewClient(base *url.URL, http *http.Client) *Client {
  64. return &Client{
  65. base: base,
  66. http: http,
  67. }
  68. }
  69. func (c *Client) do(ctx context.Context, method, path string, reqData, respData any) error {
  70. var reqBody io.Reader
  71. var data []byte
  72. var err error
  73. switch reqData := reqData.(type) {
  74. case io.Reader:
  75. // reqData is already an io.Reader
  76. reqBody = reqData
  77. case nil:
  78. // noop
  79. default:
  80. data, err = json.Marshal(reqData)
  81. if err != nil {
  82. return err
  83. }
  84. reqBody = bytes.NewReader(data)
  85. }
  86. requestURL := c.base.JoinPath(path)
  87. request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), reqBody)
  88. if err != nil {
  89. return err
  90. }
  91. request.Header.Set("Content-Type", "application/json")
  92. request.Header.Set("Accept", "application/json")
  93. request.Header.Set("User-Agent", fmt.Sprintf("ollama/%s (%s %s) Go/%s", version.Version, runtime.GOARCH, runtime.GOOS, runtime.Version()))
  94. respObj, err := c.http.Do(request)
  95. if err != nil {
  96. return err
  97. }
  98. defer respObj.Body.Close()
  99. respBody, err := io.ReadAll(respObj.Body)
  100. if err != nil {
  101. return err
  102. }
  103. if err := checkError(respObj, respBody); err != nil {
  104. return err
  105. }
  106. if len(respBody) > 0 && respData != nil {
  107. if err := json.Unmarshal(respBody, respData); err != nil {
  108. return err
  109. }
  110. }
  111. return nil
  112. }
  113. const maxBufferSize = 512 * format.KiloByte
  114. func (c *Client) stream(ctx context.Context, method, path string, data any, fn func([]byte) error) error {
  115. var buf *bytes.Buffer
  116. if data != nil {
  117. bts, err := json.Marshal(data)
  118. if err != nil {
  119. return err
  120. }
  121. buf = bytes.NewBuffer(bts)
  122. }
  123. requestURL := c.base.JoinPath(path)
  124. request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), buf)
  125. if err != nil {
  126. return err
  127. }
  128. request.Header.Set("Content-Type", "application/json")
  129. request.Header.Set("Accept", "application/x-ndjson")
  130. request.Header.Set("User-Agent", fmt.Sprintf("ollama/%s (%s %s) Go/%s", version.Version, runtime.GOARCH, runtime.GOOS, runtime.Version()))
  131. response, err := c.http.Do(request)
  132. if err != nil {
  133. return err
  134. }
  135. defer response.Body.Close()
  136. scanner := bufio.NewScanner(response.Body)
  137. // increase the buffer size to avoid running out of space
  138. scanBuf := make([]byte, 0, maxBufferSize)
  139. scanner.Buffer(scanBuf, maxBufferSize)
  140. for scanner.Scan() {
  141. var errorResponse struct {
  142. Error string `json:"error,omitempty"`
  143. }
  144. bts := scanner.Bytes()
  145. if err := json.Unmarshal(bts, &errorResponse); err != nil {
  146. return fmt.Errorf("unmarshal: %w", err)
  147. }
  148. if errorResponse.Error != "" {
  149. return errors.New(errorResponse.Error)
  150. }
  151. if response.StatusCode >= http.StatusBadRequest {
  152. return StatusError{
  153. StatusCode: response.StatusCode,
  154. Status: response.Status,
  155. ErrorMessage: errorResponse.Error,
  156. }
  157. }
  158. if err := fn(bts); err != nil {
  159. return err
  160. }
  161. }
  162. return nil
  163. }
  164. // GenerateResponseFunc is a function that [Client.Generate] invokes every time
  165. // a response is received from the service. If this function returns an error,
  166. // [Client.Generate] will stop generating and return this error.
  167. type GenerateResponseFunc func(GenerateResponse) error
  168. // Generate generates a response for a given prompt. The req parameter should
  169. // be populated with prompt details. fn is called for each response (there may
  170. // be multiple responses, e.g. in case streaming is enabled).
  171. func (c *Client) Generate(ctx context.Context, req *GenerateRequest, fn GenerateResponseFunc) error {
  172. return c.stream(ctx, http.MethodPost, "/api/generate", req, func(bts []byte) error {
  173. var resp GenerateResponse
  174. if err := json.Unmarshal(bts, &resp); err != nil {
  175. return err
  176. }
  177. return fn(resp)
  178. })
  179. }
  180. // ChatResponseFunc is a function that [Client.Chat] invokes every time
  181. // a response is received from the service. If this function returns an error,
  182. // [Client.Chat] will stop generating and return this error.
  183. type ChatResponseFunc func(ChatResponse) error
  184. // Chat generates the next message in a chat. [ChatRequest] may contain a
  185. // sequence of messages which can be used to maintain chat history with a model.
  186. // fn is called for each response (there may be multiple responses, e.g. if case
  187. // streaming is enabled).
  188. func (c *Client) Chat(ctx context.Context, req *ChatRequest, fn ChatResponseFunc) error {
  189. return c.stream(ctx, http.MethodPost, "/api/chat", req, func(bts []byte) error {
  190. var resp ChatResponse
  191. if err := json.Unmarshal(bts, &resp); err != nil {
  192. return err
  193. }
  194. return fn(resp)
  195. })
  196. }
  197. // PullProgressFunc is a function that [Client.Pull] invokes every time there
  198. // is progress with a "pull" request sent to the service. If this function
  199. // returns an error, [Client.Pull] will stop the process and return this error.
  200. type PullProgressFunc func(ProgressResponse) error
  201. // Pull downloads a model from the ollama library. fn is called each time
  202. // progress is made on the request and can be used to display a progress bar,
  203. // etc.
  204. func (c *Client) Pull(ctx context.Context, req *PullRequest, fn PullProgressFunc) error {
  205. return c.stream(ctx, http.MethodPost, "/api/pull", 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. // PushProgressFunc is a function that [Client.Push] invokes when progress is
  214. // made.
  215. // It's similar to other progress function types like [PullProgressFunc].
  216. type PushProgressFunc func(ProgressResponse) error
  217. // Push uploads a model to the model library; requires registering for ollama.ai
  218. // and adding a public key first. fn is called each time progress is made on
  219. // the request and can be used to display a progress bar, etc.
  220. func (c *Client) Push(ctx context.Context, req *PushRequest, fn PushProgressFunc) error {
  221. return c.stream(ctx, http.MethodPost, "/api/push", req, func(bts []byte) error {
  222. var resp ProgressResponse
  223. if err := json.Unmarshal(bts, &resp); err != nil {
  224. return err
  225. }
  226. return fn(resp)
  227. })
  228. }
  229. // CreateProgressFunc is a function that [Client.Create] invokes when progress
  230. // is made.
  231. // It's similar to other progress function types like [PullProgressFunc].
  232. type CreateProgressFunc func(ProgressResponse) error
  233. // Create creates a model from a [Modelfile]. fn is a progress function that
  234. // behaves similarly to other methods (see [Client.Pull]).
  235. //
  236. // [Modelfile]: https://github.com/ollama/ollama/blob/main/docs/modelfile.md
  237. func (c *Client) Create(ctx context.Context, req *CreateRequest, fn CreateProgressFunc) error {
  238. return c.stream(ctx, http.MethodPost, "/api/create", req, func(bts []byte) error {
  239. var resp ProgressResponse
  240. if err := json.Unmarshal(bts, &resp); err != nil {
  241. return err
  242. }
  243. return fn(resp)
  244. })
  245. }
  246. // List lists models that are available locally.
  247. func (c *Client) List(ctx context.Context) (*ListResponse, error) {
  248. var lr ListResponse
  249. if err := c.do(ctx, http.MethodGet, "/api/tags", nil, &lr); err != nil {
  250. return nil, err
  251. }
  252. return &lr, nil
  253. }
  254. // ListRunning lists running models.
  255. func (c *Client) ListRunning(ctx context.Context) (*ProcessResponse, error) {
  256. var lr ProcessResponse
  257. if err := c.do(ctx, http.MethodGet, "/api/ps", nil, &lr); err != nil {
  258. return nil, err
  259. }
  260. return &lr, nil
  261. }
  262. // Copy copies a model - creating a model with another name from an existing
  263. // model.
  264. func (c *Client) Copy(ctx context.Context, req *CopyRequest) error {
  265. if err := c.do(ctx, http.MethodPost, "/api/copy", req, nil); err != nil {
  266. return err
  267. }
  268. return nil
  269. }
  270. // Delete deletes a model and its data.
  271. func (c *Client) Delete(ctx context.Context, req *DeleteRequest) error {
  272. if err := c.do(ctx, http.MethodDelete, "/api/delete", req, nil); err != nil {
  273. return err
  274. }
  275. return nil
  276. }
  277. // Show obtains model information, including details, modelfile, license etc.
  278. func (c *Client) Show(ctx context.Context, req *ShowRequest) (*ShowResponse, error) {
  279. var resp ShowResponse
  280. if err := c.do(ctx, http.MethodPost, "/api/show", req, &resp); err != nil {
  281. return nil, err
  282. }
  283. return &resp, nil
  284. }
  285. // Heartbeat checks if the server has started and is responsive; if yes, it
  286. // returns nil, otherwise an error.
  287. func (c *Client) Heartbeat(ctx context.Context) error {
  288. if err := c.do(ctx, http.MethodHead, "/", nil, nil); err != nil {
  289. return err
  290. }
  291. return nil
  292. }
  293. // Embed generates embeddings from a model.
  294. func (c *Client) Embed(ctx context.Context, req *EmbedRequest) (*EmbedResponse, error) {
  295. var resp EmbedResponse
  296. if err := c.do(ctx, http.MethodPost, "/api/embed", req, &resp); err != nil {
  297. return nil, err
  298. }
  299. return &resp, nil
  300. }
  301. // Embeddings generates an embedding from a model.
  302. func (c *Client) Embeddings(ctx context.Context, req *EmbeddingRequest) (*EmbeddingResponse, error) {
  303. var resp EmbeddingResponse
  304. if err := c.do(ctx, http.MethodPost, "/api/embeddings", req, &resp); err != nil {
  305. return nil, err
  306. }
  307. return &resp, nil
  308. }
  309. // CreateBlob creates a blob from a file on the server. digest is the
  310. // expected SHA256 digest of the file, and r represents the file.
  311. func (c *Client) CreateBlob(ctx context.Context, digest string, r io.Reader) error {
  312. return c.do(ctx, http.MethodPost, fmt.Sprintf("/api/blobs/%s", digest), r, nil)
  313. }
  314. // Version returns the Ollama server version as a string.
  315. func (c *Client) Version(ctx context.Context) (string, error) {
  316. var version struct {
  317. Version string `json:"version"`
  318. }
  319. if err := c.do(ctx, http.MethodGet, "/api/version", nil, &version); err != nil {
  320. return "", err
  321. }
  322. return version.Version, nil
  323. }