Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
O Google Gemini pode servir de base para um agente no Agent Framework por meio da Gemini Developer API ou da Gemini Enterprise Agent Platform (anteriormente Vertex AI). 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.
Important
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 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 implementação IChatClient e configure a autenticação da API Gemini para desenvolvedores ou do Vertex AI.
Instalar o pacote
pip install agent-framework-gemini --pre
Configuration
Use a API do Gemini para desenvolvedores:
GOOGLE_API_KEY="<api-key>"
GOOGLE_MODEL="gemini-2.5-flash"
Ou configure o Gemini Enterprise Agent Platform:
GOOGLE_GENAI_USE_ENTERPRISE="true"
GOOGLE_CLOUD_PROJECT="<project-id>"
GOOGLE_CLOUD_LOCATION="global"
GOOGLE_MODEL="gemini-2.5-flash"
A configuração mais antiga GOOGLE_GENAI_USE_VERTEXAI=true permanece com suporte. O conector não lê mais GEMINI_API_KEY, GEMINI_MODEL ou GEMINI_EMBEDDING_MODEL; use as variáveis GOOGLE_* correspondentes ou passe os valores explicitamente.
GeminiChatClient dá suporte a streaming, ferramentas de funções, saída estruturada, pensamento estendido e ferramentas hospedadas pelo provedor.
"""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")
Tratar falhas na solicitação
Para execuções com e sem streaming, as falhas nas solicitações do SDK Gemini são expostas por meio de exceções do Agent Framework. Falhas HTTP 401 e 403 geram ChatClientInvalidAuthException, outras falhas HTTP 4xx geram ChatClientInvalidRequestException, e todas as outras falhas do provedor geram ChatClientException.
Use Catch ChatClientException quando o mesmo tratamento de erros deve ser aplicado em diferentes provedores de chat.
Incluir resumos de pensamento
O exemplo de pensamento estendido mostra como configurar ThinkingConfig. Para receber resumos de pensamento de Gêmeos, defina include_thoughts=True na configuração de pensamento:
options: GeminiChatOptions = {
"thinking_config": ThinkingConfig(include_thoughts=True, thinking_budget=2048),
}
Quando Gemini retorna um resumo de pensamento, GeminiChatClient adiciona-o à resposta como Content com type == "text_reasoning". Leia o resumo de content.text.
Para uma execução sem streaming, filtre o contents de cada item em result.messages. Para uma execução em streaming, filtre cada chunk.contents. Acessadores de texto, como result.text e chunk.text, incluem apenas conteúdo text, portanto inspecione as coleções de conteúdo quando seu aplicativo precisar de resumos de raciocínio.
Gerar inserções
GeminiEmbeddingClient usa gemini-embedding-2 por padrão. Substitua isso por GOOGLE_EMBEDDING_MODEL ou pelo parâmetro do construtor model. As entradas de texto exigem um tipo de tarefa em cada chamada; use RETRIEVAL_DOCUMENT ao indexar e RETRIEVAL_QUERY ao pesquisar o mesmo espaço de vetor.
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 o mesmo modelo e dimensões para inserções de documento e consulta. O cliente também aceita os valores de mídia Part e Content do SDK do Google para embeddings de imagem, áudio, vídeo, PDF ou embeddings combinados de texto e mídia. As entradas de mídia não usam um prefixo de tarefa de texto.
Quando uma coleção de vetores gera embeddings, passe a tarefa do documento por upsert(..., embeddings_options=...) e a tarefa de consulta por search(..., embeddings_options=...) ou create_vector_search_tool(..., embeddings_options=...). Para vários campos de vetor, use embeddings_options_by_field. O Agent Framework fornece as dimensões do campo selecionado e rejeita valores conflitantes.
O pacote inclui factories para fundamentação com a Pesquisa do Google, fundamentação com o Google Maps, execução de código, busca de arquivos e MCP.
Baseamento na Busca do Google
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 para inferência com o Gemini. Crie um *agent.Agent padrão por meio do construtor específico do provedor.
Consulte o pacote do provedor Gemini e os exemplos.
Tools
| Tool | C# | Python | Go | Notes |
|---|---|---|---|---|
| Ferramentas de Funções | ✅ | ✅ | ✅ | Chamada de função no modelo padrão. |
| Aprovação da ferramenta | ✅ | ✅ | ✅ | Aplicado pelo loop da ferramenta do framework. |
| Interpretador de Código | ❌ | ✅ | ❌ |
GeminiChatClient.get_code_interpreter_tool(). |
| Pesquisa de Arquivo | ❌ | ✅ | ❌ |
GeminiChatClient.get_file_search_tool(). |
| Pesquisa na Web | ❌ | ✅ | ❌ | Restrição da Pesquisa do Google por meio de get_web_search_tool(). |
| Restrição do Google Maps | ❌ | ✅ | ❌ |
GeminiChatClient.get_maps_grounding_tool(). |
| Ferramentas MCP hospedadas | ❌ | ✅ | ❌ |
GeminiChatClient.get_mcp_tool(). |
| Ferramentas MCP locais | ✅ | ✅ | ✅ | É executado no processo do aplicativo. |