Configure Google Gemini models with Vertex AI and API access
Overview
Google Gemini provides state-of-the-art multimodal AI models through two access methods: Google AI Studio (direct API) and Vertex AI (enterprise platform). This guide covers both approaches with the MCP Server.
Gemini 3.0 Pro (Nov 2025) is the latest model with a 1M token context window and advanced reasoning. For production workloads, Gemini 2.5 Flash and Gemini 2.5 Pro are stable, production-grade models.
New: Anthropic Claude models are also available via Vertex AI! See the Vertex AI Setup Guide for unified access to both Claude and Gemini models.
Available Models
The following models are production-ready and suitable for enterprise use:
Model
Context Window
Use Case
Pricing (per 1M tokens)
Status
gemini-3-pro-preview
1M tokens
Latest, advanced reasoning
$2 input / $12 output
🆕 Preview (Nov 2025)
gemini-2.5-flash
1M tokens
Fast responses, chat
$0.30 input / $2.50 output
✅ Production
gemini-2.5-pro
2M tokens
Complex reasoning
$1.25 input / $10.00 output
✅ Production
Vertex AI models (use vertex_ai/ prefix):
vertex_ai/gemini-3-pro-preview - Latest Gemini 3.0 Pro via Vertex AI
vertex_ai/gemini-2.5-flash - Gemini 2.5 Flash via Vertex AI
vertex_ai/gemini-2.5-pro - Gemini 2.5 Pro via Vertex AI
# Add to InfisicalGOOGLE_API_KEY=AIzaSy...your-key# In .env, reference InfisicalINFISICAL_PROJECT_ID=your-project-id
3
Test
from mcp_server_langgraph.llm.factory import LLMFactoryllm = LLMFactory( provider="google", model_name="gemini-2.5-flash")response = await llm.ainvoke("What is the capital of France?")print(response.content)# Output: "The capital of France is Paris."
Best for: Production, enterprise, private data
Complete Guide: See the Vertex AI Setup Guide for comprehensive instructions including Workload Identity (GKE), multi-provider access (Claude + Gemini), and enterprise deployment.
1
Setup GCP Project
# Install gcloud CLIcurl https://sdk.cloud.google.com | bash# Login and setupgcloud auth logingcloud config set project YOUR_PROJECT_ID# Enable Vertex AI APIgcloud services enable aiplatform.googleapis.com
2
Create Service Account
# Create service accountgcloud iam service-accounts create vertex-ai-agent \ --display-name="Vertex AI Agent"# Grant Vertex AI User rolegcloud projects add-iam-policy-binding YOUR_PROJECT_ID \ --member="serviceAccount:vertex-ai-agent@YOUR_PROJECT_ID.iam.gserviceaccount.com" \ --role="roles/aiplatform.user"# Create and download keygcloud iam service-accounts keys create vertex-key.json \ --iam-account=vertex-ai-agent@YOUR_PROJECT_ID.iam.gserviceaccount.com# Store in Infisicalcat vertex-key.json | jq -c > vertex-key-compact.json# Upload vertex-key-compact.json to Infisical as GOOGLE_APPLICATION_CREDENTIALS
from langchain_core.tools import tool@tooldef get_weather(location: str) -> str: """Get current weather for a location""" # Implementation return f"Weather in {location}: 72°F, Sunny"@tooldef search_web(query: str) -> str: """Search the web for information""" # Implementation return f"Search results for: {query}"## Bind tools to LLMllm_with_tools = llm.bind_tools([get_weather, search_web])## Use with agentfrom langgraph.prebuilt import create_react_agentagent = create_react_agent( llm_with_tools, tools=[get_weather, search_web])## Run agentresponse = await agent.ainvoke({ "messages": [("user", "What's the weather in Paris?")]})print(response["messages"][-1].content)
Structured Output
from pydantic import BaseModel, Fieldclass Person(BaseModel): name: str = Field(description="Person's full name") age: int = Field(description="Person's age in years") occupation: str = Field(description="Person's job title")## Force structured outputstructured_llm = llm.with_structured_output(Person)response = await structured_llm.ainvoke( "Extract info: John Smith is a 35-year-old software engineer")print(response.model_dump())## Output: {'name': 'John Smith', 'age': 35, 'occupation': 'software engineer'}
## Enable Workload Identity on clustergcloud container clusters update CLUSTER_NAME \ --workload-pool=PROJECT_ID.svc.id.goog## Create Kubernetes service accountkubectl create serviceaccount mcp-server-langgraph## Bind to GCP service accountgcloud iam service-accounts add-iam-policy-binding \ vertex-ai-agent@PROJECT_ID.iam.gserviceaccount.com \ --role roles/iam.workloadIdentityUser \ --member "serviceAccount:PROJECT_ID.svc.id.goog[mcp-server-langgraph/mcp-server-langgraph]"## Annotate K8s service accountkubectl annotate serviceaccount mcp-server-langgraph \ iam.gke.io/gcp-service-account=vertex-ai-agent@PROJECT_ID.iam.gserviceaccount.com## Use in deploymentapiVersion: apps/v1kind: Deploymentspec: template: spec: serviceAccountName: mcp-server-langgraph containers: - name: agent env: - name: LLM_PROVIDER value: "vertex_ai"
Performance Optimization
Caching
## Enable prompt caching (Gemini 2.5 Pro only)from langchain_google_genai import ChatGoogleGenerativeAIllm = ChatGoogleGenerativeAI( model="gemini-2.5-pro", google_api_key=settings.google_api_key, cache_content=True # Enable caching)## First call - full costresponse1 = await llm.ainvoke("Analyze this long document...")## Second call with similar prompt - cached, cheaperresponse2 = await llm.ainvoke("What are the key points in the document?")
Batching
## Process multiple requests in parallelimport asyncioqueries = [ "What is machine learning?", "Explain neural networks", "Define deep learning"]## Concurrent processingresponses = await asyncio.gather(*[ llm.ainvoke(query) for query in queries])for query, response in zip(queries, responses): print(f"Q: {query}\nA: {response.content}\n")
Streaming
## Stream responses for better UXasync def stream_response(query: str): async for chunk in llm.astream(query): yield chunk.content # Send to client incrementally## Use in FastAPIfrom fastapi.responses import StreamingResponse@app.post("/message/stream")async def stream_message(request: Request): query = request.query return StreamingResponse( stream_response(query), media_type="text/event-stream" )
Cost Optimization
Model Selection
## Use cheaper model for simple tasksdef select_model(task_complexity: str) -> str: if task_complexity == "simple": return "gemini-2.5-flash" # Free elif task_complexity == "medium": return "gemini-2.5-flash-002" # $0.15/1M else: return "gemini-2.5-pro" # $1.25/1M## Dynamic selectionllm = LLMFactory( provider="google", model_name=select_model(analyze_complexity(query)))
from langchain_google_genai import HarmBlockThreshold, HarmCategory## Configure safety settingsllm = ChatGoogleGenerativeAI( model="gemini-2.5-flash", safety_settings={ HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE, HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE, HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE, HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE, })## Handle safety blockstry: response = await llm.ainvoke(query)except Exception as e: if "SAFETY" in str(e): logger.warning(f"Content blocked by safety filters: {query}") return "I cannot provide a response to that query due to safety concerns." raise
Monitoring
LangSmith Integration
## Track Gemini usage in LangSmithimport osos.environ["LANGCHAIN_TRACING_V2"] = "true"os.environ["LANGCHAIN_PROJECT"] = "langgraph-gemini"## Calls automatically trackedresponse = await llm.ainvoke(query)## View in https://smith.langchain.com
Error: google.api_core.exceptions.Unauthenticated: 401 API key not validSolutions:
# Verify API keyecho $GOOGLE_API_KEY | head -c 10# Should start with: AIza# Test keycurl "https://generativelanguage.googleapis.com/v1beta/models?key=$GOOGLE_API_KEY"# Regenerate key# 1. Go to https://aistudio.google.com/app/apikey# 2. Delete old key# 3. Create new key# 4. Update in Infisical/config