Generate text by using a context cache

Generate text by using an existing context cache.

Code sample

C#

Before trying this sample, follow the C# setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI C# API reference documentation.

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


usingGoogle.Cloud.AIPlatform.V1Beta1 ;
usingSystem;
usingSystem.Threading.Tasks;
publicclassUseContextCache
{
publicasyncTask<string>Use(stringprojectId,CachedContentName name)
{
varpredictionServiceClient=newPredictionServiceClientBuilder
{
Endpoint=$"us-central1-aiplatform.googleapis.com"
}.Build();
vargenerateContentRequest=newGenerateContentRequest
{
CachedContentAsCachedContentName=name,
Model=$"projects/{projectId}/locations/us-central1/publishers/google/models/gemini-2.0-flash-001",
Contents=
{
newContent
{
Role="USER",
Parts=
{
newPart {Text="What are the papers about?"},
}
}
}
};
GenerateContentResponse response=awaitpredictionServiceClient.GenerateContentAsync(generateContentRequest);
stringresponseText=response.Candidates [0].Content .Parts[0].Text;
Console.WriteLine($"Response: {responseText}");
returnresponseText;
}
}

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.