Edit

Google Gemini

Google Gemini can back an Agent Framework agent through the Gemini Developer API or Gemini Enterprise Agent Platform (formerly Vertex AI). The provider-specific client handles authentication and Gemini request options while Agent Framework owns the agent definition and orchestration.

Important

Google Gemini and Vertex AI are third-party systems. Review service terms, data handling, regional boundaries, model access, and usage costs before sending application data.

Install a Gemini IChatClient

The .NET sample demonstrates the official Google GenAI client and the community Mscc.GenerativeAI.Microsoft implementation.

dotnet add package Google.GenAI
dotnet add package Mscc.GenerativeAI.Microsoft
dotnet add package Microsoft.Agents.AI --prerelease

Configuration

GOOGLE_GENAI_API_KEY="<google-ai-studio-api-key>"
GOOGLE_GENAI_MODEL="gemini-2.5-flash"
const string JokerInstructions = "You are good at telling jokes.";
const string JokerName = "JokerAgent";

string apiKey = Environment.GetEnvironmentVariable("GOOGLE_GENAI_API_KEY") ?? throw new InvalidOperationException("Please set the GOOGLE_GENAI_API_KEY environment variable.");
string model = Environment.GetEnvironmentVariable("GOOGLE_GENAI_MODEL") ?? "gemini-2.5-flash";

// Using a Google GenAI IChatClient implementation

ChatClientAgent agentGenAI = new(
    new Client(vertexAI: false, apiKey: apiKey).AsIChatClient(model),
    name: JokerName,
    instructions: JokerInstructions);

AgentResponse response = await agentGenAI.RunAsync("Tell me a joke about a pirate.");
Console.WriteLine($"Google GenAI client based agent response:\n{response}");

// Using a community driven Mscc.GenerativeAI.Microsoft package

ChatClientAgent agentCommunity = new(
    new GeminiChatClient(apiKey: apiKey, model: model),
    name: JokerName,
    instructions: JokerInstructions);

response = await agentCommunity.RunAsync("Tell me a joke about a pirate.");
Console.WriteLine($"Community client based agent response:\n{response}");

Choose one IChatClient implementation and configure its Gemini Developer API or Vertex AI authentication.

Install the package

pip install agent-framework-gemini --pre

Configuration

Use either the Gemini Developer API:

GOOGLE_API_KEY="<api-key>"
GOOGLE_MODEL="gemini-2.5-flash"

Or configure Gemini Enterprise Agent Platform:

GOOGLE_GENAI_USE_ENTERPRISE="true"
GOOGLE_CLOUD_PROJECT="<project-id>"
GOOGLE_CLOUD_LOCATION="global"
GOOGLE_MODEL="gemini-2.5-flash"

The older GOOGLE_GENAI_USE_VERTEXAI=true setting remains supported. The connector no longer reads GEMINI_API_KEY, GEMINI_MODEL, or GEMINI_EMBEDDING_MODEL; use the corresponding GOOGLE_* variables or pass values explicitly.

GeminiChatClient supports streaming, function tools, structured output, extended thinking, and provider-hosted tools.

    """Runs the agent and waits for the complete response before printing it."""
    print("=== Non-streaming ===")

    # 1. Create the agent with the Gemini chat client and local weather tool.
    agent = Agent(
        client=GeminiChatClient(),
        name="WeatherAgent",
        instructions="You are a helpful weather agent.",
        tools=[get_weather],
    )

    # 2. Ask the agent for a single weather lookup and print the final response.
    query = "What's the weather like in Karlsruhe, Germany?"
    print(f"User: {query}")
    result = await agent.run(query)
    print(f"Result: {result}\n")


async def streaming_example() -> None:
    """Runs the agent and prints each chunk as it is received."""
    print("=== Streaming ===")

    # 1. Create the same agent configuration for a streaming tool-call example.
    agent = Agent(
        client=GeminiChatClient(),
        name="WeatherAgent",
        instructions="You are a helpful weather agent.",
        tools=[get_weather],
    )

    # 2. Ask a multi-location question and stream the model output as it arrives.
    query = "What's the weather like in Portland and in Paris?"
    print(f"User: {query}")
    print("Agent: ", end="", flush=True)
    async for chunk in agent.run(query, stream=True):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print("\n")

Handle request failures

For streaming and non-streaming runs, Gemini SDK request failures are exposed through Agent Framework exceptions. HTTP 401 and 403 failures raise ChatClientInvalidAuthException, other HTTP 4xx failures raise ChatClientInvalidRequestException, and all other provider failures raise ChatClientException.

