AI智能体的安全与防护措施¶
随着人工智能(AI)代理的能力不断提升,确保它们能够安全、可靠地运行,并且符合您的品牌价值观变得至关重要。如果这些代理被置于不受控制的状态,它们可能会带来各种风险:例如执行与您的品牌价值观相悖或有害的操作(如数据泄露),或者生成可能损害您品牌声誉的内容。 风险来源包括:模糊的指令、模型产生的错误结果(即“模型幻觉”)、设备被非法破解(即“越狱”行为),以及来自恶意用户的直接指令注入;此外,还可能存在通过工具进行的间接指令注入。
Google Cloud Agent Platform 提供了一种多层次的方法来降低这些风险,使您能够构建强大的(系统或解决方案)。 和 这些代理是值得信赖的。系统提供了多种机制来设定严格的限制,确保代理仅执行您明确允许的操作。
- 身份验证与授权(Identity and Authorization):控制谁可以成为代理(即谁可以使用该代理服务)。 充当;起……的作用 通过定义代理(agent)和用户的身份验证机制(auth.)。
-
用于筛选输入和输出数据的防护机制(或:用于确保数据安全性的控制措施)。 精确地控制您的模型调用及工具使用。
- 工具内置的安全防护机制(In-Tool Guardrails): 应以防御性的方式设计开发工具,并利用开发者设定的工具配置来强制执行相关策略(例如:仅允许对特定表进行查询)。
- 内置的 Gemini 安全功能: 如果使用 Gemini 模型,可以利用内容过滤器来阻止有害的输出;同时还可以参考系统的使用说明来指导模型的行为,并遵守相关的安全准则。
- 回调函数(Callbacks)与插件(Plugins): 在执行模型或工具调用之前或之后,验证相关参数是否与代理的状态或外部政策相符。
- 将 Gemini 作为安全保障措施: 使用一个价格低廉且运行速度快的模型(例如 Gemini Flash Lite),并通过回调函数来监控输入和输出数据,从而实现额外的安全防护层。
-
沙箱环境中的代码执行: 通过将环境置于沙箱环境中(即限制其访问权限和功能),防止模型生成的代码引发安全问题。
- 评估与追踪使用评估工具来评估代理最终输出的质量、相关性和正确性。通过跟踪代理的行为来了解其解决问题的过程,包括它所选择的工具、采用的策略以及其处理问题的效率。
- 网络控制与 VPC-SC: 将代理的活动限制在安全的范围内(例如通过 VPC 服务控制机制),以防止数据泄露并降低潜在的影响范围。
安全与保障风险¶
在实施安全措施之前,请针对您的代理程序的功能、所处理的领域以及部署环境进行彻底的风险评估。
来源(Sources) 有风险;处于危险之中 ```json { "include": [ "API 标识符1", "API 标识符2", "API 标识符3", "占位符1", "占位符2", "占位符3" ] } ```
- 模糊的代理指令(Ambiguous agent instructions)
- 来自恶意用户的提示注入(prompt injection)攻击以及越狱(jailbreak)尝试
- 通过使用工具进行间接的提示信息注入(即:通过工具将预设的提示信息注入到目标系统中)
风险类别 ```json { "include": [ "API 标识符1", "API 标识符2", "API 标识符3", "占位符1", "占位符2", "占位符3" ] } ```
- 数据错位(Misalignment)与目标值被篡改(Goal Corruption)
- 追求那些无意中产生的、或通过代理手段实现的、最终会导致有害后果的目标(即所谓的“奖励欺骗行为”)。
- 误解复杂或含糊的指令
- 有害内容的生成,包括对品牌安全的威胁。
- 生成具有毒性、仇恨言论、偏见、露骨的性内容、歧视性内容或非法内容。
- 品牌安全风险包括:使用与品牌价值观相悖的语言,或进行与主题无关的对话。
- 不安全的行为
- 正在执行那些会损坏系统的命令。
- 进行未经授权的购买或财务交易。
- 泄露敏感的个人信息(PII)
- 数据泄露(Data exfiltration)
最佳实践¶
身份验证与授权(Identity and Authorization)¶
“身份”(identity)指的是一个人或事物所具有的独特特征或属性,这些特征或属性使其与其他人或事物区分开来。在许多情况下,身份还与个人的身份证明(如身份证、护照等)相关联。 tool 从安全角度来看,用于对外部系统执行操作的机制是一个非常重要的设计考量因素。同一个代理中的不同工具可以被配置为使用不同的策略;因此,在讨论代理的配置时需要格外小心。
Agent-Auth¶
The 该工具使用代理自身的身份与外部系统进行交互。 代理的身份必须在外部系统的访问策略中得到明确授权;例如,需要将代理的服务账户添加到数据库的 IAM(身份与访问管理)策略中,以授予其读取权限。这样的策略会限制代理只能执行开发者预先定义的操作:如果只授予代理读取权限,那么无论模型如何判断或决策,该代理都无法执行写入操作。
这种方法的实现非常简单。 适用于所有用户都具有相同访问权限的场景(即代理系统在这种情况下能够正常运行)。 如果并非所有用户都具有相同的访问权限,那么仅依靠这种方法是无法提供足够的安全保护的,必须结合以下其他技术来增强安全性。在工具实现过程中,务必确保生成日志记录,以便能够追踪用户的操作行为;因为所有代理的操作都会被显示为来自该代理本身。
用户认证(User Auth)¶
该工具通过以下方式与外部系统进行交互: “控制用户”的身份 (例如,用户在 Web 应用程序中与前端界面进行交互。)在 ADK 中,这通常是通过 OAuth 来实现的:代理程序与前端界面交互以获取 OAuth 令牌,然后工具在执行外部操作时使用该令牌;如果被控制的用户具有执行该操作的权限,外部系统会授权该操作。
用户身份验证的优势在于:代理仅执行用户自己能够执行的操作。这大大降低了恶意用户利用代理获取额外数据的风险。然而,大多数常见的授权机制都提供了固定的权限集(即 OAuth 的授权范围)。通常,这些授权范围比代理实际所需的访问权限更为广泛,因此需要采用以下技术来进一步限制代理的行为。
用于筛选输入和输出数据的防护机制(或“护栏”)¶
工具内置的安全防护装置(即“工具中的护栏”)¶
这些工具可以在设计时就充分考虑安全性:我们可以创建这样的工具,它们仅允许模型执行我们希望其执行的操作,而不会执行其他任何操作。通过限制我们提供给代理程序的操作范围,我们可以彻底消除那些代理程序绝对不应该执行的非法操作(即“恶意操作”)。
“工具内置的安全机制”(In-tool guardrails)是一种用于开发通用且可重复使用的工具的方法。这些工具提供了可预测(即“确定性”)的控制机制,开发人员可以利用这些机制为每个工具实例设置相应的限制(即“边界”或“使用规则”)。
这种方法基于这样一个事实:工具接收两种类型的输入:一种是模型设置的参数(arguments);另一种是……(此处内容缺失)。 Tool Context这些参数可以由代理开发者(agent developer)以确定性的方式(即:不会发生变化的方式)进行设置。我们可以依赖这些被确定性设置的信息来验证模型的行为是否符合预期。 (注意:在 TypeScript 中,……) Tool Context 与“统一标准”相对应。 Context (type.)
例如,可以设计一个查询工具,使其能够从“工具上下文”(Tool Context)中读取相应的策略信息。
# Conceptual example: Setting policy data intended for tool context
# In a real ADK app, this might be set in InvocationContext.session.state
# or passed during tool initialization, then retrieved via ToolContext.
policy = {} # Assuming policy is a dictionary
policy['select_only'] = True
policy['tables'] = ['mytable1', 'mytable2']
# Conceptual: Storing policy where the tool can access it via ToolContext later.
# This specific line might look different in practice.
# For example, storing in session state:
invocation_context.session.state["query_tool_policy"] = policy
# Or maybe passing during tool init:
query_tool = QueryTool(policy=policy)
# For this example, we'll assume it gets stored somewhere accessible.
// Conceptual example: Setting policy data intended for tool context
// In a real ADK app, this might be set in InvocationContext.session.state
// or passed during tool initialization, then retrieved via Context.
const policy: {[key: string]: any} = {}; // Assuming policy is an object
policy['select_only'] = true;
policy['tables'] = ['mytable1', 'mytable2'];
// Conceptual: Storing policy where the tool can access it via Context later.
// This specific line might look different in practice.
// For example, storing in session state:
invocationContext.session.state["query_tool_policy"] = policy;
// Or maybe passing during tool init:
const queryTool = new QueryTool({policy: policy});
// For this example, we'll assume it gets stored somewhere accessible.
// Conceptual example: Setting policy data intended for tool context
// In a real ADK app, this might be set using the session state service.
// `ctx` is an `agent.Context` available in callbacks or custom agents.
policy := map[string]any{
"select_only": true,
"tables": []string{"mytable1", "mytable2"},
}
// Conceptual: Storing policy where the tool can access it via ToolContext later.
// This specific line might look different in practice.
// For example, storing in session state:
if err := ctx.Session().State().Set("query_tool_policy", policy); err != nil {
// Handle error, e.g., log it.
}
// Or maybe passing during tool init:
// queryTool := NewQueryTool(policy)
// For this example, we'll assume it gets stored somewhere accessible.
// Conceptual example: Setting policy data intended for tool context
// In a real ADK app, this might be set in InvocationContext.session.state
// or passed during tool initialization, then retrieved via ToolContext.
policy = new HashMap<String, Object>(); // Assuming policy is a Map
policy.put("select_only", true);
policy.put("tables", new ArrayList<>("mytable1", "mytable2"));
// Conceptual: Storing policy where the tool can access it via ToolContext later.
// This specific line might look different in practice.
// For example, storing in session state:
invocationContext.session().state().put("query_tool_policy", policy);
// Or maybe passing during tool init:
query_tool = QueryTool(policy);
// For this example, we'll assume it gets stored somewhere accessible.
在工具执行过程中, Tool Context 该数据将被传递给相应的工具进行处理。 (注意:在 TypeScript 中,这些数据是以统一的形式传递的。) Context (type):
def query(query: str, tool_context: ToolContext) -> str | dict:
# Assume 'policy' is retrieved from context, e.g., via session state:
# policy = tool_context.invocation_context.session.state.get('query_tool_policy', {})
# --- Placeholder Policy Enforcement ---
policy = tool_context.invocation_context.session.state.get('query_tool_policy', {}) # Example retrieval
actual_tables = explainQuery(query) # Hypothetical function call
if not set(actual_tables).issubset(set(policy.get('tables', []))):
# Return an error message for the model
allowed = ", ".join(policy.get('tables', ['(None defined)']))
return f"Error: Query targets unauthorized tables. Allowed: {allowed}"
if policy.get('select_only', False):
if not query.strip().upper().startswith("SELECT"):
return "Error: Policy restricts queries to SELECT statements only."
# --- End Policy Enforcement ---
print(f"Executing validated query (hypothetical): {query}")
return {"status": "success", "results": [...]} # Example successful return
function query(query: string, context: Context): string | object {
// Assume 'policy' is retrieved from context, e.g., via session state:
const policy = context.state.get('query_tool_policy', {}) as {[key: string]: any};
// --- Placeholder Policy Enforcement ---
const actual_tables = explainQuery(query); // Hypothetical function call
const policyTables = new Set(policy['tables'] || []);
const isSubset = actual_tables.every(table => policyTables.has(table));
if (!isSubset) {
// Return an error message for the model
const allowed = (policy['tables'] || ['(None defined)']).join(', ');
return `Error: Query targets unauthorized tables. Allowed: {allowed}`;
}
if (policy['select_only']) {
if (!query.trim().toUpperCase().startsWith("SELECT")) {
return "Error: Policy restricts queries to SELECT statements only.";
}
}
// --- End Policy Enforcement ---
console.log(`Executing validated query (hypothetical): ${query}`);
return { "status": "success", "results": [] }; // Example successful return
}
import (
"fmt"
"strings"
"google.golang.org/adk/v2/agent"
)
func query(ctx agent.Context, args QueryArgs) (map[string]any, error) {
// Assume 'policy' is retrieved from context, e.g., via session state:
policyAny, err := ctx.Session().State().Get("query_tool_policy")
if err != nil {
return nil, fmt.Errorf("could not retrieve policy: %w", err)
}
policy, _ := policyAny.(map[string]any)
actualTables := explainQuery(args.Query) // Hypothetical function call
// --- Placeholder Policy Enforcement ---
if tables, ok := policy["tables"].([]string); ok {
if !isSubset(actualTables, tables) {
// Return an error to signal failure
allowed := strings.Join(tables, ", ")
if allowed == "" {
allowed = "(None defined)"
}
return nil, fmt.Errorf("query targets unauthorized tables. Allowed: %s", allowed)
}
}
if selectOnly, _ := policy["select_only"].(bool); selectOnly {
if !strings.HasPrefix(strings.ToUpper(strings.TrimSpace(args.Query)), "SELECT") {
return nil, fmt.Errorf("policy restricts queries to SELECT statements only")
}
}
// --- End Policy Enforcement ---
fmt.Printf("Executing validated query (hypothetical): %s\n", args.Query)
return map[string]any{"status": "success", "results": []string{"..."}}, nil
}
// Helper function to check if a is a subset of b
func isSubset(a, b []string) bool {
set := make(map[string]bool)
for _, item := range b {
set[item] = true
}
for _, item := range a {
if _, found := set[item]; !found {
return false
}
}
return true
}
import com.google.adk.tools.ToolContext;
import java.util.*;
class ToolContextQuery {
public Object query(String query, ToolContext toolContext) {
// Assume 'policy' is retrieved from context, e.g., via session state:
@SuppressWarnings("unchecked")
Map<String, Object> queryToolPolicy =
(Map<String, Object>)
toolContext.invocationContext.session().state().getOrDefault("query_tool_policy", null);
List<String> actualTables = explainQuery(query);
// --- Placeholder Policy Enforcement ---
if (!queryToolPolicy.get("tables").containsAll(actualTables)) {
List<String> allowedPolicyTables =
(List<String>) queryToolPolicy.getOrDefault("tables", new ArrayList<String>());
String allowedTablesString =
allowedPolicyTables.isEmpty() ? "(None defined)" : String.join(", ", allowedPolicyTables);
return String.format(
"Error: Query targets unauthorized tables. Allowed: %s", allowedTablesString);
}
if (!queryToolPolicy.get("select_only")) {
if (!query.trim().toUpperCase().startswith("SELECT")) {
return "Error: Policy restricts queries to SELECT statements only.";
}
}
// --- End Policy Enforcement ---
System.out.printf("Executing validated query (hypothetical) %s:", query);
Map<String, Object> successResult = new HashMap<>();
successResult.put("status", "success");
successResult.put("results", Arrays.asList("result_item1", "result_item2"));
return successResult;
}
}
内置的 Gemini 安全功能¶
Gemini 模型内置了安全机制,这些机制可以用来提升内容的安全性以及品牌保护的效果。
- 内容安全过滤器: 内容过滤器 这些工具可以帮助阻止有害内容的传播。它们独立于 Gemini 模型运行,属于多层次防御体系的一部分,用于防范那些试图破坏(或“破解”)这些模型的攻击者。Agent Platform 上的 Gemini 模型使用了两种类型的内容过滤机制:
- 不可配置的安全过滤器 自动屏蔽包含被禁止内容的输出,例如儿童性虐待材料(CSAM)和个人身份信息(PII)。
- 可配置的内容过滤器 这些功能允许您根据内容发生的概率及严重程度,为四个危害类别(仇恨言论、骚扰行为、露骨的性内容以及危险信息)设定相应的过滤阈值。这些过滤功能默认是关闭的,但您可以根据自己的需求进行配置。
from google.adk.agents import Agent
from google.genai import types
agent = Agent(
name="safety_agent",
# ...
generate_content_config=types.GenerateContentConfig(
safety_settings=[
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=types.HarmBlockThreshold.OFF,
),
],
),
)
import (
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/genai"
)
agent, _ := llmagent.New(llmagent.Config{
// ...
GenerateContentConfig: &genai.GenerateContentConfig{
SafetySettings: []*genai.SafetySetting{
{
Category: genai.HarmCategoryHateSpeech,
Threshold: genai.HarmBlockThresholdBlockLowAndAbove,
},
},
},
})
import com.google.adk.kt.agents.LlmAgent
import com.google.adk.kt.types.GenerateContentConfig
import com.google.adk.kt.types.HarmBlockThreshold
import com.google.adk.kt.types.HarmCategory
import com.google.adk.kt.types.SafetySetting
val agent =
LlmAgent(
// ...
generateContentConfig =
GenerateContentConfig(
safetySettings =
listOf(
SafetySetting(
category = HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold = HarmBlockThreshold.OFF,
),
),
),
)
- 关于安全性的系统说明: 系统说明 对于 Agent Platform 上的 Gemini 模型,系统会直接指导这些模型应该如何表现以及应该生成何种类型的内容。通过提供具体的指令,您可以主动引导模型避免生成不符合要求的内容,从而满足您组织的特定需求。您可以制定系统指令来定义内容安全规范(例如禁止或敏感的主题、免责声明等),以及品牌安全规范,以确保模型的输出与您的品牌形象、语气、价值观和目标受众保持一致。
虽然这些措施在保障内容安全方面非常有效,但您仍需要额外的检查机制,以减少代理程序的错误操作、不安全行为以及品牌安全风险。
用于安全防护机制的回调函数(Callbacks)和插件(Plugins)¶
回调(Callbacks)提供了一种简单的方法,用于为工具和模型的输入/输出操作添加预验证功能(这些功能是特定于某个代理/系统的);而插件(Plugins)则提供了一种可重用的解决方案,可用于在多个代理/系统中实施通用的安全策略。
当无法对工具进行修改以添加相应的安全防护机制(即“护栏”)时, Before Tool Callback 可以使用 `can` 函数来为调用过程添加预验证机制。回调函数可以访问代理的状态、所请求的工具以及相关参数。这种方法非常通用,甚至可以用来创建一个可重用的工具策略库。然而,如果用于执行验证规则的信息并未直接显示在参数中,那么这种方法可能并不适用于所有工具。
# Hypothetical callback function
def validate_tool_params(
tool: BaseTool,
args: Dict[str, Any],
tool_context: ToolContext
) -> Optional[Dict]: # Correct return type for before_tool_callback
print(f"Callback triggered for tool: {tool.name}, args: {args}")
# Example validation: Check if a required user ID from state matches an arg
expected_user_id = tool_context.state.get("session_user_id")
actual_user_id_in_args = args.get("user_id_param") # Assuming tool takes 'user_id_param'
if actual_user_id_in_args != expected_user_id:
print("Validation Failed: User ID mismatch!")
# Return a dictionary to prevent tool execution and provide feedback
return {"error": f"Tool call blocked: User ID mismatch."}
# Return None to allow the tool call to proceed if validation passes
print("Callback validation passed.")
return None
# Hypothetical Agent setup
root_agent = LlmAgent( # Use specific agent type
model='gemini-flash-latest',
name='root_agent',
instruction="...",
before_tool_callback=validate_tool_params, # Assign the callback
tools = [
# ... list of tool functions or Tool instances ...
# e.g., query_tool_instance
]
)
// Hypothetical callback function
function validateToolParams(
{tool, args, context}: {
tool: BaseTool,
args: {[key: string]: any},
context: Context
}
): {[key: string]: any} | undefined {
console.log(`Callback triggered for tool: ${tool.name}, args: ${JSON.stringify(args)}`);
// Example validation: Check if a required user ID from state matches an arg
const expectedUserId = context.state.get("session_user_id");
const actualUserIdInArgs = args["user_id_param"]; // Assuming tool takes 'user_id_param'
if (actualUserIdInArgs !== expectedUserId) {
console.log("Validation Failed: User ID mismatch!");
// Return a dictionary to prevent tool execution and provide feedback
return {"error": `Tool call blocked: User ID mismatch.`};
}
// Return undefined to allow the tool call to proceed if validation passes
console.log("Callback validation passed.");
return undefined;
}
// Hypothetical Agent setup
const rootAgent = new LlmAgent({
model: 'gemini-flash-latest',
name: 'root_agent',
instruction: "...",
beforeToolCallback: validateToolParams, // Assign the callback
tools: [
// ... list of tool functions or Tool instances ...
// e.g., queryToolInstance
]
});
import (
"fmt"
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/tool"
)
// Hypothetical callback function
func validateToolParams(
ctx agent.Context,
t tool.Tool,
args map[string]any,
) (map[string]any, error) {
fmt.Printf("Callback triggered for tool: %s, args: %v\n", t.Name(), args)
// Example validation: Check if a required user ID from state matches an arg
expectedUserIDVal, err := ctx.Session().State().Get("session_user_id")
if err != nil {
// Return a map to prevent tool execution and provide feedback to the model.
return map[string]any{"error": "Tool call blocked: User ID not found."}, nil
}
expectedUserID, _ := expectedUserIDVal.(string)
actualUserID, ok := args["user_id_param"].(string)
if !ok || actualUserID != expectedUserID {
fmt.Println("Validation Failed: User ID mismatch!")
return map[string]any{"error": "Tool call blocked: User ID mismatch."}, nil
}
// Return nil, nil to allow the tool call to proceed if validation passes
fmt.Println("Callback validation passed.")
return nil, nil
}
// Hypothetical Agent setup
// agent, _ := llmagent.New(llmagent.Config{
// Model: "gemini-flash-latest",
// Name: "root_agent",
// Instruction: "...",
// BeforeToolCallbacks: []llmagent.BeforeToolCallback{validateToolParams},
// Tools: []tool.Tool{queryToolInstance},
// Hypothetical callback function
public Optional<Map<String, Object>> validateToolParams(
CallbackContext callbackContext,
Tool baseTool,
Map<String, Object> input,
ToolContext toolContext) {
System.out.printf("Callback triggered for tool: %s, Args: %s", baseTool.name(), input);
// Example validation: Check if a required user ID from state matches an input parameter
Object expectedUserId = callbackContext.state().get("session_user_id");
Object actualUserIdInput = input.get("user_id_param"); // Assuming tool takes 'user_id_param'
if (!actualUserIdInput.equals(expectedUserId)) {
System.out.println("Validation Failed: User ID mismatch!");
// Return to prevent tool execution and provide feedback
return Optional.of(Map.of("error", "Tool call blocked: User ID mismatch."));
}
// Return to allow the tool call to proceed if validation passes
System.out.println("Callback validation passed.");
return Optional.empty();
}
// Hypothetical Agent setup
public void runAgent() {
LlmAgent agent =
LlmAgent.builder()
.model("gemini-flash-latest")
.name("AgentWithBeforeToolCallback")
.instruction("...")
.beforeToolCallback(this::validateToolParams) // Assign the callback
.tools(anyToolToUse) // Define the tool to be used
.build();
}
然而,在为代理应用程序添加安全防护机制时,推荐使用插件来实现那些不针对特定代理的应用策略。插件被设计为独立且模块化的组件,因此你可以为不同的安全策略创建相应的插件,并在运行器(runner)层面全局应用这些插件。这样一来,一个安全插件只需配置一次,就可以被所有使用该运行器的代理所使用,从而在整个应用程序中实现一致的安全防护机制,而无需编写重复的代码。
一些示例包括:
-
“Gemini”作为裁判插件(Gemini as a Judge Plugin)该插件使用 Gemini Flash Lite 来评估用户输入、工具输入及输出结果,以及代理程序的响应内容,以判断这些内容是否安全、是否适合用于提示的生成(如“提示注入”操作),以及是否属于非法操作(如“越狱”行为)。该插件将用户输入、工具输入及输出结果以及模型生成的输出数据传递给 Gemini Flash Lite,由后者判断这些数据是否适合被代理程序处理。如果 Gemini 认为某些数据不安全,代理程序会返回一个预设的响应:“很抱歉,我无法为您提供帮助。请问还有其他我可以为您效劳的吗?”
-
Model Armor 插件这是一个随 ADK 一起提供的插件,它会调用 Model Armor API,在代理程序执行的特定阶段检查是否存在潜在的内容安全违规行为。其功能类似于…… 双子座作为裁判 如果 Model Armor 发现有害内容,它会向用户返回一个预先设定好的响应。
-
PII(个人身份信息)脱敏插件:这是一个专为……设计的专用插件。 在工具回调函数执行之前 该工具是专门为在数据被工具处理或发送到外部服务之前删除其中包含的个人身份信息而设计的。
沙箱环境中的代码执行(Sandboxed Code Execution)¶
代码执行是一种具有特殊性质的工具,它带来了额外的安全风险:必须使用“沙箱环境”(sandboxing(隔离机制)来防止模型生成的代码破坏本地环境,从而避免潜在的安全问题。
Google 和 ADK 提供了多种选项,以确保代码的安全执行。 Vertex Gemini Enterprise API 的代码执行功能 该功能通过启用 `tool_execution` 工具,使代理能够在服务器端利用沙箱环境中的代码执行机制。对于需要执行数据分析操作的代码,您可以使用该功能。 代码执行器(Code Executor) 在 ADK 中使用相应的工具来调用该功能。 “Vertex Code Interpreter Extension”(顶点代码解释器扩展).
如果这些选项都无法满足您的需求,您可以使用 Android 开发工具包(ADK)提供的组件来自行开发代码执行器。我们建议创建“封闭式”的执行环境:禁止任何网络连接和 API 调用,以防止数据被未经控制地泄露;同时在执行过程中彻底清除所有数据,以避免数据在用户之间被共享或泄露。
评估(Evaluations)¶
请参阅: 评估代理(Agents)的性能.
VPC-SC:边界防护与网络控制¶
如果您将您的代理程序部署到 VPC-SC 环境内,那么就可以确保所有的 API 调用仅针对该环境内的资源进行操作,从而降低数据泄露的风险。
然而,身份识别和权限设置仅能对代理的行为提供粗略的控制。工具使用方面的限制措施(即“护栏”)可以缓解这些局限性,使代理开发者能够更精细地控制哪些行为是被允许的。
其他安全风险¶
在用户界面(UI)中,始终要避免使用模型生成的内容。¶
在浏览器中显示代理程序的输出时必须格外小心:如果用户界面(UI)中的 HTML 或 JS 内容没有得到正确的转义处理,模型返回的文本可能会被浏览器执行,从而导致数据泄露。例如,通过间接的方式注入代码(如提示用户输入某些内容),可以迫使模型在生成的文本中包含 `<img>` 标签;这样浏览器就会将这些内容发送到第三方网站;或者生成一些 URL,点击这些 URL 会使得数据被发送到外部网站。因此,必须对这类内容进行正确的转义处理,以确保模型生成的文本不会被浏览器解释为可执行的代码。