ollama/api/client.go

119 lines
2.3 KiB
Go
Raw Normal View History

package api
import (
2023-07-04 04:47:00 +00:00
"bufio"
"bytes"
"context"
"encoding/json"
2023-07-07 21:04:43 +00:00
"fmt"
"net/http"
2023-07-06 22:02:10 +00:00
"net/url"
)
2023-07-11 20:05:51 +00:00
type StatusError struct {
StatusCode int
Status string
Message string
}
func (e StatusError) Error() string {
if e.Message != "" {
return fmt.Sprintf("%s: %s", e.Status, e.Message)
}
return e.Status
}
type Client struct {
2023-07-06 22:02:10 +00:00
base url.URL
}
func NewClient(hosts ...string) *Client {
host := "127.0.0.1:11434"
if len(hosts) > 0 {
host = hosts[0]
}
return &Client{
base: url.URL{Scheme: "http", Host: host},
}
}
2023-07-11 20:05:51 +00:00
func (c *Client) stream(ctx context.Context, method, path string, data any, fn func([]byte) error) error {
var buf *bytes.Buffer
if data != nil {
bts, err := json.Marshal(data)
if err != nil {
return err
}
2023-07-06 23:53:14 +00:00
buf = bytes.NewBuffer(bts)
}
request, err := http.NewRequestWithContext(ctx, method, c.base.JoinPath(path).String(), buf)
if err != nil {
return err
}
2023-07-06 22:02:10 +00:00
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
2023-07-04 04:47:00 +00:00
2023-07-06 22:02:10 +00:00
response, err := http.DefaultClient.Do(request)
2023-07-04 04:47:00 +00:00
if err != nil {
return err
}
2023-07-06 22:02:10 +00:00
defer response.Body.Close()
2023-07-04 04:47:00 +00:00
scanner := bufio.NewScanner(response.Body)
for scanner.Scan() {
var errorResponse struct {
2023-07-11 20:05:51 +00:00
Error string `json:"error,omitempty"`
}
bts := scanner.Bytes()
if err := json.Unmarshal(bts, &errorResponse); err != nil {
return fmt.Errorf("unmarshal: %w", err)
}
2023-07-11 20:05:51 +00:00
if response.StatusCode >= 400 {
return StatusError{
StatusCode: response.StatusCode,
Status: response.Status,
Message: errorResponse.Error,
}
}
2023-07-11 20:05:51 +00:00
if err := fn(bts); err != nil {
return err
}
}
2023-07-06 21:05:55 +00:00
return nil
}
2023-07-06 21:05:55 +00:00
type GenerateResponseFunc func(GenerateResponse) error
2023-07-06 21:05:55 +00:00
func (c *Client) Generate(ctx context.Context, req *GenerateRequest, fn GenerateResponseFunc) error {
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)
})
2023-07-04 04:47:00 +00:00
}
2023-07-06 16:24:49 +00:00
2023-07-06 21:05:55 +00:00
type PullProgressFunc func(PullProgress) error
func (c *Client) Pull(ctx context.Context, req *PullRequest, fn PullProgressFunc) error {
return c.stream(ctx, http.MethodPost, "/api/pull", req, func(bts []byte) error {
var resp PullProgress
if err := json.Unmarshal(bts, &resp); err != nil {
return err
}
return fn(resp)
})
2023-07-06 16:24:49 +00:00
}