client.go 9.59 KB
Newer Older
1
2
3
4
5
6
// Package api implements the client-side API for code wishing to interact
// with the ollama service. The methods of the [Client] type correspond to
// the ollama REST API as described in https://github.com/ollama/ollama/blob/main/docs/api.md
//
// The ollama command-line client itself uses this package to interact with
// the backend service.
Jeffrey Morgan's avatar
Jeffrey Morgan committed
7
8
9
package api

import (
Jeffrey Morgan's avatar
Jeffrey Morgan committed
10
	"bufio"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
11
12
13
	"bytes"
	"context"
	"encoding/json"
14
	"fmt"
Patrick Devine's avatar
Patrick Devine committed
15
	"io"
Michael Yang's avatar
Michael Yang committed
16
	"net"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
17
	"net/http"
Michael Yang's avatar
Michael Yang committed
18
	"net/url"
19
	"os"
Michael Yang's avatar
Michael Yang committed
20
	"runtime"
21
	"strings"
Michael Yang's avatar
Michael Yang committed
22

23
24
	"github.com/ollama/ollama/format"
	"github.com/ollama/ollama/version"
25
26
)

27
28
// Client encapsulates client state for interacting with the ollama
// service. Use [ClientFromEnvironment] to create new Clients.
Patrick Devine's avatar
Patrick Devine committed
29
type Client struct {
Michael Yang's avatar
Michael Yang committed
30
	base *url.URL
Michael Yang's avatar
Michael Yang committed
31
	http *http.Client
Michael Yang's avatar
Michael Yang committed
32
33
}

Patrick Devine's avatar
Patrick Devine committed
34
func checkError(resp *http.Response, body []byte) error {
Michael Yang's avatar
Michael Yang committed
35
	if resp.StatusCode < http.StatusBadRequest {
Patrick Devine's avatar
Patrick Devine committed
36
		return nil
Michael Yang's avatar
Michael Yang committed
37
38
	}

Patrick Devine's avatar
Patrick Devine committed
39
	apiError := StatusError{StatusCode: resp.StatusCode}
Michael Yang's avatar
Michael Yang committed
40

Patrick Devine's avatar
Patrick Devine committed
41
42
43
	err := json.Unmarshal(body, &apiError)
	if err != nil {
		// Use the full body as the message if we fail to decode a response.
44
		apiError.ErrorMessage = string(body)
Patrick Devine's avatar
Patrick Devine committed
45
46
47
	}

	return apiError
Michael Yang's avatar
Michael Yang committed
48
49
}

