Créer un cache de contexte
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Créez un cache de contexte pour réduire les coûts liés aux requêtes répétées contenant le même nombre de jetons.
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","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)."]]