Notatka
Dostęp do tej strony wymaga autoryzacji. Może spróbować zalogować się lub zmienić katalogi.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
Google Gemini może obsługiwać agenta Agent Framework za pośrednictwem interfejsu API Gemini Developer lub platformy Gemini Enterprise Agent Platform (dawniej Vertex AI). Klient specyficzny dla danego dostawcy obsługuje uwierzytelnianie oraz opcje żądań Gemini, natomiast Agent Framework odpowiada za definicję i orkiestrację agenta.
Important
Google Gemini i Vertex AI to systemy innych firm. Przed wysłaniem danych zapoznaj się z warunkami usług, obsługą danych, granicami regionalnymi, dostępem do modelu i kosztami użycia.
Zainstaluj Gemini IChatClient
Przykład .NET demonstruje oficjalnego klienta Google GenAI oraz implementację stworzoną przez społeczność Mscc.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}");
Wybierz jedną z implementacji IChatClient i skonfiguruj uwierzytelnianie Gemini Developer API lub Vertex AI.
Instalowanie pakietu
pip install agent-framework-gemini --pre
Configuration
Użyj jednego z interfejsów API Gemini dla deweloperów:
GOOGLE_API_KEY="<api-key>"
GOOGLE_MODEL="gemini-2.5-flash"
Możesz też skonfigurować platformę Gemini Enterprise Agent Platform:
GOOGLE_GENAI_USE_ENTERPRISE="true"
GOOGLE_CLOUD_PROJECT="<project-id>"
GOOGLE_CLOUD_LOCATION="global"
GOOGLE_MODEL="gemini-2.5-flash"
Starsze GOOGLE_GENAI_USE_VERTEXAI=true ustawienie pozostaje obsługiwane. Łącznik już nie odczytuje GEMINI_API_KEY, GEMINI_MODEL ani GEMINI_EMBEDDING_MODEL; użyj odpowiednich zmiennych GOOGLE_* lub przekaż wartości jawnie.
GeminiChatClient obsługuje strumieniowanie, narzędzia funkcyjne, ustrukturyzowane dane wyjściowe, rozszerzone rozumowanie i narzędzia hostowane przez dostawcę.
"""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")
Obsługa błędów żądań
W przypadku uruchomień strumieniowych i niestrumieniowych błędy żądań SDK Gemini są zgłaszane poprzez wyjątki platformy Agent Framework. Błędy HTTP 401 i 403 powodują zgłoszenie ChatClientInvalidAuthException, inne błędy HTTP 4xx powodują zgłoszenie ChatClientInvalidRequestException, a wszystkie pozostałe błędy dostawcy powodują zgłoszenie ChatClientException.
Użyj ChatClientException, gdy ta sama obsługa błędów powinna być stosowana u różnych dostawców czatu.
Uwzględnij podsumowania myśli
Przykład z rozszerzonym rozumowaniem pokazuje, jak skonfigurować ThinkingConfig. Aby otrzymywać podsumowania myśli Gemini, ustaw include_thoughts=True w konfiguracji myślenia:
options: GeminiChatOptions = {
"thinking_config": ThinkingConfig(include_thoughts=True, thinking_budget=2048),
}
Gdy Gemini zwraca podsumowanie myśli, GeminiChatClient dodaje je do odpowiedzi tak jak Content w przypadku type == "text_reasoning". Przeczytaj podsumowanie z witryny content.text.
W przypadku uruchomienia bez strumieniowania przefiltruj contents każdego elementu w result.messages. W przypadku przebiegu przesyłania strumieniowego przefiltruj każdy chunk.contentselement . Akcesory tekstowe, takie jak result.text i chunk.text, zawierają wyłącznie treść text, więc sprawdź kolekcje treści, gdy aplikacja potrzebuje podsumowań rozumowania.
Generowanie embedów
GeminiEmbeddingClient używa gemini-embedding-2 domyślnie. Zastąpij go parametrem GOOGLE_EMBEDDING_MODEL lub konstruktorem model . Dane wejściowe tekstowe wymagają określenia typu zadania przy każdym wywołaniu; użyj RETRIEVAL_DOCUMENT podczas indeksowania i RETRIEVAL_QUERY podczas przeszukiwania tej samej przestrzeni wektorowej.
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")
Użyj tego samego modelu i wymiarów dla osadzania dokumentów i zapytań. Klient akceptuje również wartości multimedialne Google SDK Content i Part dla osadzeń obrazów, audio, wideo, PDF lub łączonych osadzeń tekstu i multimediów. Wejścia multimedialne nie używają prefiksu zadania tekstowego.
Gdy kolekcja wektorów generuje embeddingi, przekaż zadanie dla dokumentu przez upsert(..., embeddings_options=...), a zadanie dla zapytania przez search(..., embeddings_options=...) lub create_vector_search_tool(..., embeddings_options=...). W przypadku wielu pól wektorowych użyj polecenia embeddings_options_by_field. Framework agenta udostępnia wymiary wybranego pola i odrzuca sprzeczne wartości.
Pakiet zawiera fabryki dla groundingu Google Search, groundingu Google Maps, wykonywania kodu, wyszukiwania plików i MCP.
Ugruntowanie w wyszukiwarce 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())
Pakiet SDK Go zapewnia geminiprovider do wnioskowania Gemini. Utwórz standard *agent.Agent za pomocą konstruktora specyficznego dla dostawcy.
Zobacz pakiet dostawcy Gemini i przykłady.
Tools
| Narzędzie | C# | Python | Go | Notatki |
|---|---|---|---|---|
| Narzędzia funkcji | ✅ | ✅ | ✅ | Standardowe wywoływanie funkcji modelu. |
| Zatwierdzanie narzędzi | ✅ | ✅ | ✅ | Zastosowane przez pętlę narzędzi platformy. |
| Interpreter kodów | ❌ | ✅ | ❌ |
GeminiChatClient.get_code_interpreter_tool(). |
| Wyszukiwanie plików | ❌ | ✅ | ❌ |
GeminiChatClient.get_file_search_tool(). |
| Wyszukiwanie w Sieci Web | ❌ | ✅ | ❌ | Oparcie na Wyszukiwarce Google przez get_web_search_tool(). |
| Uziemienia mapy Google | ❌ | ✅ | ❌ |
GeminiChatClient.get_maps_grounding_tool(). |
| Hostowane narzędzia MCP | ❌ | ✅ | ❌ |
GeminiChatClient.get_mcp_tool(). |
| Lokalne narzędzia MCP | ✅ | ✅ | ✅ | Uruchamia się w procesie aplikacji. |