-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathmain.go
More file actions
94 lines (78 loc) · 2.16 KB
/
main.go
File metadata and controls
94 lines (78 loc) · 2.16 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"context"
"fmt"
"os"
"github.com/charmbracelet/ai"
"github.com/charmbracelet/ai/providers/openai"
)
func main() {
// Check for API key
apiKey := os.Getenv("OPENAI_API_KEY")
if apiKey == "" {
fmt.Println("Please set OPENAI_API_KEY environment variable")
os.Exit(1)
}
// Create provider and model
provider := openai.New(
openai.WithAPIKey(apiKey),
)
model, err := provider.LanguageModel("gpt-4o-mini")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Create echo tool using the new type-safe API
type EchoInput struct {
Message string `json:"message" description:"The message to echo back"`
}
echoTool := ai.NewAgentTool(
"echo",
"Echo back the provided message",
func(ctx context.Context, input EchoInput, _ ai.ToolCall) (ai.ToolResponse, error) {
return ai.NewTextResponse("Echo: " + input.Message), nil
},
)
// Create streaming agent
agent := ai.NewAgent(
model,
ai.WithSystemPrompt("You are a helpful assistant."),
ai.WithTools(echoTool),
)
ctx := context.Background()
fmt.Println("Simple Streaming Agent Example")
fmt.Println("==============================")
fmt.Println()
// Basic streaming with key callbacks
streamCall := ai.AgentStreamCall{
Prompt: "Please echo back 'Hello, streaming world!'",
// Show real-time text as it streams
OnTextDelta: func(id, text string) error {
fmt.Print(text)
return nil
},
// Show when tools are called
OnToolCall: func(toolCall ai.ToolCallContent) error {
fmt.Printf("\n[Tool: %s called]\n", toolCall.ToolName)
return nil
},
// Show tool results
OnToolResult: func(result ai.ToolResultContent) error {
fmt.Printf("[Tool result received]\n")
return nil
},
// Show when each step completes
OnStepFinish: func(step ai.StepResult) error {
fmt.Printf("\n[Step completed: %s]\n", step.FinishReason)
return nil
},
}
fmt.Println("Assistant response:")
result, err := agent.Stream(ctx, streamCall)
if err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("\n\nFinal result: %s\n", result.Response.Content.Text())
fmt.Printf("Steps: %d, Total tokens: %d\n", len(result.Steps), result.TotalUsage.TotalTokens)
}