Skip to content

Initialization

Gunpal Jain edited this page Nov 15, 2026 · 4 revisions

This page shows how to set up the SDK for the Gemini Developer API (GoogleAi) and for Vertex AI (VertexAI). You can configure it from environment variables, constructors or platform adapters.

dotnet add package Google_GenerativeAI

Most types live in the GenerativeAI and GenerativeAI.Types namespaces. For credentials (API keys, ADC, OAuth, service accounts), see Authentication.

Environment Variables

If you set these variables, you can leave the matching constructor arguments out:

Variable Used for
GOOGLE_API_KEY API key for the Gemini API (and for Vertex AI express mode). Read when you don't pass an apiKey.
GOOGLE_AI_MODEL Default model name, used when a model is created with a null model name. Defaults to GoogleAIModels.DefaultGeminiModel (models/gemini-3.8-flash).
GOOGLE_PROJECT_ID Google Cloud project for Vertex AI. If it isn't set, the SDK reads project_id from the credentials file.
GOOGLE_REGION Vertex AI location. Defaults to us-central1 when not set.
GOOGLE_ACCESS_TOKEN A ready-made OAuth access token for Vertex AI.
GOOGLE_APPLICATION_CREDENTIALS Path to a credentials file (ADC / service account) for Vertex AI.
GOOGLE_WEB_CREDENTIALS Path to OAuth web credentials. This file is checked before GOOGLE_APPLICATION_CREDENTIALS.
GOOGLE_GENAI_API_VERSION API version to use when none is passed to a platform adapter. This is the same variable the official SDKs read. beta maps to v1beta on the Gemini API and v1beta1 on Vertex AI. Any other value, such as v1, is used as-is.

Note: The SDK reads GOOGLE_API_KEY. It does not read GEMINI_API_KEY. If your environment uses GEMINI_API_KEY, pass its value explicitly: new GoogleAi(Environment.GetEnvironmentVariable("GEMINI_API_KEY")).

Tip: GenerativeAI.Types contains a type named Environment. In files that have using GenerativeAI.Types;, write System.Environment.GetEnvironmentVariable(...) to avoid a CS0104 ambiguity error.

Note on GOOGLE_GENAI_API_VERSION: The Gemini API defaults to v1beta and Vertex AI to v1beta1. The variable applies to GoogleAi, GoogleAIPlatformAdapter and VertextPlatformAdapter when you don't pass apiVersion. The VertexAI(...) convenience constructor always passes its apiVersion argument (default ApiVersions.v1Beta1), so on Vertex the variable only takes effect when you create the VertextPlatformAdapter yourself.

using GenerativeAI;

// GOOGLE_API_KEY is set in the environment
var ai = new GoogleAi();
var model = ai.CreateGenerativeModel(GoogleAIModels.Gemini38Flash);

var response = await model.GenerateContentAsync("Hello!");
Console.WriteLine(response.Text());

Gemini Developer API (GoogleAi)

using GenerativeAI;

// API key from the constructor (or from GOOGLE_API_KEY when omitted)
var ai = new GoogleAi("YOUR_API_KEY");

// Generic model
GenerativeModel model = ai.CreateGenerativeModel(GoogleAIModels.Gemini38Flash);

// GeminiModel adds file helpers (upload by file path, the Files client)
GeminiModel gemini = ai.CreateGeminiModel(GoogleAIModels.Gemini38Flash);

CreateGenerativeModel and CreateGeminiModel also take an optional GenerationConfig, safety settings and a system instruction:

var model = ai.CreateGenerativeModel(
    GoogleAIModels.Gemini38Flash,
    config: new GenerationConfig { Temperature = 0.7, MaxOutputTokens = 1024 },
    systemInstruction: "You are a concise assistant.");

The GoogleAi constructor signature is GoogleAi(string? apiKey = null, string? accessToken = null, HttpClient? client = null, ILogger? logger = null). Pass accessToken (or an authenticator through the adapter) for endpoints that need OAuth, such as tuning and semantic retrieval.

