func CacheCreateFromChat()

in go/cache.go [138:233]


func CacheCreateFromChat() (*genai.GenerateContentResponse, error) {
	// [START cache_create_from_chat]
	ctx := context.Background()
	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		APIKey:  os.Getenv("GEMINI_API_KEY"),
		Backend: genai.BackendGeminiAPI,
	})
	if err != nil {
		log.Fatal(err)
	}

	modelName := "gemini-1.5-flash-001"
	systemInstruction := "You are an expert analyzing transcripts."

	// Create initial chat with a system instruction.
	chat, err := client.Chats.Create(ctx, modelName, &genai.GenerateContentConfig{
		SystemInstruction: genai.NewContentFromText(systemInstruction, genai.RoleUser),
	}, nil)
	if err != nil {
		log.Fatal(err)
	}

	document, err := client.Files.UploadFromPath(
		ctx, 
		filepath.Join(getMedia(), "a11.txt"), 
		&genai.UploadFileConfig{
			MIMEType : "text/plain",
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	// Send first message with the transcript.
	parts := make([]genai.Part, 2)
	parts[0] = genai.Part{Text: "Hi, could you summarize this transcript?"}
	parts[1] = genai.Part{
		FileData: &genai.FileData{
			FileURI :      document.URI,
			MIMEType: document.MIMEType,
		},
	}

	// Send chat message.
	resp, err := chat.SendMessage(ctx, parts...)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("\n\nmodel: ", resp.Text())

	resp, err = chat.SendMessage(
		ctx, 
		genai.Part{
			Text: "Okay, could you tell me more about the trans-lunar injection",
		},
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("\n\nmodel: ", resp.Text())

	// To cache the conversation so far, pass the chat history as the list of contents.
	cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
		Contents:          chat.History(false),
		SystemInstruction: genai.NewContentFromText(systemInstruction, genai.RoleUser),
	})
	if err != nil {
		log.Fatal(err)
	}

	// Continue the conversation using the cached history.
	chat, err = client.Chats.Create(ctx, modelName, &genai.GenerateContentConfig{
		CachedContent: cache.Name,
	}, nil)
	if err != nil {
		log.Fatal(err)
	}

	resp, err = chat.SendMessage(
		ctx, 
		genai.Part{
			Text: "I didn't understand that last part, could you explain it in simpler language?",
		},
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("\n\nmodel: ", resp.Text())
	// [END cache_create_from_chat]

	// Clean up the cache.
	if _, err := client.Caches.Delete(ctx, cache.Name, nil); err != nil {
		log.Fatal(err)
	}
	return resp, nil
}