Googleでジェミニを検索できます

Google Gemini は、Gemini Developer API または Gemini Enterprise Agent Platform (旧称 Vertex AI) を使用してエージェント フレームワーク エージェントをバックアップできます。 エージェント フレームワークがエージェント定義とオーケストレーションを所有している間、プロバイダー固有のクライアントは認証と Gemini 要求オプションを処理します。

Important

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

1 つの IChatClient 実装を選択し、その Gemini Developer API または Vertex AI 認証を構成します。

パッケージをインストールする

pip install agent-framework-gemini --pre

Configuration

Gemini Developer 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_MODEL、または GEMINI_EMBEDDING_MODELを読み取らなくなりました。対応する GOOGLE_* 変数を使用するか、値を明示的に渡します。

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 要求エラーは Agent Framework 例外によって公開されます。 HTTP 401 および 403 エラーでは ChatClientInvalidAuthExceptionが発生し、その他の HTTP 4xx エラーでは ChatClientInvalidRequestExceptionが発生し、他のすべてのプロバイダーエラーでは ChatClientExceptionが発生します。

同じエラー処理をチャット プロバイダー間で適用する必要がある場合に ChatClientException をキャッチします。

思考の概要を含める

拡張思考のサンプルは、ThinkingConfigを構成する方法を示しています。 Gemini thought の概要を受け取るために、思考構成で include_thoughts=True を設定します。

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

Gemini が思考の概要を返すと、GeminiChatClientはtype == "text_reasoning"をContentとして応答に追加します。 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を使用します。 Agent Framework は、選択したフィールドのディメンションを提供し、競合する値を拒否します。

このパッケージには、Google Search の接地、Google Maps の接地、コード実行、ファイル検索、MCP 用のファクトリが含まれています。

Google Search の基礎


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

ツール C# Python Go 注記
関数ツール ✅ ✅ ✅ 標準モデル関数の呼び出し。
ツールの承認 ✅ ✅ ✅ フレームワーク ツール ループによって適用されます。
コード インタープリター ❌ ✅ ❌ GeminiChatClient.get_code_interpreter_tool()。
ファイル検索 ❌ ✅ ❌ GeminiChatClient.get_file_search_tool()。
Web 検索 ❌ ✅ ❌ get_web_search_tool()を使用した Google 検索の基礎。
Google マップのグラウンディング ❌ ✅ ❌ GeminiChatClient.get_maps_grounding_tool()。
ホストされている MCP ツール ❌ ✅ ❌ GeminiChatClient.get_mcp_tool()。
ローカル MCP ツール ✅ ✅ ✅ アプリケーション プロセスで実行されます。

次のステップ