- Notifications
You must be signed in to change notification settings - Fork24
Google Gen AI Dotnet SDK provides an interface for developers to integrate Google's generative models into their .NET applications.
License
googleapis/dotnet-genai
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Google Gen AI .NET SDK provides an interface for developers to integrateGoogle's generative models into their .NET applications. It supports theGemini Developer API andVertex AIAPIs.
This library is built for net8.0 and netstandard2.0.
The full API reference is hosted in thededicated GitHub Page
In your dotnet project directory, type the the following command
dotnet add package Google.GenAIusingGoogle.GenAI;usingGoogle.GenAI.Types;
Please run one of the following code blocks to create a client fordifferent services (Gemini Developer API orVertex AI).
usingGoogle.GenAI;// Only run this block for Gemini Developer APIvarclient=newClient(apiKey:apiKey);
usingGoogle.GenAI;// only run this block for Vertex AI APIclient=newClient(project:project,location:location,vertexAI:true)
(Optional) Using environment variables:
You can create a client by configuring the necessary environment variables.Configuration setup instructions depends on whether you're using the GeminiDeveloper API or the Gemini API in Vertex AI.
Gemini Developer API: Set theGOOGLE_API_KEY. It will automatically bepicked up by the client.
export GEMINI_API_KEY='your-api-key'
Gemini API on Vertex AI: SetGOOGLE_GENAI_USE_VERTEXAI,GOOGLE_CLOUD_PROJECT andGOOGLE_CLOUD_LOCATION, as shown below:
export GOOGLE_GENAI_USE_VERTEXAI=trueexport GOOGLE_CLOUD_PROJECT='your-project-id'export GOOGLE_CLOUD_LOCATION='us-central1'
usingGoogle.GenAI;client=newClient();
Parameter types are specified in theGoogle.GenAI.Types namespace.
Enums are represented using structs for forward compatibility reasons. Enumvalues follow C# naming conventions (PascalCase).
The SDK enum value contains an underlying string value that is sent to the API,which is usually UPPER_SNAKE_CASE. Please refer to the API documentation forthe expected enum string values if you do not use the static SDK enum values.
Unknown enum values are preserved as string values, accessible throughPersonGeneration.Value. String equality with static SDK enum values can bechecked, but must match the underlying string value exactly(ex.PersonGeneration.AllowAll == "ALLOW_ALL" is true).
Theclient.Models module exposes model inferencing. SeeCreate a clientsection above to initialize a client.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGenerateContentSimpleText{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varresponse=awaitclient.Models.GenerateContentAsync(model:"gemini-2.0-flash",contents:"why is the sky blue?");Console.WriteLine(response.Candidates[0].Content.Parts[0].Text);}}
The output of the model can be influenced by several optional settingsavailable in GenerateContentAsync's config parameter. For example, to make a model moredeterministic, lowering theTemperature parameter reduces randomness, withvalues near 0 minimizing variability. Capabilities and parameter defaults foreach model is shown in theVertex AI docsandGemini API docs respectively.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGenerateContentWithConfig{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();vargenerateContentConfig=newGenerateContentConfig{SystemInstruction=newContent{Parts=newList<Part>{newPart{Text="I say high you say low."}}},Temperature=0.1,MaxOutputTokens=3};varresponse=awaitclient.Models.GenerateContentAsync(model:"gemini-2.0-flash",contents:"high",config:generateContentConfig);Console.WriteLine(response.Candidates[0].Content.Parts[0].Text);}}
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;classGenerateContentWithSafetySettings{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varsafetySettings=newList<SafetySetting>{newSafetySetting{Category=HarmCategory.HARM_CATEGORY_HATE_SPEECH,Threshold=HarmBlockThreshold.BLOCK_LOW_AND_ABOVE}};vargenerateContentConfig=newGenerateContentConfig{SafetySettings=newList<SafetySetting>(safetySettings)};varresponse=awaitclient.Models.GenerateContentAsync(model:"gemini-2.0-flash",contents:"say something hateful",config:generateContentConfig);Console.WriteLine(response.Candidates[0].SafetyRatings);}}
However you define your schema, don't duplicate it in your input prompt,including by giving examples of expected JSON output. If you do, the generatedoutput might be lower in quality.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGenerateContentWithJsonSchema{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();// define the response schema you desireSchemacountryInfo=newSchema{Properties=newDictionary<string,Schema>{{"title",newSchema{Type=Type.STRING,Title="Title"}},{"population",newSchema{Type=Type.INTEGER,Title="Population"}},{"capital",newSchema{Type=Type.STRING,Title="Capital"}},{"continent",newSchema{Type=Type.STRING,Title="Continent"}},{"language",newSchema{Type=Type.STRING,Title="Language"}}},PropertyOrdering=newList<string>{"title","population","capital","continent","language"},Required=newList<string>{"title","population","capital","continent","language"},Title="CountryInfo",Type=Type.OBJECT};varresponse=awaitclient.Models.GenerateContentAsync(model:"gemini-2.0-flash",contents:"Give me information about Australia",config:newGenerateContentConfig{ResponseMimeType="application/json",ResponseSchema=countryInfo});stringtext=response.Candidates[0].Content.Parts[0].Text;varparsedText=JsonSerializer.Deserialize<Dictionary<string,object>>(text);Console.WriteLine(parsedText);}}
The usage of GenerateContentStreamAsync is similar to GenerateContentAsync, this section shows one simple example to showcase the nuance in the usage.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;classGenerateContentStreamSimpleText{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();awaitforeach(varchunkinclient.Models.GenerateContentStreamAsync(model:"gemini-2.0-flash",contents:"why is the sky blue?")){Console.WriteLine(chunk.Candidates[0].Content.Parts[0].Text);}}}
Microsoft.Extensions.AI provides abstractions and exchange types for working with AI services. The Google.GenAI library includes an implementation of the IChatClient interface to enableeasy integration with applications that use these abstractions.
usingGoogle.GenAI;usingMicrosoft.Extensions.AI;usingSystem.ComponentModel// assuming credentials are set up in environment variables as instructed above.IChatClient chatClient=newClient().AsIChatClient("gemini-2.0-flash").AsBuilder().UseFunctionInvocation().UseOpenTelemetry().Build();ChatOptionsoptions=new(){Tools=[AIFunctionFactory.Create(([Description("The name of the person whose age is to be retrieved")]stringpersonName)=>personNameswitch{"Alice"=>30,"Bob"=>25, _=>35},"get_person_age","Gets the age of the specified person");};awaitforeach(varupdateinchatClient.GetStreamingResponseAsync("How much older is Alice than Bob?",options)){ Console.Write(update);}
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGenerateImagesSimple{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();vargenerateImagesConfig=newGenerateImagesConfig{NumberOfImages=1,AspectRatio="1:1",SafetyFilterLevel=SafetyFilterLevel.BLOCK_LOW_AND_ABOVE,PersonGeneration=PersonGeneration.DONT_ALLOW,IncludeSafetyAttributes=true,IncludeRaiReason=true,OutputMimeType="image/jpeg",};varresponse=awaitclient.Models.GenerateImagesAsync(model:"imagen-4.0-generate-001",prompt:"Red skateboard",config:generateImagesConfig);// Do something with the generated imagevarimage=response.GeneratedImages.First().Image;}}
Upscaling an image is only supported on the Vertex AI client.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassUpscaleImageSimple{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varupscaleImageConfig=newUpscaleImageConfig{OutputMimeType="image/jpeg",EnhanceInputImage=true};varimage;// Image to upscale herevarresponse=awaitclient.Models.UpscaleImageAsync(model:modelName,image:image,upscaleFactor:"x2",config:upscaleImageConfig);// Do something with the generated imagevarimage=response.GeneratedImages.First().Image;}}
Edit image uses a separate model from generate and upscale.
Edit image is only supported in the Vertex AI client.
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassEditImageSimple{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();List<IReferenceImage>referenceImages=newList<IReferenceImage>();// Raw reference imagevarrawReferenceImage=newRawReferenceImage{ReferenceImage=Image.FromFile("path/to/file","image/png"),ReferenceId=1,};referenceImages.Add(rawReferenceImage);// Mask reference image, generated by modelvarmaskReferenceImage=newMaskReferenceImage{ReferenceId=2,Config=newMaskReferenceConfig{MaskMode=MaskReferenceMode.MASK_MODE_BACKGROUND,MaskDilation=0.06,}};referenceImages.Add(maskReferenceImage);vareditImageConfig=newEditImageConfig{EditMode=EditMode.EDIT_MODE_INPAINT_INSERTION,NumberOfImages=1,OutputMimeType="image/jpeg",};vareditImageResponse=awaitclient.Models.EditImageAsync(model:"imagen-3.0-capability-001",prompt:"Change the colors of [1] using the mask [2]",referenceImages:referenceImages,config:editImageConfig);// Do something with the generated imagevarimage=editImageResponse.GeneratedImages.First().Image;}}
Segment image is only supported in the Vertex AI client.
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassSegmentImageSimple{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varsegmentImageConfig=newSegmentImageConfig{Mode=SegmentMode.BACKGROUND,MaxPredictions=1,};varsegmentImageResponse=awaitclient.Models.SegmentImageAsync(model:modelName,source:newSegmentImageSource{Image=Image.FromFile("path/to/image.png","image/png"),},config:segmentImageConfig);// Do something with the generated maskvarmask=segmentImageResponse.GeneratedMasks.First().Mask;}}
Generated videos can be either be returned by the API as bytes or a GCS URI forVertex. For Gemini Developer API, only a Files URI can be returned.
For Gemini, generated videos can be downloaded to a local file as follows:
awaitclient.Files.DownloadToFileAsync(generatedVideo:operation.Response.GeneratedVideos.First(),outputPath:"video.mp4");
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGenerateVideosFromText{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varsource=newGenerateVideosSource{Prompt="Man with a dog",};varconfig=newGenerateVideosConfig{NumberOfVideos=1,};varoperation=awaitclient.Models.GenerateVideosAsync(model:"veo-3.1-generate-preview",source:source,config:config);while(operation.Done!=true){try{awaitTask.Delay(10000);operation=awaitclient.Operations.GetAsync(operation,null);}catch(TaskCanceledException){System.Console.WriteLine("Task was cancelled while waiting.");break;}}// Do something with the generated videovarvideo=operation.Response.GeneratedVideos.First().Video;}}
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGenerateVideosFromText{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varsource=newGenerateVideosSource{// Prompt is optional if Image is providedPrompt="Man with a dog",Image=Image.FromFile("images/man.png"),};varconfig=newGenerateVideosConfig{NumberOfVideos=1,};varoperation=awaitclient.Models.GenerateVideosAsync(model:"veo-3.1-generate-preview",source:source,config:config);while(operation.Done!=true){try{awaitTask.Delay(10000);operation=awaitclient.Operations.GetAsync(operation,null);}catch(TaskCanceledException){System.Console.WriteLine("Task was cancelled while waiting.");break;}}// Do something with the generated videovarvideo=operation.Response.GeneratedVideos.First().Video;}}
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGenerateVideosFrameInterpolation{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varsource=newGenerateVideosSource{Prompt="At the park",Image=Image.FromFile("images/man.jpg"),};varconfig=newGenerateVideosConfig{NumberOfVideos=1,LastFrame=Image.FromFile("images/dog.jpg"),};varoperation=awaitclient.Models.GenerateVideosAsync(model:"veo-3.1-generate-preview",source:source,config:config);while(operation.Done!=true){try{awaitTask.Delay(10000);operation=awaitclient.Operations.GetAsync(operation,null);}catch(TaskCanceledException){System.Console.WriteLine("Task was cancelled while waiting.");break;}}// Do something with the generated videovarvideo=operation.Response.GeneratedVideos.First().Video;}}
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGenerateVideosReferenceImages{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varsource=newGenerateVideosSource{Prompt="Chirping birds in a colorful forest",};List<VideoGenerationReferenceImage>referenceImages=newList<VideoGenerationReferenceImage>();referenceImages.Add(newVideoGenerationReferenceImage{Image=Image.FromFile("images/man.jpg"),ReferenceType=VideoGenerationReferenceType.ASSET,});varconfig=newGenerateVideosConfig{NumberOfVideos=1,ReferenceImages=referenceImages,};varoperation=awaitclient.Models.GenerateVideosAsync(model:"veo-3.1-generate-preview",source:source,config:config);while(operation.Done!=true){try{awaitTask.Delay(10000);operation=awaitclient.Operations.GetAsync(operation,null);}catch(TaskCanceledException){System.Console.WriteLine("Task was cancelled while waiting.");break;}}// Do something with the generated videovarvideo=operation.Response.GeneratedVideos.First().Video;}}
Gemini Developer API only accepts previously generated videos.Vertex accepts a Video from GCS URI.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGenerateVideosFromVideo{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varsource1=newGenerateVideosSource{Prompt="Man with a dog",};varoperation1=awaitclient.Models.GenerateVideosAsync(model:modelName,source:source1,config:newGenerateVideosConfig{NumberOfVideos=1,});while(operation1.Done!=true){try{awaitTask.Delay(10000);operation1=awaitclient.Operations.GetAsync(operation1,null);}catch(TaskCanceledException){System.Console.WriteLine("Task was cancelled while waiting.");break;}}varsource2=newGenerateVideosSource{Prompt="Driving through a tunnel.",Video=operation1.Response.GeneratedVideos.First().Video,};varoperation2=awaitclient.Models.GenerateVideosAsync(model:"veo-3.1-generate-preview",source:source2,config:newGenerateVideosConfig{NumberOfVideos=1,});while(operation2.Done!=true){try{awaitTask.Delay(10000);operation2=awaitclient.Operations.GetAsync(operation2,null);}catch(TaskCanceledException){System.Console.WriteLine("Task was cancelled while waiting.");break;}}// Do something with the generated videovarvideo=operation2.Response.GeneratedVideos.First().Video;}}
Editing a video is only available on Vertex
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassEditVideoOutpaint{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varsource=newGenerateVideosSource{Prompt="A mountain landscape",Video=newVideo{Uri="gs://bucket/inputs/editing_demo.mp4",MimeType="video/mp4",},};varconfig=newGenerateVideosConfig{OutputGcsUri=outputGcsUri,AspectRatio="16:9",Mask=newVideoGenerationMask{Image=newImage{GcsUri="gs://bucket/inputs/video_outpaint_mask.png",MimeType="image/png",},MaskMode=VideoGenerationMaskMode.OUTPAINT,},};varoperation=awaitvertexClient.Models.GenerateVideosAsync(model:"veo-2.0-generate-exp",source:source,config:config);while(operation.Done!=true){try{awaitTask.Delay(10000);operation=awaitvertexClient.Operations.GetAsync(operation,null);}catch(TaskCanceledException){System.Console.WriteLine("Task was cancelled while waiting.");break;}}varvideo=operation.Response.GeneratedVideos.First().Video;}}
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCountTokensExample{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varresponse=awaitclient.Models.CountTokensAsync(model:"gemini-2.0-flash",contents:"What is the capital of France?");Console.Writeline(response.TotalTokens);}}
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassComputeTokensExample{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varresponse=awaitclient.Models.ComputeTokensAsync(model:"gemini-2.0-flash",contents:"What is the capital of France?");Console.Writeline(response.TokensInfo);}}
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassEmbedContentExample{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varresponse=awaitclient.Models.EmbedContentAsync(model:"text-embedding-004",contents:"What is the capital of France?");Console.WriteLine(response.Embeddings[0].Values);// Multimodal embedding with Vertex AIvarvertexClient=newClient(vertexAI:true);varcontents=newList<Content>{newContent{Parts=newList<Part>{newPart{Text="Hello."},newPart{FileData=newFileData{MimeType="image/png",FileUri="gs://cloud-samples-data/generative-ai/image/a-man-and-a-dog.png"}}}}};varconfig=newEmbedContentConfig{OutputDimensionality=10,Title="test_title",TaskType="RETRIEVAL_DOCUMENT",};varmmResponse=awaitvertexClient.Models.EmbedContentAsync(model:"gemini-embedding-2-exp-11-2025",contents:contents,config:config);Console.WriteLine(mmResponse.Embeddings);}}
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGetModelExample{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();// get a base modelvarbaseModelResponse=awaitclient.Models.GetAsync(model:"gemini-2.5-flash");// get a tuned modelvartunedModelResponse=awaitclient.Models.GetAsync(model:"models/your-tuned-model");}}
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassUpdateModelExample{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varresponse=awaitclient.Models.UpdateAsync(model:"models/your-tuned-model",config:newUpdateModelConfig{Description="updated model description"});Console.WriteLine(response.Description);}}
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassDeleteModelExample{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();awaitclient.Models.DeleteAsync(model:"models/your-tuned-model");}}
TheListAsync method returns aPager object that allows you to iterate through pages of models. IfQueryBase is set totrue (the default) inListModelsConfig, it lists base models; otherwise, it lists tuned models.
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassListModelsExample{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();// List base models with default settingsConsole.WriteLine("Base Models:");varpager=awaitclient.Models.ListAsync();awaitforeach(varmodelinpager){Console.WriteLine(model.Name);}// List tuned models with a page size of 10Console.WriteLine("Tuned Models:");varconfig=newListModelsConfig{QueryBase=false,PageSize=10};vartunedModelsPager=awaitclient.Models.ListAsync(config);awaitforeach(varmodelintunedModelsPager){Console.WriteLine(model.Name);}}}
Theclient.Batches module can be used to manage batch jobs.SeeCreate a client section above to initialize a client.
Batch jobs can be created from GCS URIs or BigQuery URIs when using Vertex AI, or from Files or Inlined Requests when using the Gemini API.
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCreateBatchWithGcs{publicstaticasyncTaskmain(){// assuming credentials are set up for Vertex AI in environment variables as instructed above.varclient=newClient();varsrc=newBatchJobSource{GcsUri=newList<string>{"gs://unified-genai-tests/batches/input/generate_content_requests.jsonl"},Format="jsonl"};varconfig=newCreateBatchJobConfig{DisplayName="test_batch_gcs",Dest=newBatchJobDestination{GcsUri="gs://unified-genai-tests/batches/output",Format="jsonl"}};varresponse=awaitclient.Batches.CreateAsync("gemini-2.5-flash",src,config);Console.WriteLine($"Created Vertex AI batch job:{response.Name}");}}
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCreateBatchWithBigQuery{publicstaticasyncTaskmain(){// assuming credentials are set up for Vertex AI in environment variables as instructed above.varclient=newClient();varsrc=newBatchJobSource{BigqueryUri="bq://storage-samples.generative_ai.batch_requests_for_multimodal_input",Format="bigquery"};varconfig=newCreateBatchJobConfig{DisplayName="test_batch_bigquery",Dest=newBatchJobDestination{BigqueryUri="bq://REDACTED.unified_genai_tests_batches.generate_content_output",Format="bigquery"}};varresponse=awaitclient.Batches.CreateAsync("gemini-2.5-flash",src,config);Console.WriteLine($"Created Vertex AI batch job:{response.Name}");}}
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCreateBatchWithInlinedRequests{publicstaticasyncTaskmain(){// assuming credentials are set up for Gemini API in environment variables as instructed above.varclient=newClient();varsafetySettings=newList<SafetySetting>{newSafetySetting{Category=HarmCategory.HARM_CATEGORY_HATE_SPEECH,Threshold=HarmBlockThreshold.BLOCK_ONLY_HIGH}};varinlineRequest=newInlinedRequest{Contents=newList<Content>{newContent{Parts=newList<Part>{newPart{Text="Hello!"}},Role="user"}},Metadata=newDictionary<string,string>{{"key","request-1"}},Config=newGenerateContentConfig{SafetySettings=safetySettings}};varsrc=newBatchJobSource{InlinedRequests=newList<InlinedRequest>{inlineRequest}};varconfig=newCreateBatchJobConfig{DisplayName="test_batch_inlined"};varresponse=awaitclient.Batches.CreateAsync("gemini-2.5-flash",src,config);Console.WriteLine($"Created Gemini API batch job:{response.Name}");}}
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCreateBatchWithFile{publicstaticasyncTaskmain(){// assuming credentials are set up for Gemini API in environment variables as instructed above.varclient=newClient();varsrc=newBatchJobSource{FileName="files/your-file-id"};varconfig=newCreateBatchJobConfig{DisplayName="test_batch_file"};varresponse=awaitclient.Batches.CreateAsync("gemini-2.5-flash",src,config);Console.WriteLine($"Created Gemini API batch job:{response.Name}");}}
Embedding batch jobs are only supported in Gemini API, from Files or Inlined Requests.
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCreateEmbeddingBatchWithInlinedRequests{publicstaticasyncTaskmain(){// assuming credentials are set up for Gemini API in environment variables as instructed above.varclient=newClient();varsrc=newEmbeddingsBatchJobSource{InlinedRequests=newEmbedContentBatch{Config=newEmbedContentConfig{OutputDimensionality=64},Contents=newList<Content>{newContent{Parts=newList<Part>{newPart{Text="1"}}},newContent{Parts=newList<Part>{newPart{Text="2"}}},newContent{Parts=newList<Part>{newPart{Text="3"}}},}}};varconfig=newCreateEmbeddingsBatchJobConfig{DisplayName="test_batch_embedding_inlined"};varresponse=awaitclient.Batches.CreateEmbeddingsAsync("gemini-embedding-001",src,config);Console.WriteLine($"Created Gemini API embedding batch job:{response.Name}");}}
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCreateEmbeddingBatchWithFile{publicstaticasyncTaskmain(){// assuming credentials are set up for Gemini API in environment variables as instructed above.varclient=newClient();varsrc=newEmbeddingsBatchJobSource{FileName="files/your-file-id",};varconfig=newCreateEmbeddingsBatchJobConfig{DisplayName="test_batch_embedding_file"};varresponse=awaitclient.Batches.CreateEmbeddingsAsync("gemini-embedding-001",src,config);Console.WriteLine($"Created Gemini API embedding batch job:{response.Name}");}}
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGetBatchJob{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();// Use a batch job name from a previously created batch job.varbatchJob=awaitclient.Batches.GetAsync(name:"batches/your-batch-job-name");Console.WriteLine($"Batch job name:{batchJob.Name}, State:{batchJob.State}");}}
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCancelBatchJob{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();// Use a batch job name from a previously created batch job.awaitclient.Batches.CancelAsync(name:"batches/your-batch-job-name");Console.WriteLine("Batch job cancelled.");}}
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassListBatchJobs{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varpager=awaitclient.Batches.ListAsync(newListBatchJobsConfig{PageSize=10});awaitforeach(varjobinpager){Console.WriteLine($"Batch job name:{job.Name}, State:{job.State}");}}}
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassDeleteBatchJob{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();// Use a batch job name from a previously created batch job.awaitclient.Batches.DeleteAsync(name:"batches/your-batch-job-name");Console.WriteLine("Batch job deleted.");}}
Theclient.Caches module can be used to manage cached content.SeeCreate a client section above to initialize a client.
Cacheable content can be created from Google Cloud Storage URIs when using Vertex AI, or from File URIs when using the Gemini API.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCreateCache{publicstaticasyncTaskmain(){// Example for Vertex AI with GCS URIs:varvertexClient=newClient(project:project,location:location,vertexAI:true);varvertexConfig=newCreateCachedContentConfig{Contents=newList<Content>{newContent{Role="user",Parts=newList<Part>{newPart{FileData=newFileData{FileUri="gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",MimeType="application/pdf"}},newPart{FileData=newFileData{FileUri="gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",MimeType="application/pdf"}}}}},DisplayName="my-vertex-cache",Ttl="600s"};varvertexResponse=awaitvertexClient.Caches.CreateAsync(model:"gemini-2.5-flash",config:vertexConfig);Console.WriteLine($"Created Vertex AI cache:{vertexResponse.Name}");// Example for Gemini API with File URIs:vargeminiClient=newClient(apiKey:apiKey);vargeminiConfig=newCreateCachedContentConfig{Contents=newList<Content>{newContent{Role="user",Parts=newList<Part>{newPart{FileData=newFileData{FileUri="https://generativelanguage.googleapis.com/v1beta/files/file-id",MimeType="application/pdf"}}}}},DisplayName="my-gemini-cache",Ttl="600s"};vargeminiResponse=awaitgeminiClient.Caches.CreateAsync(model:"gemini-2.5-flash",config:geminiConfig);Console.WriteLine($"Created Gemini API cache:{geminiResponse.Name}");}}
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassGetCache{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();// Use a cache name from a previously created cache.varcachedContent=awaitclient.Caches.GetAsync(name:"cachedContents/your-cache-name",config:null);Console.WriteLine($"Cache name:{cachedContent.Name}, DisplayName:{cachedContent.DisplayName}");}}
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassUpdateCache{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varupdateConfig=newUpdateCachedContentConfig{Ttl="1200s"};// Use a cache name from a previously created cache.varcachedContent=awaitclient.Caches.UpdateAsync(name:"cachedContents/your-cache-name",config:updateConfig);Console.WriteLine($"Cache updated. New expiration time:{cachedContent.ExpireTime}");}}
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassDeleteCache{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();// Use a cache name from a previously created cache.awaitclient.Caches.DeleteAsync(name:"cachedContents/your-cache-name",config:null);Console.WriteLine("Cache deleted.");}}
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassListCaches{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varpager=awaitclient.Caches.ListAsync(newListCachedContentConfig{PageSize=10});awaitforeach(varcacheinpager){Console.WriteLine($"Cache name:{cache.Name}, DisplayName:{cache.DisplayName}");}}}
Theclient.Tunings module exposes model tuning. SeeCreate a clientsection above to initialize a client.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCreateTuningJobSimple{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient(vertexAI:true);vartrainingDataset=newTuningDataset{GcsUri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl"};vartuningJob=awaitclient.Tunings.TuneAsync(baseModel:"gemini-2.5-flash",trainingDataset:trainingDataset,);Console.WriteLine(tuningJob.State);}}
The tuning job can be configured by several optional settingsavailable in Tune's config parameter. For example, we can configurethe number of epochs to train for, or specify a validation dataset.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCreateTuningJobWithConfig{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient(vertexAI:true);vartrainingDataset=newTuningDataset{GcsUri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl"};varvalidationDataset=newTuningValidationDataset{GcsUri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_validation_data.jsonl"};varconfig=newCreateTuningJobConfig{TunedModelDisplayName="Tuned Model",EpochCount=3,LearningRateMultiplier=0.5,ValidationDataset=validationDataset,};vartuningJob=awaitclient.Tunings.TuneAsync(baseModel:"gemini-2.5-flash",trainingDataset:trainingDataset,config:config,);Console.WriteLine(tuningJob.State);}}
You can perform preference tuning by settingMethod toTuningMethod.PREFERENCE_TUNING inCreateTuningJobConfig.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassPreferenceTuningJob{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient(vertexAI:true);vartrainingDataset=newTuningDataset{GcsUri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl"};varconfig=newCreateTuningJobConfig{TunedModelDisplayName="Tuned Model",Method=TuningMethod.PREFERENCE_TUNING,EpochCount=1,};vartuningJob=awaitclient.Tunings.TuneAsync(baseModel:"gemini-2.5-flash",trainingDataset:trainingDataset,config:config,);Console.WriteLine(tuningJob.State);}}
You can perform continuous tuning on a previously tuned model by passingthe tuned model's resource name as thebaseModel parameter.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassContinuousTuningJob{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient(vertexAI:true);vartrainingDataset=newTuningDataset{GcsUri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl"};// Continuously tune a previously tuned model by passing in its resource name.vartunedModelResourceName="models/your-tuned-model";vartuningJob=awaitclient.Tunings.TuneAsync(baseModel:tunedModelResourceName,trainingDataset:trainingDataset,);Console.WriteLine(tuningJob.State);}}
You can perform distillation by settingMethod toTuningMethod.DISTILLATION inCreateTuningJobConfig.
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassDistillationJob{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient(vertexAI:true);// Prompt datasetvartrainingDataset=newTuningDataset{GcsUri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl"};varconfig=newCreateTuningJobConfig{Method=TuningMethod.DISTILLATION,BaseTeacherModel="teacher-model-id",EpochCount=1,};vartuningJob=awaitclient.Tunings.TuneAsync(baseModel:"student-model-id",trainingDataset:trainingDataset,config:config,);Console.WriteLine(tuningJob.State);}}
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassCancelTuningJobExample{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();// The tuning job resource name to cancel, retrieved from a created tuning job.vartuningJobResourceName="tuningJobs/your-tuning-job";awaitclient.Tunings.CancelAsync(tuningJobResourceName);}}
usingSystem.Threading.Tasks;usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassListTuningJobs{publicstaticasyncTaskmain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient();varpager=awaitclient.Tunings.ListAsync(newListTuningJobsConfig{PageSize=2});awaitforeach(vartuningJobinpager){Console.WriteLine($"Tuning job name:{tuningJob.Name}, State:{tuningJob.State}");}}}
The Files feature are only supported for the Gemini API.
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassFiles{publicstaticasyncTaskMain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient(vertexAI:false);// uploading from local file pathvaruploadResponse1=awaitclient.Files.UploadAsync(filtePath:"path/to/your/file.png");Console.WriteLine($"Gemini API Files Upload Response:{uploadResponse1}");// uploading from bytes// using this fileBytes variable for demo purpose onlybyte[]fileBytes=awaitSystem.IO.File.ReadAllBytesAsync("path/to/your/file.png");varuploadResponse2=awaitgeminiClient.Files.UploadAsync(bytes:fileBytes,fileName:"file.png");Console.WriteLine($"Gemini API Files Upload Response:{uploadResponse2}");}}
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassFiles{publicstaticasyncTaskMain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient(vertexAI:false);// usually, pattern is similar to this example "files/s0pa54alni6w"stringfileName="files/randomID";vargetResponse=awaitclient.Files.GetAsync(name:fileName);Console.WriteLine($"Gemini API Files Get Response:{getResponse}");}}
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassFiles{publicstaticasyncTaskMain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient(vertexAI:false);// usually, pattern is similar to this example "files/s0pa54alni6w"stringfileName="files/randomID";vardeleteResponse=awaitclient.Files.DeleteAsync(name:fileName);Console.WriteLine($"Gemini API Files Delete Response:{deleteResponse}");}}
usingGoogle.GenAI;usingGoogle.GenAI.Types;publicclassFiles{publicstaticasyncTaskMain(){// assuming credentials are set up in environment variables as instructed above.varclient=newClient(vertexAI:false);varpager=awaitclient.Files.ListAsync();awaitforeach(varpageinpager){Console.WriteLine($"Gemini API Files List Response page:{page}");}}}
About
Google Gen AI Dotnet SDK provides an interface for developers to integrate Google's generative models into their .NET applications.
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.