client.go 6.3 KB
Newer Older
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1
2
3
package api

import (
Jeffrey Morgan's avatar
Jeffrey Morgan committed
4
	"bufio"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
5
6
7
	"bytes"
	"context"
	"encoding/json"
8
	"fmt"
Patrick Devine's avatar
Patrick Devine committed
9
	"io"
Michael Yang's avatar
Michael Yang committed
10
	"net"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
11
	"net/http"
Michael Yang's avatar
Michael Yang committed
12
	"net/url"
13
	"os"
Michael Yang's avatar
Michael Yang committed
14
	"runtime"
15
	"strings"
Michael Yang's avatar
Michael Yang committed
16
17

	"github.com/jmorganca/ollama/version"
18
19
)

Patrick Devine's avatar
Patrick Devine committed
20
type Client struct {
Michael Yang's avatar
Michael Yang committed
21
22
	base *url.URL
	http http.Client
Michael Yang's avatar
Michael Yang committed
23
24
}

Patrick Devine's avatar
Patrick Devine committed
25
func checkError(resp *http.Response, body []byte) error {
Michael Yang's avatar
Michael Yang committed
26
	if resp.StatusCode < http.StatusBadRequest {
Patrick Devine's avatar
Patrick Devine committed
27
		return nil
Michael Yang's avatar
Michael Yang committed
28
29
	}

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

Patrick Devine's avatar
Patrick Devine committed
32
33
34
	err := json.Unmarshal(body, &apiError)
	if err != nil {
		// Use the full body as the message if we fail to decode a response.
35
		apiError.ErrorMessage = string(body)
Patrick Devine's avatar
Patrick Devine committed
36
37
38
	}

	return apiError
Michael Yang's avatar
Michael Yang committed
39
40
}

Michael Yang's avatar
Michael Yang committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
func ClientFromEnvironment() (*Client, error) {
	scheme, hostport, ok := strings.Cut(os.Getenv("OLLAMA_HOST"), "://")
	if !ok {
		scheme, hostport = "http", os.Getenv("OLLAMA_HOST")
	}

	host, port, err := net.SplitHostPort(hostport)
	if err != nil {
		host, port = "127.0.0.1", "11434"
		if ip := net.ParseIP(strings.Trim(os.Getenv("OLLAMA_HOST"), "[]")); ip != nil {
			host = ip.String()
		}
	}

	client := Client{
		base: &url.URL{
			Scheme: scheme,
			Host:   net.JoinHostPort(host, port),
		},
60
61
	}

Michael Yang's avatar
Michael Yang committed
62
63
64
	mockRequest, err := http.NewRequest("HEAD", client.base.String(), nil)
	if err != nil {
		return nil, err
65
66
	}

Michael Yang's avatar
Michael Yang committed
67
	proxyURL, err := http.ProxyFromEnvironment(mockRequest)
68
	if err != nil {
Michael Yang's avatar
Michael Yang committed
69
		return nil, err
Michael Yang's avatar
Michael Yang committed
70
71
	}

Michael Yang's avatar
Michael Yang committed
72
73
74
75
	client.http = http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyURL(proxyURL),
		},
Patrick Devine's avatar
Patrick Devine committed
76
	}
77

Michael Yang's avatar
Michael Yang committed
78
	return &client, nil
Patrick Devine's avatar
Patrick Devine committed
79
80
81
82
83
84
85
86
87
88
89
90
91
92
}

func (c *Client) do(ctx context.Context, method, path string, reqData, respData any) error {
	var reqBody io.Reader
	var data []byte
	var err error
	if reqData != nil {
		data, err = json.Marshal(reqData)
		if err != nil {
			return err
		}
		reqBody = bytes.NewReader(data)
	}

Michael Yang's avatar
Michael Yang committed
93
	requestURL := c.base.JoinPath(path)
Michael Yang's avatar
Michael Yang committed
94
	request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), reqBody)
Patrick Devine's avatar
Patrick Devine committed
95
96
97
98
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
99
100
101
	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
102

Michael Yang's avatar
Michael Yang committed
103
	respObj, err := c.http.Do(request)
Patrick Devine's avatar
Patrick Devine committed
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
	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
124
125
}

126
127
const maxBufferSize = 512 * 1024 // 512KB

