Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
O Google Gemini pode apoiar um agente do Agent Framework através da Gemini Developer API ou da Gemini Enterprise Agent Platform (anteriormente Vertex AI). O cliente específico do fornecedor gere a autenticação e as opções de pedido do Gemini, enquanto o Agent Framework é responsável pela definição e pela orquestração do agente.
Importante
O Google Gemini e o Vertex AI são sistemas de terceiros. Revise os termos do serviço, o tratamento dos dados, os limites regionais, o acesso ao modelo e os custos de utilização antes de enviar os dados da aplicação.
Instale o Gemini IChatClient
O exemplo .NET demonstra o cliente oficial 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 a sua API de Desenvolvimento Gemini ou a autenticação Vertex AI.
Instale o pacote
pip install agent-framework-gemini --pre
Configuration
Utilize uma das seguintes opções: a API para Programadores Gemini:
GOOGLE_API_KEY="<api-key>"
GOOGLE_MODEL="gemini-2.5-flash"
Ou configure a 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 definição mais antiga GOOGLE_GENAI_USE_VERTEXAI=true continua a ser suportada. O conector já não lê GEMINI_API_KEY, GEMINI_MODEL, ou GEMINI_EMBEDDING_MODEL; utiliza as variáveis correspondentes GOOGLE_* ou passa valores explicitamente.
GeminiChatClient Suporta streaming, ferramentas funcionais, output estruturado, pensamento alargado e ferramentas alojadas pelo fornecedor.
"""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")
Gerir falhas de pedidos
Para execuções com e sem streaming, as falhas nas solicitações do Gemini SDK são comunicadas através de exceções do Agent Framework. As falhas HTTP 401 e 403 geram ChatClientInvalidAuthException, as outras falhas HTTP 4xx geram ChatClientInvalidRequestException, e todas as outras falhas do fornecedor geram ChatClientException.
Perceba ChatClientException quando o mesmo tratamento de erros deve aplicar-se a todos os fornecedores de chat.
Inclua resumos de pensamento
O exemplo de pensamento estendido mostra como configurar ThinkingConfig. Para receber resumos do processo de pensamento do Gemini, defina include_thoughts=True na configuração de raciocínio:
options: GeminiChatOptions = {
"thinking_config": ThinkingConfig(include_thoughts=True, thinking_budget=2048),
}
Quando Gemini devolve uma síntese do raciocínio, GeminiChatClient adiciona-a à 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 de transmissão, filtre cada chunk.contents. Os acessórios de texto como result.text e chunk.text incluem apenas text conteúdo, por isso inspecione as coleções de conteúdos quando a sua aplicação precisar de resumos de raciocínio.
Gerar incorporações
GeminiEmbeddingClient usa gemini-embedding-2 por defeito. Substitua-o por GOOGLE_EMBEDDING_MODEL ou pelo parâmetro do construtor model. As entradas de texto requerem um tipo de tarefa em cada chamada; usar RETRIEVAL_DOCUMENT ao indexar e RETRIEVAL_QUERY ao procurar no mesmo espaço vetorial.
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")
Utilize o mesmo modelo e as mesmas dimensões para embeddings de documentos e consultas. O cliente também aceita valores de multimédia Part e Content do SDK da Google para embeddings de imagem, áudio, vídeo, PDF ou combinados de texto e multimédia. As entradas multimédia não utilizam um prefixo da tarefa de texto.
Quando uma coleção de vetores gera embeddings, passe a tarefa do documento através de upsert(..., embeddings_options=...) e a tarefa de consulta através de search(..., embeddings_options=...) ou create_vector_search_tool(..., embeddings_options=...). Para múltiplos campos vetoriais, use embeddings_options_by_field. O Agent Framework fornece as dimensões do campo selecionado e rejeita valores conflitantes.
O pacote inclui fábricas para aterramento da pesquisa Google, aterramento do Google Maps, execução de código, pesquisa de ficheiros e MCP.
Fundamentação na Pesquisa 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 disponibiliza geminiprovider para inferência com o Gemini. Crie um padrão *agent.Agent utilizando o construtor específico do fornecedor.
Veja o pacote do fornecedor Gemini e exemplos.
Tools
| Tool | C# | Python | Go | Observações |
|---|---|---|---|---|
| Ferramentas Funcionais | ✅ | ✅ | ✅ | Chamadas de funções do modelo padrão. |
| Aprovação de Ferramentas | ✅ | ✅ | ✅ | Aplicado pelo ciclo de ferramentas framework. |
| Intérprete de código | ❌ | ✅ | ❌ |
GeminiChatClient.get_code_interpreter_tool(). |
| Pesquisa de ficheiros | ❌ | ✅ | ❌ |
GeminiChatClient.get_file_search_tool(). |
| Pesquisa na Web | ❌ | ✅ | ❌ | Fundamentação da Pesquisa Google através de get_web_search_tool(). |
| Ancoragem no Google Maps | ❌ | ✅ | ❌ |
GeminiChatClient.get_maps_grounding_tool(). |
| Ferramentas alojadas do MCP | ❌ | ✅ | ❌ |
GeminiChatClient.get_mcp_tool(). |
| Ferramentas MCP Locais | ✅ | ✅ | ✅ | É executado no processo da aplicação. |