Google Gemini 可以通过 Gemini Developer API 或 Gemini Enterprise Agent Platform(原 Vertex AI)为 Agent Framework 代理提供支持。 特定于提供程序的客户端负责处理身份验证和 Gemini 请求选项,而 Agent Framework 负责代理定义和编排。
重要
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 Developer 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_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。 若要接收双子座思想摘要,请设置 include_thoughts=True 在思维配置中:
options: GeminiChatOptions = {
"thinking_config": ThinkingConfig(include_thoughts=True, thinking_budget=2048),
}
当双子座返回一个想法摘要时,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")
对文档和查询嵌入使用相同的模型和维度。 客户端还接受 Google SDK 的媒体 Part 和 Content 值,用于图像、音频、视频、PDF 或文本与媒体组合嵌入。 媒体输入不使用文本任务前缀。
当向量集合生成嵌入时,请将文档任务传递给 upsert(..., embeddings_options=...),并将查询任务传递给 search(..., embeddings_options=...) 或 create_vector_search_tool(..., embeddings_options=...)。 对于多个向量字段,请使用 embeddings_options_by_field。 代理框架提供所选字段的维度,并拒绝冲突值。
该软件包包含用于 Google 搜索基础支持、Google 地图基础支持、代码执行、文件搜索和 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
| 工具 | 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 工具 | ✅ | ✅ | ✅ | 在应用程序进程中运行。 |