A partir de 29 de abril de 2025, os modelos Gemini 1.5 Pro e Gemini 1.5 Flash não estarão disponíveis em projetos que não os usaram antes, incluindo novos projetos. Para mais detalhes, consulte
Versões e ciclo de vida do modelo.
Criar um cache de contexto
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Crie um cache de contexto para reduzir os custos com solicitações repetidas que contêm a mesma entrada de contagem de tokens.
Exemplo de código
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],[],[],[],null,["# Create a context cache to reduce costs with repeated requests that contain the same token count input.\n\nCode sample\n-----------\n\n### C#\n\n\nBefore trying this sample, follow the C# setup instructions in the\n[Vertex AI quickstart using\nclient libraries](/vertex-ai/docs/start/client-libraries).\n\n\nFor more information, see the\n[Vertex AI C# API\nreference documentation](/dotnet/docs/reference/Google.Cloud.AIPlatform.V1/latest).\n\n\nTo authenticate to Vertex AI, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n using https://cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1Beta1/latest/Google.Cloud.AIPlatform.V1Beta1.html;\n using https://cloud.google.com/dotnet/docs/reference/Google.Protobuf/latest/Google.Protobuf.WellKnownTypes.html;\n using System;\n using System.Threading.Tasks;\n\n public class CreateContextCache\n {\n public async Task\u003cCachedContentName\u003e Create(string projectId)\n {\n var client = await new https://cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1Beta1/latest/Google.Cloud.AIPlatform.V1Beta1.GenAiCacheServiceClientBuilder.html\n {\n Endpoint = \"us-central1-aiplatform.googleapis.com\"\n }.BuildAsync();\n\n var request = new https://cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1Beta1/latest/Google.Cloud.AIPlatform.V1Beta1.CreateCachedContentRequest.html\n {\n Parent = $\"projects/{projectId}/locations/us-central1\",\n CachedContent = new https://cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1Beta1/latest/Google.Cloud.AIPlatform.V1Beta1.CachedContent.html\n {\n Model = $\"projects/{projectId}/locations/us-central1/publishers/google/models/gemini-2.0-flash-001\",\n SystemInstruction = new https://cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1Beta1/latest/Google.Cloud.AIPlatform.V1Beta1.Content.html\n {\n Parts =\n {\n new https://cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1Beta1/latest/Google.Cloud.AIPlatform.V1Beta1.Part.html { Text = \"You are an expert researcher. You always stick to the facts in the sources provided and\"\n + \" never make up new facts. Now look at these research papers, and answer the following questions.\" }\n }\n },\n Contents =\n {\n new https://cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1Beta1/latest/Google.Cloud.AIPlatform.V1Beta1.Content.html\n {\n Role = \"USER\",\n Parts =\n {\n new https://cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1Beta1/latest/Google.Cloud.AIPlatform.V1Beta1.Part.html { FileData = new() { MimeType = \"application/pdf\", FileUri = \"gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf\" } },\n new https://cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1Beta1/latest/Google.Cloud.AIPlatform.V1Beta1.Part.html { FileData = new() { MimeType = \"application/pdf\", FileUri = \"gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf\" } }\n }\n }\n },\n Ttl = https://cloud.google.com/dotnet/docs/reference/Google.Protobuf/latest/Google.Protobuf.WellKnownTypes.Duration.html.https://cloud.google.com/dotnet/docs/reference/Google.Protobuf/latest/Google.Protobuf.WellKnownTypes.Duration.html#Google_Protobuf_WellKnownTypes_Duration_FromTimeSpan_System_TimeSpan_(TimeSpan.FromMinutes(60))\n }\n };\n\n var cachedContent = await client.CreateCachedContentAsync(request);\n Console.WriteLine($\"Created cache: {cachedContent.https://cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1Beta1/latest/Google.Cloud.AIPlatform.V1Beta1.CachedContentName.html}\");\n return cachedContent.https://cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1Beta1/latest/Google.Cloud.AIPlatform.V1Beta1.CachedContentName.html;\n }\n }\n\n### Go\n\n\nBefore trying this sample, follow the Go setup instructions in the\n[Vertex AI quickstart using\nclient libraries](/vertex-ai/docs/start/client-libraries).\n\n\nFor more information, see the\n[Vertex AI Go API\nreference documentation](/go/docs/reference/cloud.google.com/go/aiplatform/latest/apiv1).\n\n\nTo authenticate to Vertex AI, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"io\"\n \t\"time\"\n\n \t\"cloud.google.com/go/vertexai/genai\"\n )\n\n // createContextCache shows how to create a cached content, and returns its name.\n func createContextCache(w io.Writer, projectID, location, modelName string) (string, error) {\n \t// location := \"us-central1\"\n \t// modelName := \"gemini-2.0-flash-001\"\n \tctx := context.Background()\n\n \tsystemInstruction := `\n \tYou are an expert researcher. You always stick to the facts in the sources provided, and never make up new facts.\n \tNow look at these research papers, and answer the following questions.\n `\n\n \tclient, err := genai.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_Client_NewClient(ctx, projectID, location)\n \tif err != nil {\n \t\treturn \"\", fmt.Errorf(\"unable to create client: %w\", err)\n \t}\n \tdefer client.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_Client_Close()\n\n \t// These PDF are viewable at\n \t// https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf\n \t// https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf\n\n \tpart1 := genai.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_FileData{\n \t\tMIMEType: \"application/pdf\",\n \t\tFileURI: \"gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf\",\n \t}\n\n \tpart2 := genai.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_FileData{\n \t\tMIMEType: \"application/pdf\",\n \t\tFileURI: \"gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf\",\n \t}\n\n \tcontent := &genai.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_CachedContent{\n \t\tModel: modelName,\n \t\tSystemInstruction: &genai.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_Content{\n \t\t\tParts: []genai.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_Part{genai.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_Text(systemInstruction)},\n \t\t},\n \t\tExpiration: genai.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_ExpireTimeOrTTL{TTL: 60 * time.Minute},\n \t\tContents: []*genai.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_Content{\n \t\t\t{\n \t\t\t\tRole: \"user\",\n \t\t\t\tParts: []genai.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_Part{part1, part2},\n \t\t\t},\n \t\t},\n \t}\n\n \tresult, err := client.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_Client_CreateCachedContent(ctx, content)\n \tif err != nil {\n \t\treturn \"\", fmt.Errorf(\"CreateCachedContent: %w\", err)\n \t}\n \tfmt.Fprint(w, result.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_GenerativeModel_Name)\n \treturn result.https://cloud.google.com/vertex-ai/generative-ai/docs/reference/go/latest/genai.html#cloud_google_com_go_vertexai_genai_GenerativeModel_Name, nil\n }\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=generativeaionvertexai)."]]