Michael Yang's avatar
Michael Yang committed
128
func (c *Client) stream(ctx context.Context, method, path string, data any, fn func([]byte) error) error {
129
130
131
132
133
134
	var buf *bytes.Buffer
	if data != nil {
		bts, err := json.Marshal(data)
		if err != nil {
			return err
		}
Michael Yang's avatar
Michael Yang committed
135

136
		buf = bytes.NewBuffer(bts)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
137
138
	}

Michael Yang's avatar
Michael Yang committed
139
	requestURL := c.base.JoinPath(path)
Michael Yang's avatar
Michael Yang committed
140
	request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), buf)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
141
142
143
144
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
145
146
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Accept", "application/json")
Michael Yang's avatar
Michael Yang committed
147
	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
148

Michael Yang's avatar
Michael Yang committed
149
	response, err := c.http.Do(request)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
150
151
152
	if err != nil {
		return err
	}
Michael Yang's avatar
Michael Yang committed
153
	defer response.Body.Close()
Jeffrey Morgan's avatar
Jeffrey Morgan committed
154

155
	scanner := bufio.NewScanner(response.Body)
156
157
158
	// increase the buffer size to avoid running out of space
	scanBuf := make([]byte, 0, maxBufferSize)
	scanner.Buffer(scanBuf, maxBufferSize)
159
160
	for scanner.Scan() {
		var errorResponse struct {
Michael Yang's avatar
Michael Yang committed
161
			Error string `json:"error,omitempty"`
162
163
164
165
166
167
168
		}

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

Michael Yang's avatar
Michael Yang committed
169
		if errorResponse.Error != "" {
170
			return fmt.Errorf(errorResponse.Error)
Michael Yang's avatar
Michael Yang committed
171
172
		}

Michael Yang's avatar
Michael Yang committed
173
		if response.StatusCode >= http.StatusBadRequest {
Michael Yang's avatar
Michael Yang committed
174
			return StatusError{
175
176
177
				StatusCode:   response.StatusCode,
				Status:       response.Status,
				ErrorMessage: errorResponse.Error,
Michael Yang's avatar
Michael Yang committed
178
			}
179
180
		}

Michael Yang's avatar
Michael Yang committed
181
		if err := fn(bts); err != nil {
182
			return err
Jeffrey Morgan's avatar
Jeffrey Morgan committed
183
184
185
		}
	}

Michael Yang's avatar
Michael Yang committed
186
187
	return nil
}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
188

Michael Yang's avatar
Michael Yang committed
189
type GenerateResponseFunc func(GenerateResponse) error
Jeffrey Morgan's avatar
Jeffrey Morgan committed
190

Michael Yang's avatar
Michael Yang committed
191
func (c *Client) Generate(ctx context.Context, req *GenerateRequest, fn GenerateResponseFunc) error {
192
193
194
195
196
197
198
199
	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
200
}
Bruce MacDonald's avatar
Bruce MacDonald committed
201

202
type PullProgressFunc func(ProgressResponse) error
Michael Yang's avatar
Michael Yang committed
203
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
208
209
210
211
212
		if err := json.Unmarshal(bts, &resp); err != nil {
			return err
		}

		return fn(resp)
	})
Bruce MacDonald's avatar
Bruce MacDonald committed
213
}
214

215
type PushProgressFunc func(ProgressResponse) error
216
217
218

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 {
219
		var resp ProgressResponse
220
221
222
223
224
225
226
227
		if err := json.Unmarshal(bts, &resp); err != nil {
			return err
		}

		return fn(resp)
	})
}

228
type CreateProgressFunc func(ProgressResponse) error
229
230
231

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 {
232
		var resp ProgressResponse
233
234
235
236
237
238
239
		if err := json.Unmarshal(bts, &resp); err != nil {
			return err
		}

		return fn(resp)
	})
}
Patrick Devine's avatar
Patrick Devine committed
240
241
242
243
244
245
246
247

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
}
248

Patrick Devine's avatar
Patrick Devine committed
249
250
251
252
253
254
255
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
}

256
257
258
259
260
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
261
}
262

Patrick Devine's avatar
Patrick Devine committed
263
264
265
266
267
268
269
270
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
}

271
func (c *Client) Heartbeat(ctx context.Context) error {
Bruce MacDonald's avatar
Bruce MacDonald committed
272
	if err := c.do(ctx, http.MethodHead, "/", nil, nil); err != nil {
273
274
275
276
		return err
	}
	return nil
}