Vertex AI (VertexAI)

using GenerativeAI;

var vertex = new VertexAI(projectId: "your-project-id", region: "global");
var model = vertex.CreateGenerativeModel(VertexAIModels.Gemini.Gemini38Flash);

Full constructor:

public VertexAI(string? projectId = null, string? region = null, string? accessToken = null,
    bool expressMode = false, string? apiKey = null, string apiVersion = ApiVersions.v1Beta1,
    HttpClient? httpClient = null, IGoogleAuthenticator? authenticator = null, ILogger? logger = null)

If you leave out projectId and region, the SDK uses GOOGLE_PROJECT_ID and GOOGLE_REGION. If no project ID is found there, it reads project_id from the credentials file.

Choosing a region: global vs. regional

  • global: The newest Gemini models (for example the Gemini 3.x family) are served only from the global location. With region: "global" the SDK calls https://aiplatform.googleapis.com/... instead of https://{region}-aiplatform.googleapis.com/....
  • Regional (for example us-central1): Use a regional location for the Vertex RAG Engine and for embedding models that are not served globally, such as gemini-embedding-001 and text-embedding-005 (see Embeddings).

You can create two VertexAI instances, one for each location:

var global   = new VertexAI("your-project-id", "global");      // chat / generation
var regional = new VertexAI("your-project-id", "us-central1"); // RAG, embeddings

Express mode (API key)

Vertex AI express mode uses an API key instead of a Google Cloud project:

var vertex = new VertexAI(expressMode: true, apiKey: "YOUR_VERTEX_API_KEY");
var model = vertex.CreateGenerativeModel(VertexAIModels.Gemini.Gemini38Flash);

Express mode throws ArgumentException when no API key is passed and GOOGLE_API_KEY is not set.

Platform Adapters

GoogleAi and VertexAI are wrappers around an IPlatformAdapter (namespace GenerativeAI.Core). Create the adapter yourself when you need to control the API version, authenticator or token validation, or when you want to share one adapter between models and clients (FileClient, CachingClient, ModelClient, EmbeddingModel, ...).

using GenerativeAI;
using GenerativeAI.Core;

// Gemini API
IPlatformAdapter googleAdapter = new GoogleAIPlatformAdapter("YOUR_API_KEY", apiVersion: ApiVersions.v1Beta);
var ai = new GoogleAi(googleAdapter);
var model = ai.CreateGenerativeModel(GoogleAIModels.Gemini38Flash);

// Vertex AI (note the class name: VertextPlatformAdapter)
IPlatformAdapter vertexAdapter = new VertextPlatformAdapter(projectId: "your-project-id", region: "global");
var vertex = new VertexAI(vertexAdapter);
var vertexModel = vertex.CreateGenerativeModel(VertexAIModels.Gemini.Gemini38Flash);

// Adapters can also be passed to models and clients directly
var direct = new GenerativeModel(googleAdapter, GoogleAIModels.Gemini38Flash);

Available API versions are on ApiVersions: v1, v1Beta, v1Beta1 and v1Alpha.

Custom HttpClient and Logging

Every entry point takes an optional HttpClient and ILogger:

var http = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
var ai = new GoogleAi("YOUR_API_KEY", client: http, logger: myLogger);

Choosing an Initialization Method

Method Best for
Environment variables Quick setup, development, containers and CI
GoogleAi / VertexAI constructors Most applications
Platform adapters Custom API versions or auth, or sharing one adapter between many clients

Error Handling

When an API call fails, the SDK throws GenerativeAI.Exceptions.ApiException with ErrorCode (HTTP or API code), ErrorStatus (for example INVALID_ARGUMENT or RESOURCE_EXHAUSTED) and ErrorMessage. See Generate Content.

Related Pages

API Reference

Clone this wiki locally