Google Gemma 模型,适用于 ADK(Android Development Kit)代理程序¶
ADK 代理可以使用该功能。 Google Gemma 这是一系列生成式人工智能模型,它们具备广泛的功能。ADK 支持许多 Gemma 的特性,包括…… 工具调用(Tool Calling) 和 结构化输出(Structured Output).
您可以通过以下方式使用 Gemma 4: Gemini API或者,您也可以选择 Google Cloud 提供的多种自托管方案之一来进行部署: 代理平台(Agent Platform), Google Kubernetes Engine, Cloud Run.
Gemma 3 需要使用与下面 Gemma 4 示例不同的模型类。Gemma 3 不支持任何原生的函数调用或系统指令;因此,ADK 通过专门的类提供了相应的解决方案(即替代方案)。 Gemma(model="gemma-3-27b-it") 对于 Gemini API 来说…… Gemma3Ollama() 对于 Ollama 来说,这两者都来自…… google.adk.models.
Gemma3Ollama 该变量仅在满足特定条件时才会被定义。 LiteLLM 该软件是否已安装?)litellm>=1.84).
Gemini API 示例¶
在……中创建一个 API 密钥。 Google AI Studio.
# Set GEMINI_API_KEY environment variable to your API key
# export GEMINI_API_KEY="YOUR_API_KEY"
from google.adk.agents import LlmAgent
from google.adk.models import Gemini
# Simple tool to try
def get_weather(location: str) -> str:
return f"Location: {location}. Weather: sunny, 76 degrees Fahrenheit, 8 mph wind."
root_agent = LlmAgent(
model=Gemini(model="gemma-4-31b-it"),
name="weather_agent",
instruction="You are a helpful assistant that can provide current weather.",
tools=[get_weather]
)
// Set GEMINI_API_KEY environment variable to your API key
// export GEMINI_API_KEY="YOUR_API_KEY"
import com.google.adk.agents.LlmAgent;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.FunctionTool;
LlmAgent weatherAgent = LlmAgent.builder()
.model("gemma-4-31b-it")
.name("weather_agent")
.instruction("""
You are a helpful assistant that can provide current weather.
""")
.tools(FunctionTool.create(this, "getWeather"))
.build();
@Schema(name = "getWeather",
description = "Retrieve the weather forecast for a given location")
public Map<String, String> getWeather(
@Schema(name = "location",
description = "The location for the weather forecast")
String location) {
return Map.of("forecast", "Location: " + location
+ ". Weather: sunny, 76 degrees Fahrenheit, 8 mph wind.");
}
vLLM 示例¶
要访问这些服务中的 Gemma 4 终端点,您可以通过 vLLM 模型来实现。 LiteLLM 这是一个用于 Python 的库;通过这个库,可以……(具体功能或操作在后续内容中说明)。 LangChain4j 适用于 Java 的代码。
以下示例展示了如何将 Gemma 4 vLLM 终点与 ADK 代理一起使用。
设置¶
- 部署模型: 使用以下方法部署您选择的模型:
代理平台(Agent Platform),
Google Kubernetes Engine或者 Cloud Run请使用其与 OpenAI 兼容的 API 端点。
请注意,API 的基础 URL 包含了……(具体内容请根据实际情况填写)。
/v1(e.g.,https://your-vllm-endpoint.run.app/v1).- 对于 ADK 工具来说非常重要: 在部署过程中,请确保所使用的服务工具支持并能够调用兼容的工具/功能,同时具备相应的解析(reasoning)能力。
- 身份验证: 确定您的终端点(endpoint)如何处理身份验证(例如:API密钥、bearer token等)。
代码¶
import subprocess
from google.adk.agents import LlmAgent
from google.adk.models.lite_llm import LiteLlm
# --- Example Agent using a model hosted on a vLLM endpoint ---
# Endpoint URL provided by your model deployment
api_base_url = "https://your-vllm-endpoint.run.app/v1"
# Model name as recognized by *your* vLLM endpoint configuration
model_name_at_endpoint = "openai/google/gemma-4-31B-it"
# Simple tool to try
def get_weather(location: str) -> str:
return f"Location: {location}. Weather: sunny, 76 degrees Fahrenheit, 8 mph wind."
# Authentication (Example: using gcloud identity token for a Cloud Run deployment)
# Adapt this based on your endpoint's security
try:
gcloud_token = subprocess.check_output(
["gcloud", "auth", "print-identity-token", "-q"]
).decode().strip()
auth_headers = {"Authorization": f"Bearer {gcloud_token}"}
except Exception as e:
print(f"Warning: Could not get gcloud token - {e}.")
auth_headers = None # Or handle error appropriately
root_agent = LlmAgent(
model=LiteLlm(
model=model_name_at_endpoint,
api_base=api_base_url,
# Pass authentication headers if needed
extra_headers=auth_headers,
# Alternatively, if endpoint uses an API key:
# api_key="YOUR_ENDPOINT_API_KEY",
extra_body={
"chat_template_kwargs": {
"enable_thinking": True # Enable thinking
},
"skip_special_tokens": False # Should be set to False
},
),
name="weather_agent",
instruction="You are a helpful assistant that can provide current weather.",
tools=[get_weather] # Tools!
)
要使用托管在 vLLM 上的 Gemma,你必须使用一个与 OpenAI 兼容的库。LangChain4j 提供了一个 OpenAI 依赖项,你可以将其添加到你的项目中。 pom.xml:
<!-- LangChain4j to ADK bridge -->
<dependency>
<groupId>com.google.adk</groupId>
<artifactId>google-adk-langchain4j</artifactId>
<version>${adk.version}</version>
</dependency>
<!-- Core LangChain4j library -->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-core</artifactId>
<version>${langchain4j.version}</version>
</dependency>
<!-- OpenAI compatible model -->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai</artifactId>
<version>${langchain4j.version}</version>
</dependency>
创建一个与 OpenAI 兼容的聊天模型(支持流式传输或非流式传输),并将其封装在适当的框架或系统中。 LangChain4j `wrapper`,
然后将其传递给…… LlmAgent:
import com.google.adk.agents.LlmAgent;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.FunctionTool;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
// Endpoint URL provided by your model deployment
String apiBaseUrl = "https://your-vllm-endpoint.run.app/v1";
// Model name as recognized by *your* vLLM endpoint configuration
String gemmaModelName = "gg-hf-gg/gemma-4-31b-it";
// First, define an OpenAI compatible chat model with LangChain4j
StreamingChatModel model =
OpenAiStreamingChatModel.builder()
.modelName(gemmaModelName)
// If your endpoint requires an API key
// .apiKey("YOUR_ENDPOINT_API_KEY")
.baseUrl(apiBaseUrl)
.customParameters(
Map.of(
"skip_special_tokens", false,
"chat_template_kwargs", Map.of("enable_thinking", true)
)
)
.build();
// Configure the agent with the LangChain4j wrapper model
LlmAgent weatherAgent = LlmAgent.builder()
.model(new LangChain4j(model))
.name("weather_agent")
.instruction("""
You are a helpful assistant that can provide the current weather.
""")
.tools(FunctionTool.create(this, "getWeather"))
.build();
@Schema(name = "getWeather",
description = "Retrieve the weather forecast for a given location")
public Map<String, String> getWeather(
@Schema(name = "location",
description = "The location for the weather forecast")
String location) {
return Map.of("forecast", "Location: " + location
+ ". Weather: sunny, 76 degrees Fahrenheit, 8 mph wind.");
}
使用 Gemma 4、ADK 和 Google Maps MCP 构建一个食品旅游代理服务系统。¶
这个示例展示了如何使用 Gemma 4、ADK 以及 Google Maps MCP 服务器来创建一个个性化的美食旅游服务代理。该代理会接收用户提供的菜肴照片或文字描述、所在位置以及可选的预算信息,随后会推荐适合就餐的场所,并将这些推荐地点安排成一条步行路线。
先决条件¶
- 获取 API 密钥。 Google AI Studio```
Set
```
GEMINI_API_KEY将环境变量设置为你的 Gemini API 密钥。 - 启用 Google Maps API 在 Google Cloud Console 中。
- 创建一个…… Google Maps Platform API 密钥```
Set
```
MAPS_API_KEY将环境变量中的值设置为你的 API 密钥。 - 在您的 Python 环境中安装 ADK 并对其进行配置; 或者,在您的 Java 项目中配置所需的 Java 依赖项。
项目结构¶
agent.py
import os
import dotenv
from google.adk.agents import LlmAgent
from google.adk.models import Gemini
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
dotenv.load_dotenv()
system_instruction = """
You are an expert personalized food tour guide.
Your goal is to build a culinary tour based on the user's inputs: a photo of a dish (or a text description), a location, and a budget.
Follow these 4 rigorous steps:
1. **Identify the Cuisine/Dish:** Analyze the user's provided description or image URL to determine the primary cuisine or specific dish.
2. **Find the Best Spots:** Use the `search_places` tool to find highly rated restaurants, stalls, or cafes serving that cuisine/dish in the user's specified location.
**CRITICAL RULE FOR PLACES:** `search_places` returns AI-generated place data summaries along with `place_id`, latitude/longitude coordinates, and map links for each place, but may lack a direct, explicit name field. You must carefully associate each described place to its provided `place_id` or `lat_lng`.
3. **Build the Route:** Use the `compute_routes` tool to structure a walking-optimized route between the selected spots.
**CRITICAL ROUTING RULE:** To avoid hallucinating, you MUST provide the `origin` and `destination` using the exact `place_id` string OR `lat_lng` object returned by `search_places`. Do NOT guess or hallucinate an `address` or `place_id` if you do not know the exact name.
4. **Insider Tips:** Provide specific "order this, skip that" insider tips for each location on the tour.
Structure your response clearly and concisely. If the user provides a budget, ensure your suggestions align with it.
"""
MAPS_MCP_URL = "https://mapstools.googleapis.com/mcp"
def get_maps_mcp_toolset():
dotenv.load_dotenv()
maps_api_key = os.getenv("MAPS_API_KEY")
if not maps_api_key:
print("Warning: MAPS_API_KEY environment variable not found.")
maps_api_key = "no_api_found"
tools = McpToolset(
connection_params=StreamableHTTPConnectionParams(
url=MAPS_MCP_URL,
headers={
"X-Goog-Api-Key": maps_api_key
}
)
)
print("Google Maps MCP Toolset configured.")
return tools
maps_toolset = get_maps_mcp_toolset()
root_agent = LlmAgent(
model=Gemini(model="gemma-4-31b-it"),
name="food_tour_agent",
instruction=system_instruction,
tools=[maps_toolset],
)
环境变量¶
在运行代理程序之前,请设置所需的环境变量。
示例用法:¶
为了测试“美食之旅代理”(Food Tour Agent)的功能,可以尝试将以下提示之一粘贴到聊天框中:
- “我想在多伦多体验一下拉面文化。我的预算是一天60美元。请为我规划一条步行路线,推荐三家最好的拉面店,并告诉我每家店应该点什么食物。”
- “我有一张深盘披萨的照片(请插入图片的 URL)。我想在芝加哥的 Navy Pier 附近找到最适合享用这种披萨的地方。请为我规划一条步行游览路线,并告诉我每个游览地点的必尝披萨是什么。”
- “我在奥斯汀市中心,正在寻找一场真正的烧烤之旅。希望预算能控制在 100 美元以内。请规划一条从三家评分很高的烧烤店出发的步行路线,并告诉我哪些部位的肉最好吃。”
该代理将执行以下操作:
- 推断可能的菜肴类型或烹饪风格。
- 使用 Google Maps MCP 工具搜索相关的地点。
- 计算选定站点之间的步行路线
- 提供一个结构化的美食之旅服务,其中包含美食推荐及内部人士提供的实用建议。