Google Gemini: Um projeto de inteligência artificial do Google.

O Google Gemini pode apoiar um agente do Agent Framework por meio da API do Desenvolvedor Gemini ou da IA do Vértice. O cliente específico do provedor manipula as opções de autenticação e solicitação Gemini, enquanto o Agent Framework possui a definição e a orquestração do agente.

Importante

O Google Gemini e a IA do Vértice são sistemas de terceiros. Examine os termos de serviço, o tratamento de dados, os limites regionais, o acesso ao modelo e os custos de uso antes de enviar dados do aplicativo.

Instalar um Gemini IChatClient

O exemplo de .NET demonstra o cliente oficial do Google GenAI e a implementação da comunidadeMscc.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}");

Escolha uma IChatClient implementação e configure sua API de Desenvolvedor gemini ou autenticação de IA do Vértice.

Instalar o pacote

pip install agent-framework-gemini --pre

Configuration

Use a API de Desenvolvedor do Gemini:

GEMINI_API_KEY="<api-key>"
GEMINI_MODEL="gemini-2.5-flash"
# GOOGLE_API_KEY and GOOGLE_MODEL are also supported.

Ou configure a IA do Vértice:

GOOGLE_GENAI_USE_VERTEXAI="true"
GOOGLE_CLOUD_PROJECT="<project-id>"
GOOGLE_CLOUD_LOCATION="us-central1"
GOOGLE_MODEL="gemini-2.5-flash"

GeminiChatClient dá suporte a streaming, ferramentas de funções, saída estruturada, pensamento estendido e ferramentas hospedadas pelo provedor.

async def non_streaming_example() -> None:
    """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")

O pacote inclui fábricas para aterramento do Google Search, aterramento do Google Mapas, execução de código, pesquisa de arquivos e MCP.

Aterramento da Pesquisa do Google

import asyncio

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

O SDK go fornece geminiprovider inferência Gemini. Crie um padrão *agent.Agent por meio do construtor específico do provedor.

Consulte o pacote e os exemplos do provedor Gemini.

Tools

Tool C# Python Go Notes
Ferramentas de Funções Chamada de função de modelo padrão.
Aprovação da ferramenta Aplicado pelo loop de ferramentas da estrutura.
Interpretador de Código GeminiChatClient.get_code_interpreter_tool().
Pesquisa de Arquivo GeminiChatClient.get_file_search_tool().
Pesquisa na Web Google Search aterrando através get_web_search_tool()de .
Aterramento do Google Mapas GeminiChatClient.get_maps_grounding_tool().
Ferramentas MCP hospedadas GeminiChatClient.get_mcp_tool().
Ferramentas MCP locais É executado no processo do aplicativo.

Próximas Etapas