1// Package main provides a simple streaming agent example of using the fantasy AI SDK.
2package main
3
4import (
5 "context"
6 "fmt"
7 "os"
8
9 "charm.land/fantasy"
10 "charm.land/fantasy/providers/openai"
11)
12
13func main() {
14 // Check for API key
15 apiKey := os.Getenv("OPENAI_API_KEY")
16 if apiKey == "" {
17 fmt.Println("Please set OPENAI_API_KEY environment variable")
18 os.Exit(1)
19 }
20
21 // Create provider and model
22 provider, err := openai.New(openai.WithAPIKey(apiKey))
23 if err != nil {
24 fmt.Fprintf(os.Stderr, "Error creating OpenAI provider: %v\n", err)
25 os.Exit(1)
26 }
27
28 ctx := context.Background()
29
30 model, err := provider.LanguageModel(ctx, "gpt-4o-mini")
31 if err != nil {
32 fmt.Println(err)
33 os.Exit(1)
34 }
35
36 // Create echo tool using the new type-safe API
37 type EchoInput struct {
38 Message string `json:"message" description:"The message to echo back"`
39 }
40
41 echoTool := fantasy.NewAgentTool(
42 "echo",
43 "Echo back the provided message",
44 func(_ context.Context, input EchoInput, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
45 return fantasy.NewTextResponse("Echo: " + input.Message), nil
46 },
47 )
48
49 // Create streaming agent
50 agent := fantasy.NewAgent(
51 model,
52 fantasy.WithSystemPrompt("You are a helpful assistant."),
53 fantasy.WithTools(echoTool),
54 )
55
56 fmt.Println("Simple Streaming Agent Example")
57 fmt.Println("==============================")
58 fmt.Println()
59
60 // Basic streaming with key callbacks
61 streamCall := fantasy.AgentStreamCall{
62 Prompt: "Please echo back 'Hello, streaming world!'",
63
64 // Show real-time text as it streams
65 OnTextDelta: func(_ string, text string) error {
66 fmt.Print(text)
67 return nil
68 },
69
70 // Show when tools are called
71 OnToolCall: func(toolCall fantasy.ToolCallContent) error {
72 fmt.Printf("\n[Tool: %s called]\n", toolCall.ToolName)
73 return nil
74 },
75
76 // Show tool results
77 OnToolResult: func(_ fantasy.ToolResultContent) error {
78 fmt.Printf("[Tool result received]\n")
79 return nil
80 },
81
82 // Show when each step completes
83 OnStepFinish: func(step fantasy.StepResult) error {
84 fmt.Printf("\n[Step completed: %s]\n", step.FinishReason)
85 return nil
86 },
87 }
88
89 fmt.Println("Assistant response:")
90 result, err := agent.Stream(ctx, streamCall)
91 if err != nil {
92 fmt.Printf("Error: %v\n", err)
93 os.Exit(1)
94 }
95
96 fmt.Printf("\n\nFinal result: %s\n", result.Response.Content.Text())
97 fmt.Printf("Steps: %d, Total tokens: %d\n", len(result.Steps), result.TotalUsage.TotalTokens)
98}