Repository navigation
Initialization
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_GenerativeAIMost types live in the GenerativeAI and GenerativeAI.Types namespaces. For credentials (API keys, ADC, OAuth, service accounts), see Authentication.
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 readGEMINI_API_KEY. If your environment usesGEMINI_API_KEY, pass its value explicitly:new GoogleAi(Environment.GetEnvironmentVariable("GEMINI_API_KEY")).
Tip:
GenerativeAI.Typescontains a type namedEnvironment. In files that haveusing GenerativeAI.Types;, writeSystem.Environment.GetEnvironmentVariable(...)to avoid a CS0104 ambiguity error.
Note on
GOOGLE_GENAI_API_VERSION: The Gemini API defaults tov1betaand Vertex AI tov1beta1. The variable applies toGoogleAi,GoogleAIPlatformAdapterandVertextPlatformAdapterwhen you don't passapiVersion. TheVertexAI(...)convenience constructor always passes itsapiVersionargument (defaultApiVersions.v1Beta1), so on Vertex the variable only takes effect when you create theVertextPlatformAdapteryourself.
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());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.
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.
-
global: The newest Gemini models (for example the Gemini 3.x family) are served only from thegloballocation. Withregion: "global"the SDK callshttps://aiplatform.googleapis.com/...instead ofhttps://{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 asgemini-embedding-001andtext-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, embeddingsVertex 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.
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.
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);| 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 |
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.
Getting Started
- Initialization
- Authentication
- Configuration & Error Handling
- Supported Models
- Migration Guide (v4)
- Release Notes (v4)
Core Features
- Generate Content
- Chat Session
- Streaming
- Multimodal Features
- JSON Mode
- Function Calling
- Embeddings
- Context Caching
Gemini APIs
- Interactions API
- Multimodal Live API
- File Search
- Batch API
- Model Tuning
- Webhooks
- Agent APIs
- Image Generation
- Video Generation
- Speech Generation
- Files Client
- Model Client
Vertex AI
Integrations
Guides
Legacy