50
51
52
53
54
55
56
57
58
// ClientFromEnvironment creates a new [Client] using configuration from the
// environment variable OLLAMA_HOST, which points to the network host and
// port on which the ollama service is listenting. The format of this variable
// is:
//
//	<scheme>://<host>:<port>
//
// If the variable is not specified, a default ollama host and port will be
// used.
Michael Yang's avatar
Michael Yang committed
59
func ClientFromEnvironment() (*Client, error) {
Michael Yang's avatar
Michael Yang committed
60
61
	defaultPort := "11434"

Michael Yang's avatar
Michael Yang committed
62
	scheme, hostport, ok := strings.Cut(os.Getenv("OLLAMA_HOST"), "://")
Michael Yang's avatar
Michael Yang committed
63
64
	switch {
	case !ok:
Michael Yang's avatar
Michael Yang committed
65
		scheme, hostport = "http", os.Getenv("OLLAMA_HOST")
Michael Yang's avatar
Michael Yang committed
66
67
68
69
	case scheme == "http":
		defaultPort = "80"
	case scheme == "https":
		defaultPort = "443"
Michael Yang's avatar
Michael Yang committed
70
71
	}

Michael Yang's avatar
Michael Yang committed
72
73
74
	// trim trailing slashes
	hostport = strings.TrimRight(hostport, "/")

Michael Yang's avatar
Michael Yang committed
75
76
	host, port, err := net.SplitHostPort(hostport)
	if err != nil {
Michael Yang's avatar
Michael Yang committed
77
		host, port = "127.0.0.1", defaultPort
Michael Yang's avatar
Michael Yang committed
78
		if ip := net.ParseIP(strings.Trim(hostport, "[]")); ip != nil {
Michael Yang's avatar
Michael Yang committed
79
			host = ip.String()
Michael Yang's avatar
Michael Yang committed
80
81
		} else if hostport != "" {
			host = hostport
Michael Yang's avatar
Michael Yang committed
82
83
84
		}
	}

Michael Yang's avatar
Michael Yang committed
85
	return &Client{
Michael Yang's avatar
Michael Yang committed
86
87
88
89
		base: &url.URL{
			Scheme: scheme,
			Host:   net.JoinHostPort(host, port),
		},
Michael Yang's avatar
Michael Yang committed
90
91
		http: http.DefaultClient,
	}, nil
Patrick Devine's avatar
Patrick Devine committed
92
93
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
94
95
96
97
98
99
100
func NewClient(base *url.URL, http *http.Client) *Client {
	return &Client{
		base: base,
		http: http,
	}
}

Patrick Devine's avatar
Patrick Devine committed
101
102
103
104
func (c *Client) do(ctx context.Context, method, path string, reqData, respData any) error {
	var reqBody io.Reader
	var data []byte
	var err error
Michael Yang's avatar
Michael Yang committed
105
106
107
108
109
110
111
112

	switch reqData := reqData.(type) {
	case io.Reader:
		// reqData is already an io.Reader
		reqBody = reqData
	case nil:
		// noop
	default:
Patrick Devine's avatar
Patrick Devine committed
113
114
115
116
		data, err = json.Marshal(reqData)
		if err != nil {
			return err
		}
Michael Yang's avatar
Michael Yang committed
117

Patrick Devine's avatar
Patrick Devine committed
118
119
120
		reqBody = bytes.NewReader(data)
	}

Michael Yang's avatar
Michael Yang committed
121
	requestURL := c.base.JoinPath(path)
Michael Yang's avatar
Michael Yang committed
122
	request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), reqBody)
Patrick Devine's avatar
Patrick Devine committed
123
124
125
126
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
127
128
129
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Accept", "application/json")
	request.Header.Set("User-Agent", fmt.Sprintf("ollama/%s (%s %s) Go/%s", version.Version, runtime.GOARCH, runtime.GOOS, runtime.Version()))
Patrick Devine's avatar
Patrick Devine committed
130

Michael Yang's avatar
Michael Yang committed
131
	respObj, err := c.http.Do(request)
Patrick Devine's avatar
Patrick Devine committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
	if err != nil {
		return err
	}
	defer respObj.Body.Close()

	respBody, err := io.ReadAll(respObj.Body)
	if err != nil {
		return err
	}

	if err := checkError(respObj, respBody); err != nil {
		return err
	}

	if len(respBody) > 0 && respData != nil {
		if err := json.Unmarshal(respBody, respData); err != nil {
			return err
		}
	}
	return nil
Jeffrey Morgan's avatar
Jeffrey Morgan committed
152
153
}

Michael Yang's avatar
Michael Yang committed
154
const maxBufferSize = 512 * format.KiloByte
155

Michael Yang's avatar
Michael Yang committed
156
func (c *Client) stream(ctx context.Context, method, path string, data any, fn func([]byte) error) error {
157
158
159
160
161
162
	var buf *bytes.Buffer
	if data != nil {
		bts, err := json.Marshal(data)
		if err != nil {
			return err
		}
Michael Yang's avatar
Michael Yang committed
163

164
		buf = bytes.NewBuffer(bts)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
165
166
	}

Michael Yang's avatar
Michael Yang committed
167
	requestURL := c.base.JoinPath(path)
Michael Yang's avatar
Michael Yang committed
168
	request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), buf)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
169
170
171
172
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
173
	request.Header.Set("Content-Type", "application/json")
174
	request.Header.Set("Accept", "application/x-ndjson")
Michael Yang's avatar
Michael Yang committed
175
	request.Header.Set("User-Agent", fmt.Sprintf("ollama/%s (%s %s) Go/%s", version.Version, runtime.GOARCH, runtime.GOOS, runtime.Version()))
Jeffrey Morgan's avatar
Jeffrey Morgan committed
176

Michael Yang's avatar
Michael Yang committed
177
	response, err := c.http.Do(request)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
178
179
180
	if err != nil {
		return err
	}
