cmd: support OLLAMA_CLIENT_HOST environment variable (#262)

* cmd: support OLLAMA_HOST environment variable

This commit adds support for the OLLAMA_HOST environment
variable. This variable can be used to specify the host to which
the client should connect. This is useful when the client is
running somewhere other than the host where the server is running.

The new api.FromEnv function is used to read configure clients from the
environment. Clients wishing to use the environment variable being
consistent with the Ollama CLI can use this new function.

* Update api/client.go

Co-authored-by: Jeffrey Morgan <jmorganca@gmail.com>

* Update api/client.go

Co-authored-by: Jeffrey Morgan <jmorganca@gmail.com>

---------

Co-authored-by: Jeffrey Morgan <jmorganca@gmail.com>
This commit is contained in:
Blake Mizerany 2023-08-16 08:03:48 -07:00 committed by GitHub
parent d15c7622b9
commit 67e593e355
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 64 additions and 13 deletions

View file

@ -9,10 +9,17 @@ import (
"io"
"net/http"
"net/url"
"os"
)
const DefaultHost = "localhost:11434"
var (
envHost = os.Getenv("OLLAMA_HOST")
)
type Client struct {
base url.URL
Base url.URL
HTTP http.Client
Headers http.Header
}
@ -33,14 +40,34 @@ func checkError(resp *http.Response, body []byte) error {
return apiError
}
// 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) {
u, err := url.Parse(Host())
if err != nil {
return nil, err
}
return &Client{Base: *u}, nil
}
func NewClient(hosts ...string) *Client {
host := "127.0.0.1:11434"
host := DefaultHost
if len(hosts) > 0 {
host = hosts[0]
}
return &Client{
base: url.URL{Scheme: "http", Host: host},
Base: url.URL{Scheme: "http", Host: host},
HTTP: http.Client{},
}
}
@ -57,7 +84,7 @@ func (c *Client) do(ctx context.Context, method, path string, reqData, respData
reqBody = bytes.NewReader(data)
}
url := c.base.JoinPath(path).String()
url := c.Base.JoinPath(path).String()
req, err := http.NewRequestWithContext(ctx, method, url, reqBody)
if err != nil {
@ -105,7 +132,7 @@ func (c *Client) stream(ctx context.Context, method, path string, data any, fn f
buf = bytes.NewBuffer(bts)
}
request, err := http.NewRequestWithContext(ctx, method, c.base.JoinPath(path).String(), buf)
request, err := http.NewRequestWithContext(ctx, method, c.Base.JoinPath(path).String(), buf)
if err != nil {
return err
}