Catch ChatClientException when the same error handling should apply across chat providers.

Include thought summaries

The extended thinking sample shows how to configure ThinkingConfig. To receive Gemini thought summaries, set include_thoughts=True in the thinking configuration:

options: GeminiChatOptions = {
    "thinking_config": ThinkingConfig(include_thoughts=True, thinking_budget=2048),
}

When Gemini returns a thought summary, GeminiChatClient adds it to the response as Content with type == "text_reasoning". Read the summary from content.text.

For a run without streaming, filter the contents of each item in result.messages. For a streaming run, filter each chunk.contents. Text accessors such as result.text and chunk.text include only text content, so inspect the content collections when your app needs reasoning summaries.

Generate embeddings

GeminiEmbeddingClient uses gemini-embedding-2 by default. Override it with GOOGLE_EMBEDDING_MODEL or the model constructor parameter. Text inputs require a task type on each call; use RETRIEVAL_DOCUMENT when indexing and RETRIEVAL_QUERY when searching the same vector space.


import asyncio

from agent_framework.gemini import GeminiEmbeddingClient
from dotenv import load_dotenv

load_dotenv()


async def main() -> None:
    """Embed a document and a search query for the same vector index."""
    # 1. Choose task instructions for each call, not for the client.
    client = GeminiEmbeddingClient()
    try:
        # 2. Use matching dimensions for stored documents and search queries.
        document = await client.get_embeddings(
            ["Agent Framework helps build and orchestrate AI agents."],
            options={"task_type": "RETRIEVAL_DOCUMENT", "title": "Agent Framework", "dimensions": 768},
        )
        query = await client.get_embeddings(
            ["How can I orchestrate AI agents?"],
            options={"task_type": "RETRIEVAL_QUERY", "dimensions": 768},
        )
        print(f"Document embedding: {document[0].dimensions} dimensions")
        print(f"Query embedding: {query[0].dimensions} dimensions")

Use the same model and dimensions for document and query embeddings. The client also accepts Google SDK media Part and Content values for image, audio, video, PDF, or combined text-and-media embeddings. Media inputs don't use a text task prefix.

When a vector collection generates embeddings, pass the document task through upsert(..., embeddings_options=...) and the query task through search(..., embeddings_options=...) or create_vector_search_tool(..., embeddings_options=...). For multiple vector fields, use embeddings_options_by_field. Agent Framework supplies the selected field's dimensions and rejects conflicting values.

The package includes factories for Google Search grounding, Google Maps grounding, code execution, file search, and MCP.

Google Search grounding


from agent_framework import Agent
from agent_framework.gemini import GeminiChatClient
from dotenv import load_dotenv

load_dotenv()


async def main() -> None:
    """Run the Google Search grounding example."""
    print("=== Google Search grounding ===")

    # 1. Create the agent with Gemini and the built-in Google Search grounding tool.
    agent = Agent(
        client=GeminiChatClient(),
        name="SearchAgent",
        instructions="You are a helpful assistant. Use Google Search to provide accurate, up-to-date answers.",
        tools=[GeminiChatClient.get_web_search_tool()],
    )

    # 2. Ask a current-events style question and stream the grounded answer.
    query = "What is the latest stable release of the .NET SDK?"
    print(f"User: {query}")
    print("Agent: ", end="", flush=True)
    async for chunk in agent.run(query, stream=True):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print("\n")


if __name__ == "__main__":
    asyncio.run(main())

The Go SDK provides geminiprovider for Gemini inference. Create a standard *agent.Agent through the provider-specific constructor.

See the Gemini provider package and examples.

Tools

Tool C# Python Go Notes
Function Tools ✅ ✅ ✅ Standard model function calling.
Tool Approval ✅ ✅ ✅ Applied by the framework tool loop.
Code Interpreter ❌ ✅ ❌ GeminiChatClient.get_code_interpreter_tool().
File Search ❌ ✅ ❌ GeminiChatClient.get_file_search_tool().
Web Search ❌ ✅ ❌ Google Search grounding through get_web_search_tool().
Google Maps grounding ❌ ✅ ❌ GeminiChatClient.get_maps_grounding_tool().
Hosted MCP Tools ❌ ✅ ❌ GeminiChatClient.get_mcp_tool().
Local MCP Tools ✅ ✅ ✅ Runs in the application process.

Next steps