Michael Yang's avatar
Michael Yang committed
181
	defer response.Body.Close()
Jeffrey Morgan's avatar
Jeffrey Morgan committed
182

183
	scanner := bufio.NewScanner(response.Body)
184
185
186
	// increase the buffer size to avoid running out of space
	scanBuf := make([]byte, 0, maxBufferSize)
	scanner.Buffer(scanBuf, maxBufferSize)
187
188
	for scanner.Scan() {
		var errorResponse struct {
Michael Yang's avatar
Michael Yang committed
189
			Error string `json:"error,omitempty"`
190
191
192
193
194
195
196
		}

		bts := scanner.Bytes()
		if err := json.Unmarshal(bts, &errorResponse); err != nil {
			return fmt.Errorf("unmarshal: %w", err)
		}

Michael Yang's avatar
Michael Yang committed
197
		if errorResponse.Error != "" {
198
			return fmt.Errorf(errorResponse.Error)
Michael Yang's avatar
Michael Yang committed
199
200
		}

Michael Yang's avatar
Michael Yang committed
201
		if response.StatusCode >= http.StatusBadRequest {
Michael Yang's avatar
Michael Yang committed
202
			return StatusError{
203
204
205
				StatusCode:   response.StatusCode,
				Status:       response.Status,
				ErrorMessage: errorResponse.Error,
Michael Yang's avatar
Michael Yang committed
206
			}
207
208
		}

Michael Yang's avatar
Michael Yang committed
209
		if err := fn(bts); err != nil {
210
			return err
Jeffrey Morgan's avatar
Jeffrey Morgan committed
211
212
213
		}
	}

Michael Yang's avatar
Michael Yang committed
214
215
	return nil
}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
216

217
218
219
// GenerateResponseFunc is a function that [Client.Generate] invokes every time
// a response is received from the service. If this function returns an error,
// [Client.Generate] will stop generating and return this error.
Michael Yang's avatar
Michael Yang committed
220
type GenerateResponseFunc func(GenerateResponse) error
Jeffrey Morgan's avatar
Jeffrey Morgan committed
221

222
223
224
// Generate generates a response for a given prompt. The req parameter should
// be populated with prompt details. fn is called for each response (there may
// be multiple responses, e.g. in case streaming is enabled).
Michael Yang's avatar
Michael Yang committed
225
func (c *Client) Generate(ctx context.Context, req *GenerateRequest, fn GenerateResponseFunc) error {
226
227
228
229
230
231
232
233
	return c.stream(ctx, http.MethodPost, "/api/generate", req, func(bts []byte) error {
		var resp GenerateResponse
		if err := json.Unmarshal(bts, &resp); err != nil {
			return err
		}

		return fn(resp)
	})
Jeffrey Morgan's avatar
Jeffrey Morgan committed
234
}
Bruce MacDonald's avatar
Bruce MacDonald committed
235

236
237
238
// ChatResponseFunc is a function that [Client.Chat] invokes every time
// a response is received from the service. If this function returns an error,
// [Client.Chat] will stop generating and return this error.
Bruce MacDonald's avatar
Bruce MacDonald committed
239
240
type ChatResponseFunc func(ChatResponse) error

241
242
243
244
// Chat generates the next message in a chat. [ChatRequest] may contain a
// sequence of messages which can be used to maintain chat history with a model.
// fn is called for each response (there may be multiple responses, e.g. if case
// streaming is enabled).
Bruce MacDonald's avatar
Bruce MacDonald committed
245
246
247
248
249
250
251
252
253
254
255
func (c *Client) Chat(ctx context.Context, req *ChatRequest, fn ChatResponseFunc) error {
	return c.stream(ctx, http.MethodPost, "/api/chat", req, func(bts []byte) error {
		var resp ChatResponse
		if err := json.Unmarshal(bts, &resp); err != nil {
			return err
		}

		return fn(resp)
	})
}

256
257
258
// PullProgressFunc is a function that [Client.Pull] invokes every time there
// is progress with a "pull" request sent to the service. If this function
// returns an error, [Client.Pull] will stop the process and return this error.
259
type PullProgressFunc func(ProgressResponse) error
Michael Yang's avatar
Michael Yang committed
260

