구글 Gemini

Google Gemini는 Gemini 개발자 API 또는 Gemini Enterprise Agent Platform(이전의 꼭짓점 AI)을 통해 에이전트 프레임워크 에이전트를 백업할 수 있습니다. 에이전트 프레임워크가 에이전트 정의 및 오케스트레이션을 소유하는 동안 공급자별 클라이언트는 인증 및 Gemini 요청 옵션을 처리합니다.

중요합니다

Google Gemini 및 꼭짓점 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 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 설정은 계속 지원됩니다. 커넥터는 더 이상 GOOGLE_*, GEMINI_API_KEY 또는 GEMINI_MODEL를 읽지 않습니다. 해당하는 GEMINI_EMBEDDING_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 구성에서 include_thoughts=True를 설정하세요.

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

Gemini가 생각 요약 GeminiChatClient 을 반환하면 다음과 같이 Contenttype == "text_reasoning"응답에 추가합니다. content.text에서 요약을 읽어보세요.

스트리밍 없이 실행하려면 contents에서 각 항목의 result.messages을 필터링합니다. 스트리밍 실행의 경우 각각 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 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

Tool C# Python Go 비고
함수 도구 ✅ ✅ ✅ 표준 모델 함수 호출.
도구 승인 ✅ ✅ ✅ 프레임워크 도구 루프에 의해 적용됩니다.
코드 해석기 ❌ ✅ ❌ GeminiChatClient.get_code_interpreter_tool();
파일 검색 ❌ ✅ ❌ GeminiChatClient.get_file_search_tool();
웹 검색 ❌ ✅ ❌ get_web_search_tool()를 통한 Google Search 그라운딩
Google Maps 그라운딩 ❌ ✅ ❌ GeminiChatClient.get_maps_grounding_tool();
호스트된 MCP 도구 ❌ ✅ ❌ GeminiChatClient.get_mcp_tool();
로컬 MCP 도구 ✅ ✅ ✅ 애플리케이션 프로세스에서 실행됩니다.

다음 단계