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