261
262
263
// Pull downloads a model from the ollama library. fn is called each time
// progress is made on the request and can be used to display a progress bar,
// etc.
Michael Yang's avatar
Michael Yang committed
264
func (c *Client) Pull(ctx context.Context, req *PullRequest, fn PullProgressFunc) error {
265
	return c.stream(ctx, http.MethodPost, "/api/pull", req, func(bts []byte) error {
266
		var resp ProgressResponse
267
268
269
270
271
272
		if err := json.Unmarshal(bts, &resp); err != nil {
			return err
		}

		return fn(resp)
	})
Bruce MacDonald's avatar
Bruce MacDonald committed
273
}
274

275
type PushProgressFunc func(ProgressResponse) error
276
277
278

func (c *Client) Push(ctx context.Context, req *PushRequest, fn PushProgressFunc) error {
	return c.stream(ctx, http.MethodPost, "/api/push", req, func(bts []byte) error {
279
		var resp ProgressResponse
280
281
282
283
284
285
286
287
		if err := json.Unmarshal(bts, &resp); err != nil {
			return err
		}

		return fn(resp)
	})
}

288
type CreateProgressFunc func(ProgressResponse) error
289
290
291

func (c *Client) Create(ctx context.Context, req *CreateRequest, fn CreateProgressFunc) error {
	return c.stream(ctx, http.MethodPost, "/api/create", req, func(bts []byte) error {
292
		var resp ProgressResponse
293
294
295
296
297
298
299
		if err := json.Unmarshal(bts, &resp); err != nil {
			return err
		}

		return fn(resp)
	})
}
Patrick Devine's avatar
Patrick Devine committed
300
301
302
303
304
305
306
307

func (c *Client) List(ctx context.Context) (*ListResponse, error) {
	var lr ListResponse
	if err := c.do(ctx, http.MethodGet, "/api/tags", nil, &lr); err != nil {
		return nil, err
	}
	return &lr, nil
}
308

Patrick Devine's avatar
Patrick Devine committed
309
310
311
312
313
314
315
func (c *Client) Copy(ctx context.Context, req *CopyRequest) error {
	if err := c.do(ctx, http.MethodPost, "/api/copy", req, nil); err != nil {
		return err
	}
	return nil
}

316
317
318
319
320
func (c *Client) Delete(ctx context.Context, req *DeleteRequest) error {
	if err := c.do(ctx, http.MethodDelete, "/api/delete", req, nil); err != nil {
		return err
	}
	return nil
321
}
322

Patrick Devine's avatar
Patrick Devine committed
323
324
325
326
327
328
329
330
func (c *Client) Show(ctx context.Context, req *ShowRequest) (*ShowResponse, error) {
	var resp ShowResponse
	if err := c.do(ctx, http.MethodPost, "/api/show", req, &resp); err != nil {
		return nil, err
	}
	return &resp, nil
}

331
func (c *Client) Heartbeat(ctx context.Context) error {
Bruce MacDonald's avatar
Bruce MacDonald committed
332
	if err := c.do(ctx, http.MethodHead, "/", nil, nil); err != nil {
333
334
335
336
		return err
	}
	return nil
}
Brian Murray's avatar
Brian Murray committed
337
338
339
340
341
342
343
func (c *Client) Embeddings(ctx context.Context, req *EmbeddingRequest) (*EmbeddingResponse, error) {
	var resp EmbeddingResponse
	if err := c.do(ctx, http.MethodPost, "/api/embeddings", req, &resp); err != nil {
		return nil, err
	}
	return &resp, nil
}
Michael Yang's avatar
Michael Yang committed
344

Michael Yang's avatar
Michael Yang committed
345
func (c *Client) CreateBlob(ctx context.Context, digest string, r io.Reader) error {
346
	return c.do(ctx, http.MethodPost, fmt.Sprintf("/api/blobs/%s", digest), r, nil)
Michael Yang's avatar
Michael Yang committed
347
}
Michael Yang's avatar
Michael Yang committed
348
349
350
351
352
353
354
355
356
357
358
359

func (c *Client) Version(ctx context.Context) (string, error) {
	var version struct {
		Version string `json:"version"`
	}

	if err := c.do(ctx, http.MethodGet, "/api/version", nil, &version); err != nil {
		return "", err
	}

	return version.Version, nil
}