Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

openai.go

108 lines2.0 KB

1package main
2​
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/json"
8 "fmt"
9 "io"
10 "net/http"
11 "os"
12 "strings"
14​
15func streamOpenAI(
16 ctx context.Context,
17 model string,
18 system string,
19 messages []chatMessage,
20 emit func(string) error,
21) error {
22 apiKey := os.Getenv("OPENAI_API_KEY")
23 if apiKey == "" {
24 return fmt.Errorf("OPENAI_API_KEY is not set")
25 }
26​
27 openAIMessages := make([]map[string]string, 0, len(messages)+1)
28 if system != "" {
29 openAIMessages = append(openAIMessages, map[string]string{
30 "role": "system",
31 "content": system,
32 })
33 }
34 for _, msg := range messages {
35 openAIMessages = append(openAIMessages, map[string]string{
36 "role": msg.Role,
37 "content": msg.Content,
38 })
39 }
40​
41 payload, err := json.Marshal(map[string]any{
42 "model": model,
43 "messages": openAIMessages,
44 "stream": true,
45 })
46 if err != nil {
47 return err
48 }
49​
50 req, err := http.NewRequestWithContext(
51 ctx,
52 http.MethodPost,
53 "https://api.openai.com/v1/chat/completions",
54 bytes.NewReader(payload),
55 )
56 if err != nil {
57 return err
58 }
59 req.Header.Set("Authorization", "Bearer "+apiKey)
60 req.Header.Set("Content-Type", "application/json")
61​
62 resp, err := http.DefaultClient.Do(req)
63 if err != nil {
64 return err
65 }
66 defer resp.Body.Close()
67​
68 if resp.StatusCode >= 400 {
69 body, _ := io.ReadAll(resp.Body)
70 return fmt.Errorf("openai request failed (%d): %s", resp.StatusCode, strings.TrimSpace(string(body)))
71 }
72​
73 scanner := bufio.NewScanner(resp.Body)
74 for scanner.Scan() {
75 if ctx.Err() != nil {
76 return ctx.Err()
77 }
78​
79 line := scanner.Text()
80 if !strings.HasPrefix(line, "data: ") {
81 continue
82 }
83​
84 data := strings.TrimPrefix(line, "data: ")
85 if data == "[DONE]" {
86 break
87 }
88​
89 var chunk struct {
90 Choices []struct {
91 Delta struct {
92 Content string `json:"content"`
93 } `json:"delta"`
94 } `json:"choices"`
95 }
96 if err := json.Unmarshal([]byte(data), &chunk); err != nil {
97 continue
98 }
99 if len(chunk.Choices) == 0 {
100 continue
101 }
102 if err := emit(chunk.Choices[0].Delta.Content); err != nil {
103 return err
104 }
105 }
106​
107 return scanner.Err()