client.go 11 KB

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