client.go 11 KB

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