Google Gemini

Google Gemini puede respaldar a un agente de Agent Framework a través de la API para desarrolladores deGéminis o la Plataforma de agente de Gemini Enterprise (anteriormente Vertex AI). El cliente específico del proveedor controla las opciones de autenticación y solicitud de Gemini, mientras que Agent Framework posee la definición y orquestación del agente.

Important

Google Gemini y Vertex AI son sistemas de terceros. Revise los términos del servicio, el control de datos, los límites regionales, el acceso al modelo y los costos de uso antes de enviar datos de la aplicación.

Instala Gemini IChatClient

En el ejemplo .NET se muestra el cliente oficial de Google GenAI y la implementación de la comunidadMscc.GenerativeAI.Microsoft.

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}");

Seleccione una implementación de IChatClient y configure la autenticación de la API de Gemini para desarrolladores o de Vertex AI.

Instalar el paquete

pip install agent-framework-gemini --pre

Configuration

Utilice una de las siguientes APIs para desarrolladores de Gemini:

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

O bien configure la plataforma de agentes Gemini Enterprise:

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

La configuración anterior GOOGLE_GENAI_USE_VERTEXAI=true sigue siendo compatible. El conector ya no lee GEMINI_MODEL, GEMINI_EMBEDDING_MODEL ni GOOGLE_*; use las variables correspondientes GEMINI_API_KEY o pase los valores explícitamente.

GeminiChatClient admite el streaming, las herramientas de funciones, la salida estructurada, el pensamiento extendido y las herramientas hospedadas por el proveedor.

    """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")

Gestionar errores de solicitud

En las ejecuciones con y sin streaming, los fallos en las solicitudes del SDK de Gemini se muestran mediante excepciones de Agent Framework. Los errores HTTP 401 y 403 generan ChatClientInvalidAuthException, otros errores HTTP 4xx generan ChatClientInvalidRequestExceptiony todos los demás errores de proveedor generan ChatClientException.

Detectar ChatClientException cuándo se debe aplicar el mismo control de errores en los proveedores de chat.

Incluir resúmenes de pensamiento

En el ejemplo de pensamiento extendido se muestra cómo configurar ThinkingConfig. Para recibir resúmenes de pensamiento de Gemini, establezca include_thoughts=True en la configuración de pensamiento:

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

Cuando Gemini devuelve un resumen de pensamiento, GeminiChatClient lo agrega a la respuesta como Content con type == "text_reasoning". Lea el resumen de content.text.

Para una ejecución sin streaming, filtra el contents de cada elemento en result.messages. Para una ejecución en streaming, filtre cada chunk.contents. Accesores de texto como result.text y chunk.text solo incluyen contenido de text, así que inspecciona las colecciones de contenido cuando tu app necesite resúmenes del razonamiento.

Generación de inserciones

GeminiEmbeddingClient usa gemini-embedding-2 de forma predeterminada. Sustitúyalo por medio de GOOGLE_EMBEDDING_MODEL o del parámetro del constructor model. Las entradas de texto requieren un tipo de tarea en cada llamada; use RETRIEVAL_DOCUMENT al indexar y RETRIEVAL_QUERY al buscar en el mismo espacio vectorial.


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 el mismo modelo y dimensiones para las incrustaciones de documentos y consultas. El cliente también acepta valores de medios del SDK de Google Part y Content para incrustaciones de imagen, audio, vídeo, PDF o una combinación de texto y medios. Las entradas multimedia no usan un prefijo de tarea de texto.

Cuando una colección de vectores genera representaciones vectoriales, pase la tarea del documento a través de upsert(..., embeddings_options=...) y la tarea de la consulta a través de search(..., embeddings_options=...) o create_vector_search_tool(..., embeddings_options=...). Para varios campos vectoriales, use embeddings_options_by_field. Agent Framework proporciona las dimensiones del campo seleccionado y rechaza los valores en conflicto.

El paquete incluye fábricas para la contextualización de Google Search, la contextualización de Google Maps, la ejecución de código, la búsqueda de archivos y MCP.

Contextualización de Google Search


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())

El SDK de Go proporciona geminiprovider para la inferencia con Gemini. Cree un estándar *agent.Agent a través del constructor específico del proveedor.

Consulte el paquete del proveedor Gemini y los ejemplos.

Tools

Herramienta C# Python Go Notas
Herramientas de funciones ✅ ✅ ✅ Llamada estándar a funciones del modelo.
Aprobación de herramientas ✅ ✅ ✅ Aplicado por el bucle de herramientas del framework.
Intérprete de código ❌ ✅ ❌ GeminiChatClient.get_code_interpreter_tool().
Búsqueda de archivos ❌ ✅ ❌ GeminiChatClient.get_file_search_tool().
Búsqueda web ❌ ✅ ❌ Anclaje en Google Search a través de get_web_search_tool().
Anclaje en Google Maps ❌ ✅ ❌ GeminiChatClient.get_maps_grounding_tool().
Herramientas de MCP hospedadas ❌ ✅ ❌ GeminiChatClient.get_mcp_tool().
Herramientas de MCP locales ✅ ✅ ✅ Se ejecuta en el proceso de la aplicación.

Pasos siguientes