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