-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmain.go
More file actions
60 lines (51 loc) · 1.17 KB
/
main.go
File metadata and controls
60 lines (51 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"context"
"fmt"
"log"
"go.jetify.com/ai"
"go.jetify.com/ai/api"
"go.jetify.com/ai/provider/openai"
)
func example() error {
// Create a model
model := openai.NewLanguageModel("gpt-4o-mini")
// Stream text
response, err := ai.StreamTextStr(
context.Background(),
"Explain what artificial intelligence is in simple terms",
ai.WithModel(model),
ai.WithMaxOutputTokens(100),
)
if err != nil {
return err
}
// Print the streaming response:
printStreamResponse(response)
return nil
}
func printStreamResponse(response *api.StreamResponse) {
fmt.Print("AI: ")
for event := range response.Stream {
switch e := event.(type) {
case *api.TextDeltaEvent:
// Print text delta events as they arrive
fmt.Print(e.TextDelta)
case *api.FinishEvent:
// Print final information
fmt.Printf("\n\nFinish Reason: %s\n", e.FinishReason)
fmt.Printf("Usage: Input=%d, Output=%d, Total=%d tokens\n",
e.Usage.InputTokens,
e.Usage.OutputTokens,
e.Usage.TotalTokens)
case *api.ErrorEvent:
// Handle errors
fmt.Printf("\nError: %s\n", e.Error())
}
}
}
func main() {
if err := example(); err != nil {
log.Fatal(err)
}
}