Skip to content

Commit f0bc1bb

Browse files
committed
Adding openai to api
1 parent c29c592 commit f0bc1bb

File tree

15 files changed

+72
-3
lines changed

15 files changed

+72
-3
lines changed

cmd/api/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ func main() {
2626
ipifyRegister(flags)
2727
mistralRegister(flags)
2828
newsapiRegister(flags)
29+
openaiRegister(flags)
2930
samRegister(flags)
3031
weatherapiRegister(flags)
3132

cmd/api/openai.go

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
7+
// Packages
8+
"github.com/djthorpe/go-tablewriter"
9+
client "github.com/mutablelogic/go-client"
10+
openai "github.com/mutablelogic/go-client/pkg/openai"
11+
)
12+
13+
///////////////////////////////////////////////////////////////////////////////
14+
// GLOBALS
15+
16+
var (
17+
openaiName = "openai"
18+
openaiClient *openai.Client
19+
)
20+
21+
///////////////////////////////////////////////////////////////////////////////
22+
// LIFECYCLE
23+
24+
func openaiRegister(flags *Flags) {
25+
// Register flags
26+
flags.String(openaiName, "openai-api-key", "${OPENAI_API_KEY}", "OpenAI API key")
27+
28+
// Register commands
29+
flags.Register(Cmd{
30+
Name: openaiName,
31+
Description: "Interact with OpenAI, from https://platform.openai.com/docs/api-reference",
32+
Parse: openaiParse,
33+
Fn: []Fn{
34+
{Name: "models", Call: openaiModels, Description: "Gets a list of available models"},
35+
{Name: "model", Call: openaiModel, Description: "Return model information", MinArgs: 1, MaxArgs: 1, Syntax: "<model>"},
36+
},
37+
})
38+
}
39+
40+
func openaiParse(flags *Flags, opts ...client.ClientOpt) error {
41+
apiKey := flags.GetString("openai-api-key")
42+
if apiKey == "" {
43+
return fmt.Errorf("missing -openai-api-key flag")
44+
} else if client, err := openai.New(apiKey, opts...); err != nil {
45+
return err
46+
} else {
47+
openaiClient = client
48+
}
49+
50+
// Return success
51+
return nil
52+
}
53+
54+
///////////////////////////////////////////////////////////////////////////////
55+
// METHODS
56+
57+
func openaiModels(ctx context.Context, w *tablewriter.Writer, args []string) error {
58+
models, err := openaiClient.ListModels()
59+
if err != nil {
60+
return err
61+
}
62+
return w.Write(models)
63+
}
64+
65+
func openaiModel(ctx context.Context, w *tablewriter.Writer, args []string) error {
66+
model, err := openaiClient.GetModel(args[0])
67+
if err != nil {
68+
return err
69+
}
70+
return w.Write(model)
71+
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)