x

Programs, configuration and documentation that don't fit anywhere else
Log | Files | Refs | README | LICENSE

commit 5a8cb9306ea5b15940ed7ef671f47d6b3f71c3b8
parent 7d5f9562c75185f9fe13bbc326577dc860146124
Author: Oliver Lowe <o@olowe.co>
Date:   Sun, 12 Jan 2025 17:08:31 +1100

openai: add list models

Diffstat:
Msrc/openai/openai.go | 37+++++++++++++++++++++++++++++++++++++
1 file changed, 37 insertions(+), 0 deletions(-)

diff --git a/src/openai/openai.go b/src/openai/openai.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "strings" + "time" ) type Role string @@ -29,6 +30,15 @@ type Chat struct { } `json:"response_format,omitempty"` } +type Model struct { + ID string + Name string + Description string + Aliases []string + MaxContextLength int + Deprecation time.Time +} + type Client struct { *http.Client Token string @@ -106,3 +116,30 @@ func (c *Client) Complete(chat *Chat) (*Message, error) { } return &cresp.Choices[0].Message, nil } + +func (c *Client) Models() ([]Model, error) { + u := c.BaseURL + "/v1/models" + req, err := http.NewRequest(http.MethodGet, u, nil) + if err != nil { + return nil, err + } + resp, err := c.do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + var aerr apiError + if err := json.NewDecoder(resp.Body).Decode(&aerr); err != nil { + return nil, fmt.Errorf(resp.Status) + } + return nil, aerr + } + v := struct { + Data []Model + }{} + if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + return nil, fmt.Errorf("decode response: %w", err) + } + return v.Data, nil +}