main
Raw Download raw file
 1package main
 2
 3import (
 4	"context"
 5	"fmt"
 6	"io"
 7	"os"
 8	"strings"
 9
10	"github.com/spf13/cobra"
11)
12
13type M8B interface {
14	Complete(ctx context.Context, prompt string) (<-chan string, error)
15}
16
17func Execute() error {
18	root := &cobra.Command{
19		Use:  "8b",
20		RunE: m8b,
21	}
22
23	return root.Execute()
24}
25
26func m8b(cmd *cobra.Command, args []string) error {
27
28	var prompt string
29	stat, err := os.Stdin.Stat()
30	if err != nil {
31		err := fmt.Errorf("reading stdin: %w", err)
32		return err
33	}
34	prompt = strings.Join(args, " ")
35	if (stat.Mode() & os.ModeCharDevice) == 0 {
36		// stdin is being piped
37		bytes, err := io.ReadAll(os.Stdin)
38		if err != nil {
39			fmt.Fprintln(os.Stderr, "Error reading stdin:", err)
40			os.Exit(1)
41		}
42		prompt = string(bytes)
43	}
44
45	client, err := NewOpenAIClient("gpt-4o")
46	if err != nil {
47		err := fmt.Errorf("setting up client: %w", err)
48		return err
49	}
50
51	ctx := context.TODO()
52	respChan, err := client.Complete(ctx, prompt)
53
54	if err != nil {
55		err := fmt.Errorf("starting client: %w", err)
56		return err
57	}
58
59	for {
60		select {
61		case <-ctx.Done():
62			return nil
63		case token, ok := <-respChan:
64			if !ok {
65				fmt.Println()
66				return nil
67			}
68			fmt.Print(token)
69		}
70	}
71}
72
73func main() {
74	err := Execute()
75	if err != nil {
76		os.Exit(1)
77	}
78}