谷歌雙子座

Google Gemini 可以透過 Gemini 開發者 API 或 Gemini Enterprise Agent Platform(前稱 Vertex AI)來支援 Agent Framework。 提供者專屬客戶端負責認證與 Gemini 請求選項,而代理框架則擁有代理定義與編排。

這很重要

Google Gemini 和 Vertex AI 是第三方系統。 在傳送應用程式資料前,請先審查服務條款、資料處理、區域邊界、模型存取及使用成本。

安裝 Gemini IChatClient

.NET 範例展示了官方的 Google GenAI 客戶端及社群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}");

選擇一個 IChatClient 實作並設定其 Gemini 開發者 API 或 Vertex AI 認證。

安裝套件

pip install agent-framework-gemini --pre

Configuration

使用以下其中一種:Gemini 開發人員 API:

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

或者設定 Gemini Enterprise Agent Platform:

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

舊 GOOGLE_GENAI_USE_VERTEXAI=true 設定仍被支援。 連接器不再讀取 GEMINI_API_KEY、GEMINI_EMBEDDING_MODEL 或 GOOGLE_*;請改用對應的 GEMINI_MODEL 變數,或明確傳入值。

GeminiChatClient 支援串流、函式工具、結構化輸出、延伸思考及提供者託管工具。

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

處理請求失敗的情況

對於串流與非串流執行,Gemini SDK 的請求失敗會透過代理框架例外揭露。 HTTP 401 和 403 失敗會發生 ChatClientInvalidAuthException,其他 HTTP 4xx 失敗也會發生 ChatClientInvalidRequestException,所有其他提供者失敗也會出現 ChatClientException。

當相同的錯誤處理應套用於不同聊天提供者時,請擷取ChatClientException。

包含思想摘要

延伸思考範例展示了如何配置 ThinkingConfig。 若要接收 Gemini 的思考摘要,請在 thinking configuration 中設定 include_thoughts=True:

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

當 Gemini 傳回思考摘要時,GeminiChatClient 會將其以 Content 的形式加入回應中,並搭配 type == "text_reasoning"。 請閱讀以下摘要。content.text

對於未使用串流的執行作業,請篩選 result.messages 中每個項目的 contents。 串流時,過濾每個 chunk.contents。 像 result.text 和 chunk.text 這類文字存取器只包含 text 內容,因此當您的應用程式需要推理摘要時,請檢查內容集合。

產生內嵌

GeminiEmbeddingClient 預設使用 gemini-embedding-2。 用 GOOGLE_EMBEDDING_MODEL 或 model 建構參數覆蓋它。 文字輸入在每次呼叫時都需要指定任務類型;建立索引時使用 RETRIEVAL_QUERY,而在搜尋相同向量空間時使用 RETRIEVAL_DOCUMENT。


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

文件和查詢嵌入時使用相同的模型和維度。 用戶端也接受適用於影像、音訊、影片、PDF 或文字與媒體混合嵌入的 Google SDK 媒體 Part 和 Content 值。 媒體輸入不會使用文字工作前置詞。

當向量集合產生嵌入向量時,請將文件任務透過 upsert(..., embeddings_options=...) 傳遞,並將查詢任務透過 search(..., embeddings_options=...) 或 create_vector_search_tool(..., embeddings_options=...) 傳遞。 對於多向量場,請使用 embeddings_options_by_field。 代理框架提供所選欄位的維度,並拒絕衝突的值。

此套件包含用於以 Google 搜尋為基礎、以 Google Maps 為基礎、程式碼執行、檔案搜尋和 MCP 的工廠。

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

Go SDK 為 Gemini 推論提供 geminiprovider。 透過提供者專屬建構器建立標準 *agent.Agent 。

請參閱 Gemini 供應商方案 及 範例。

Tools

Tool C# Python Go 註釋
函式工具 ✅ ✅ ✅ 標準模型函數呼叫。
工具核准 ✅ ✅ ✅ 透過框架工具迴圈應用。
程式碼解譯器 ❌ ✅ ❌ GeminiChatClient.get_code_interpreter_tool()。
檔案搜尋 ❌ ✅ ❌ GeminiChatClient.get_file_search_tool()。
網路搜尋 ❌ ✅ ❌ 透過 get_web_search_tool() 以 Google 搜尋為基礎。
以 Google Maps 為基礎 ❌ ✅ ❌ GeminiChatClient.get_maps_grounding_tool()。
託管 MCP 工具 ❌ ✅ ❌ GeminiChatClient.get_mcp_tool()。
本地 MCP 工具 ✅ ✅ ✅ 在應用程式程序中執行。

下一步