func ThinkingWithSearchToolStreaming()

in go/thinking_generation.go [219:265]


func ThinkingWithSearchToolStreaming() (string, error) {
	// [START thinking_with_search_tool_streaming]
	ctx := context.Background()
	client, err := newGenAIClient(ctx)
	if err != nil {
		log.Printf("Failed to create client: %v", err)
		return "", err
	}

	googleSearchTool := &genai.Tool{
		GoogleSearch: &genai.GoogleSearch{},
	}

	prompt := "When is the next total solar eclipse visible from mainland Europe?"
	contents := []*genai.Content{
		genai.NewContentFromText(prompt, genai.RoleUser),
	}
	config := &genai.GenerateContentConfig{
		Tools: []*genai.Tool{googleSearchTool},
	}

	var fullResponseText strings.Builder
	// var finalResponse *genai.GenerateContentResponse // Store the last response chunk

	stream := client.Models.GenerateContentStream(ctx, modelID, contents, config)
	for resp, err := range stream {
		if err != nil {
			log.Printf("Stream error: %v", err)
			fmt.Println("\nCould not access grounding metadata from stream response likely due to error.")
			return fullResponseText.String(), err
		}
		// Process text chunks
		if len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil && len(resp.Candidates[0].Content.Parts) > 0 {
			textPart := resp.Candidates[0].Content.Parts[0].Text
			if textPart != "" {
				fmt.Print(textPart)
				fullResponseText.WriteString(textPart)
			}
		}
		// finalResponse = resp // Keep track of the latest response which might contain aggregated data
	}

	fmt.Println("\n" + strings.Repeat("_", 80)) // Separator

	// [END thinking_with_search_tool_streaming]
	return fullResponseText.String(), nil
}