"...controlnet/train_controlnet_webdataset.py" did not exist on "e7534542a2e736ab54328a7fb3a0a15fe4f31da2"
client.go 6.35 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"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
10
	"net/http"
Michael Yang's avatar
Michael Yang committed
11
	"net/url"
12
	"os"
Michael Yang's avatar
Michael Yang committed
13
	"runtime"
14
	"strings"
Michael Yang's avatar
Michael Yang committed
15
16

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

19
const DefaultHost = "127.0.0.1:11434"
20

21
var envHost = os.Getenv("OLLAMA_HOST")
Jeffrey Morgan's avatar
Jeffrey Morgan committed
22

Patrick Devine's avatar
Patrick Devine committed
23
type Client struct {
24
	Base    url.URL
Patrick Devine's avatar
Patrick Devine committed
25
26
	HTTP    http.Client
	Headers http.Header
Michael Yang's avatar
Michael Yang committed
27
28
}

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

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

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

	return apiError
Michael Yang's avatar
Michael Yang committed
43
44
}

45
46
47
48
49
50
51
52
53
54
55
56
57
// Host returns the default host to use for the client. It is determined in the following order:
// 1. The OLLAMA_HOST environment variable
// 2. The default host (localhost:11434)
func Host() string {
	if envHost != "" {
		return envHost
	}
	return DefaultHost
}

// FromEnv creates a new client using Host() as the host. An error is returns
// if the host is invalid.
func FromEnv() (*Client, error) {
58
59
60
	h := Host()
	if !strings.HasPrefix(h, "http://") && !strings.HasPrefix(h, "https://") {
		h = "http://" + h
61
62
	}

63
64
65
	u, err := url.Parse(h)
	if err != nil {
		return nil, fmt.Errorf("could not parse host: %w", err)
Michael Yang's avatar
Michael Yang committed
66
67
	}

68
69
	if u.Port() == "" {
		u.Host += ":11434"
Patrick Devine's avatar
Patrick Devine committed
70
	}
71
72

	return &Client{Base: *u, HTTP: http.Client{}}, nil
Patrick Devine's avatar
Patrick Devine committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
}

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
87
88
	requestURL := c.Base.JoinPath(path)
	request, err := http.NewRequestWithContext(ctx, method, requestURL.String(), reqBody)
Patrick Devine's avatar
Patrick Devine committed
89
90
91
92
	if err != nil {
		return err
	}

Michael Yang's avatar
Michael Yang committed
93
94
95
	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
96
97

	for k, v := range c.Headers {
Michael Yang's avatar
Michael Yang committed
98
		request.Header[k] = v
Michael Yang's avatar
Michael Yang committed
99
	}
Patrick Devine's avatar
Patrick Devine committed
100

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

124
125
const maxBufferSize = 512 * 1024 // 512KB

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

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

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

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

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

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

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

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

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

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

Michael Yang's avatar
Michael Yang committed
184
185
	return nil
}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
186

Michael Yang's avatar
Michael Yang committed
187
type GenerateResponseFunc func(GenerateResponse) error
Jeffrey Morgan's avatar
Jeffrey Morgan committed
188

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

200
type PullProgressFunc func(ProgressResponse) error
Michael Yang's avatar
Michael Yang committed
201
202

func (c *Client) Pull(ctx context.Context, req *PullRequest, fn PullProgressFunc) error {
203
	return c.stream(ctx, http.MethodPost, "/api/pull", req, func(bts []byte) error {
204
		var resp ProgressResponse
205
206
207
208
209
210
		if err := json.Unmarshal(bts, &resp); err != nil {
			return err
		}

		return fn(resp)
	})
Bruce MacDonald's avatar
Bruce MacDonald committed
211
}
212

213
type PushProgressFunc func(ProgressResponse) error
214
215
216

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

		return fn(resp)
	})
}

226
type CreateProgressFunc func(ProgressResponse) error
227
228
229

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

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

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

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

254
255
256
257
258
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
259
}
260

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

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