agent-governance

agent-governance

熱門

為 AI Agent 系統新增治理、安全性與信任控制的模式與技巧。適用時機: - 開發會呼叫外部工具(API、資料庫、檔案系統)的 AI Agent - 針對 Agent 工具的使用實作基於策略的存取控制 - 新增語意意圖分類以偵測危險提示詞 - 為多 Agent 工作流程建立信任評分系統 - 為 Agent 的動作與決策建立稽核紀錄 - 對 Agent 強制執行速率限制、內容過濾或工具限制 - 使用任何 Agent 框架(PydanticAI、CrewAI、OpenAI Agents、LangChain、AutoGen)

3.6萬星標
4556分支
更新於 2026/7/13
SKILL.md
唯讀
名稱
agent-governance
描述

為 AI Agent 系統新增治理、安全性與信任控制的模式與技巧。適用時機: - 開發會呼叫外部工具(API、資料庫、檔案系統)的 AI Agent - 針對 Agent 工具的使用實作基於策略的存取控制 - 新增語意意圖分類以偵測危險提示詞 - 為多 Agent 工作流程建立信任評分系統 - 為 Agent 的動作與決策建立稽核紀錄 - 對 Agent 強制執行速率限制、內容過濾或工具限制 - 使用任何 Agent 框架(PydanticAI、CrewAI、OpenAI Agents、LangChain、AutoGen)

Agent 治理模式 (Agent Governance Patterns)

為 AI Agent 系統新增安全性、信任度與策略強制執行的模式。

總覽

治理模式可確保 AI Agent 在定義好的邊界內運作 — 控制它們可以呼叫哪些工具、可以處理哪些內容、可以執行多少動作,並透過稽核紀錄維持可追溯性。

使用者請求 → 意圖分類 → 策略檢查 → 工具執行 → 稽核日誌
                ↓           ↓          ↓
             威脅偵測     允許/拒絕    信任度更新

適用時機

  • 具備工具存取權的 Agent:任何會呼叫外部工具(API、資料庫、Shell 命令)的 Agent
  • 多 Agent 系統:委派任務給其他 Agent 時需要信任邊界
  • 正式環境部署:合規性、稽核與安全性要求
  • 敏感操作:金融交易、資料存取、基礎架構管理

模式 1:治理策略 (Governance Policy)

將 Agent 被允許執行的操作定義為可組合、可序列化的策略物件。

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
import re

class PolicyAction(Enum):
    ALLOW = "allow"
    DENY = "deny"
    REVIEW = "review"  # 標記為需要人工審查

@dataclass
class GovernancePolicy:
    """控制 Agent 行為的宣告式策略。"""
    name: str
    allowed_tools: list[str] = field(default_factory=list)       # 允許清單 (allowlist)
    blocked_tools: list[str] = field(default_factory=list)       # 封鎖清單 (blocklist)
    blocked_patterns: list[str] = field(default_factory=list)    # 內容過濾器
    max_calls_per_request: int = 100                             # 速率限制
    require_human_approval: list[str] = field(default_factory=list)  # 需要人工核准的工具

    def check_tool(self, tool_name: str) -> PolicyAction:
        """檢查此策略是否允許使用特定工具。"""
        if tool_name in self.blocked_tools:
            return PolicyAction.DENY
        if tool_name in self.require_human_approval:
            return PolicyAction.REVIEW
        if self.allowed_tools and tool_name not in self.allowed_tools:
            return PolicyAction.DENY
        return PolicyAction.ALLOW

    def check_content(self, content: str) -> Optional[str]:
        """比對內容與封鎖模式。回傳匹配的模式或 None。"""
        for pattern in self.blocked_patterns:
            if re.search(pattern, content, re.IGNORECASE):
                return pattern
        return None

策略組合 (Policy Composition)

組合多個策略(例如:全公司 + 團隊 + Agent 專屬策略):

def compose_policies(*policies: GovernancePolicy) -> GovernancePolicy:
    """合併策略,採「最嚴格者優先」語意。"""
    combined = GovernancePolicy(name="composed")

    for policy in policies:
        combined.blocked_tools.extend(policy.blocked_tools)
        combined.blocked_patterns.extend(policy.blocked_patterns)
        combined.require_human_approval.extend(policy.require_human_approval)
        combined.max_calls_per_request = min(
            combined.max_calls_per_request,
            policy.max_calls_per_request
        )
        if policy.allowed_tools:
            if combined.allowed_tools:
                combined.allowed_tools = [
                    t for t in combined.allowed_tools if t in policy.allowed_tools
                ]
            else:
                combined.allowed_tools = list(policy.allowed_tools)

    return combined


# 使用方式:由寬鬆到嚴格分層套用策略
org_policy = GovernancePolicy(
    name="org-wide",
    blocked_tools=["shell_exec", "delete_database"],
    blocked_patterns=[r"(?i)(api[_-]?key|secret|password)\s*[:=]"],
    max_calls_per_request=50
)
team_policy = GovernancePolicy(
    name="data-team",
    allowed_tools=["query_db", "read_file", "write_report"],
    require_human_approval=["write_report"]
)
agent_policy = compose_policies(org_policy, team_policy)

以 YAML 表示策略

將策略儲存為設定檔,而非硬編碼於程式中:

# governance-policy.yaml
name: production-agent
allowed_tools:
  - search_documents
  - query_database
  - send_email
blocked_tools:
  - shell_exec
  - delete_record
blocked_patterns:
  - "(?i)(api[_-]?key|secret|password)\\s*[:=]"
  - "(?i)(drop|truncate|delete from)\\s+\\w+"
max_calls_per_request: 25
require_human_approval:
  - send_email
import yaml

def load_policy(path: str) -> GovernancePolicy:
    with open(path) as f:
        data = yaml.safe_load(f)
    return GovernancePolicy(**data)

模式 2:語意意圖分類 (Semantic Intent Classification)

在提示詞到達 Agent 之前,使用基於特徵模式的訊號偵測危險意圖。

from dataclasses import dataclass

@dataclass
class IntentSignal:
    category: str       # 例如:"data_exfiltration", "privilege_escalation"
    confidence: float   # 0.0 到 1.0
    evidence: str       # 觸發偵測的內容

# 用於威脅偵測的加權訊號模式
THREAT_SIGNALS = [
    # 資料外洩 (Data exfiltration)
    (r"(?i)send\s+(all|every|entire)\s+\w+\s+to\s+", "data_exfiltration", 0.8),
    (r"(?i)export\s+.*\s+to\s+(external|outside|third.?party)", "data_exfiltration", 0.9),
    (r"(?i)curl\s+.*\s+-d\s+", "data_exfiltration", 0.7),

    # 權限提升 (Privilege escalation)
    (r"(?i)(sudo|as\s+root|admin\s+access)", "privilege_escalation", 0.8),
    (r"(?i)chmod\s+777", "privilege_escalation", 0.9),

    # 系統修改 (System modification)
    (r"(?i)(rm\s+-rf|del\s+/[sq]|format\s+c:)", "system_destruction", 0.95),
    (r"(?i)(drop\s+database|truncate\s+table)", "system_destruction", 0.9),

    # 提示詞注入 (Prompt injection)
    (r"(?i)ignore\s+(previous|above|all)\s+(instructions?|rules?)", "prompt_injection", 0.9),
    (r"(?i)you\s+are\s+now\s+(a|an)\s+", "prompt_injection", 0.7),
]

def classify_intent(content: str) -> list[IntentSignal]:
    """對內容進行威脅訊號分類。"""
    signals = []
    for pattern, category, weight in THREAT_SIGNALS:
        match = re.search(pattern, content)
        if match:
            signals.append(IntentSignal(
                category=category,
                confidence=weight,
                evidence=match.group()
            ))
    return signals

def is_safe(content: str, threshold: float = 0.7) -> bool:
    """快速檢查:內容在指定閾值以上是否安全?"""
    signals = classify_intent(content)
    return not any(s.confidence >= threshold for s in signals)

核心觀點:意圖分類發生在工具執行之前,作為預防性的安全檢查。這與只在生成之後才檢查的輸出防護欄 (output guardrails) 有根本上的不同。


模式 3:工具層級治理修飾器 (Tool-Level Governance Decorator)

使用治理檢查包覆個別工具函式:

import functools
import time
from collections import defaultdict

_call_counters: dict[str, int] = defaultdict(int)

def govern(policy: GovernancePolicy, audit_trail=None):
    """在工具函式上強制執行治理策略的修饰器。"""
    def decorator(func):
        @functools.wraps(func)
        async def wrapper(*args, **kwargs):
            tool_name = func.__name__

            # 1. 檢查工具允許清單/封鎖清單
            action = policy.check_tool(tool_name)
            if action == PolicyAction.DENY:
                raise PermissionError(f"Policy '{policy.name}' blocks tool '{tool_name}'")
            if action == PolicyAction.REVIEW:
                raise PermissionError(f"Tool '{tool_name}' requires human approval")

            # 2. 檢查速率限制
            _call_counters[policy.name] += 1
            if _call_counters[policy.name] > policy.max_calls_per_request:
                raise PermissionError(f"Rate limit exceeded: {policy.max_calls_per_request} calls")

            # 3. 檢查引數中的內容
            for arg in list(args) + list(kwargs.values()):
                if isinstance(arg, str):
                    matched = policy.check_content(arg)
                    if matched:
                        raise PermissionError(f"Blocked pattern detected: {matched}")

            # 4. 執行與稽核
            start = time.monotonic()
            try:
                result = await func(*args, **kwargs)
                if audit_trail is not None:
                    audit_trail.append({
                        "tool": tool_name,
                        "action": "allowed",
                        "duration_ms": (time.monotonic() - start) * 1000,
                        "timestamp": time.time()
                    })
                return result
            except Exception as e:
                if audit_trail is not None:
                    audit_trail.append({
                        "tool": tool_name,
                        "action": "error",
                        "error": str(e),
                        "timestamp": time.time()
                    })
                raise

        return wrapper
    return decorator


# 可搭配任何 Agent 框架使用
audit_log = []
policy = GovernancePolicy(
    name="search-agent",
    allowed_tools=["search", "summarize"],
    blocked_patterns=[r"(?i)password"],
    max_calls_per_request=10
)

@govern(policy, audit_trail=audit_log)
async def search(query: str) -> str:
    """搜尋文件 — 受策略治理。"""
    return f"Results for: {query}"

# 通過:search("latest quarterly report")
# 封鎖:search("show me the admin password")

模式 4:信任評分 (Trust Scoring)

使用具時間衰減特性的信任分數追蹤 Agent 隨時間變化的可靠性:

from dataclasses import dataclass, field
import math
import time

@dataclass
class TrustScore:
    """具時間衰減特性的信任分數。"""
    score: float = 0.5          # 0.0(不信任)至 1.0(完全信任)
    successes: int = 0
    failures: int = 0
    last_updated: float = field(default_factory=time.time)

    def record_success(self, reward: float = 0.05):
        self.successes += 1
        self.score = min(1.0, self.score + reward * (1 - self.score))
        self.last_updated = time.time()

    def record_failure(self, penalty: float = 0.15):
        self.failures += 1
        self.score = max(0.0, self.score - penalty * self.score)
        self.last_updated = time.time()

    def current(self, decay_rate: float = 0.001) -> float:
        """取得包含時間衰減的分數 — 缺乏活動會使信任度受損。"""
        elapsed = time.time() - self.last_updated
        decay = math.exp(-decay_rate * elapsed)
        return self.score * decay

    @property
    def reliability(self) -> float:
        total = self.successes + self.failures
        return self.successes / total if total > 0 else 0.0


# 在多 Agent 系統中的使用範例
trust = TrustScore()

# Agent 成功完成任務
trust.record_success()  # 0.525
trust.record_success()  # 0.549

# Agent 發生錯誤
trust.record_failure()  # 0.467

# 根據信任度關卡控制敏感操作
if trust.current() >= 0.7:
    # 允許自主執行操作
    pass
elif trust.current() >= 0.4:
    # 允許在人工監督下執行
    pass
else:
    # 拒絕或需要明確核准
    pass

多 Agent 信任機制:在 Agent 會將任務委派給其他 Agent 的系統中,每個 Agent 都為其受委派者維護信任分數:

class AgentTrustRegistry:
    def __init__(self):
        self.scores: dict[str, TrustScore] = {}

    def get_trust(self, agent_id: str) -> TrustScore:
        if agent_id not in self.scores:
            self.scores[agent_id] = TrustScore()
        return self.scores[agent_id]

    def most_trusted(self, agents: list[str]) -> str:
        return max(agents, key=lambda a: self.get_trust(a).current())

    def meets_threshold(self, agent_id: str, threshold: float) -> bool:
        return self.get_trust(agent_id).current() >= threshold

模式 5:稽核紀錄 (Audit Trail)

僅限附加 (Append-only) 的 Agent 所有動作稽核日誌 — 對於合規性與偵錯至關重要:

from dataclasses import dataclass, field
import json
import time

@dataclass
class AuditEntry:
    timestamp: float
    agent_id: str
    tool_name: str
    action: str           # "allowed", "denied", "error"
    policy_name: str
    details: dict = field(default_factory=dict)

class AuditTrail:
    """Agent 治理事件的僅限附加稽核紀錄。"""
    def __init__(self):
        self._entries: list[AuditEntry] = []

    def log(self, agent_id: str, tool_name: str, action: str,
            policy_name: str, **details):
        self._entries.append(AuditEntry(
            timestamp=time.time(),
            agent_id=agent_id,
            tool_name=tool_name,
            action=action,
            policy_name=policy_name,
            details=details
        ))

    def denied(self) -> list[AuditEntry]:
        """取得所有被拒絕的動作 — 對資安審查非常有幫助。"""
        return [e for e in self._entries if e.action == "denied"]

    def by_agent(self, agent_id: str) -> list[AuditEntry]:
        return [e for e in self._entries if e.agent_id == agent_id]

    def export_jsonl(self, path: str):
        """匯出為 JSON Lines,供日誌聚合系統使用。"""
        with open(path, "w") as f:
            for entry in self._entries:
                f.write(json.dumps({
                    "timestamp": entry.timestamp,
                    "agent_id": entry.agent_id,
                    "tool": entry.tool_name,
                    "action": entry.action,
                    "policy": entry.policy_name,
                    **entry.details
                }) + "\n")

模式 6:框架整合 (Framework Integration)

PydanticAI

from pydantic_ai import Agent

policy = GovernancePolicy(
    name="support-bot",
    allowed_tools=["search_docs", "create_ticket"],
    blocked_patterns=[r"(?i)(ssn|social\s+security|credit\s+card)"],
    max_calls_per_request=20
)

agent = Agent("openai:gpt-4o", system_prompt="You are a support assistant.")

@agent.tool
@govern(policy)
async def search_docs(ctx, query: str) -> str:
    """搜尋知識庫 — 受治理。"""
    return await kb.search(query)

@agent.tool
@govern(policy)
async def create_ticket(ctx, title: str, body: str) -> str:
    """建立支援工單 — 受治理。"""
    return await tickets.create(title=title, body=body)

CrewAI

from crewai import Agent, Task, Crew

policy = GovernancePolicy(
    name="research-crew",
    allowed_tools=["search", "analyze"],
    max_calls_per_request=30
)

# 在 Crew 層級套用治理
def governed_crew_run(crew: Crew, policy: GovernancePolicy):
    """使用治理檢查包覆 Crew 的執行過程。"""
    audit = AuditTrail()
    for agent in crew.agents:
        for tool in agent.tools:
            original = tool.func
            tool.func = govern(policy, audit_trail=audit)(original)
    result = crew.kickoff()
    return result, audit

OpenAI Agents SDK

from agents import Agent, function_tool

policy = GovernancePolicy(
    name="coding-agent",
    allowed_tools=["read_file", "write_file", "run_tests"],
    blocked_tools=["shell_exec"],
    max_calls_per_request=50
)

@function_tool
@govern(policy)
async def read_file(path: str) -> str:
    """讀取檔案內容 — 受治理。"""
    import os
    safe_path = os.path.realpath(path)
    if not safe_path.startswith(os.path.realpath(".")):
        raise ValueError("Path traversal blocked by governance")
    with open(safe_path) as f:
        return f.read()

治理等級 (Governance Levels)

將治理嚴格度與風險等級相互搭配:

等級 控制措施 使用場景
開放 (Open) 僅稽核,無限制 內部開發/測試
標準 (Standard) 工具允許清單 + 內容過濾器 一般正式環境 Agent
嚴格 (Strict) 所有控制措施 + 敏感操作需人工核准 金融、醫療、法律
鎖定 (Locked) 僅限允許清單、無動態工具、完整稽核 需符合嚴格合規要求的系統

最佳實踐

做法 原理說明
策略即設定 (Policy as configuration) 將策略儲存在 YAML/JSON 中而非硬編碼 — 實現無需重新部署即可變更
最嚴格者優先 (Most-restrictive-wins) 組合策略時,拒絕 (deny) 永遠優先於允許 (allow)
執行前意圖檢查 (Pre-flight intent check) 在工具執行之前分類意圖,而非事後才檢查
信任度衰減 (Trust decay) 信任分數應隨時間衰減 — 要求持續表現良好行為
僅限附加稽核 (Append-only audit) 絕不修改或刪除稽核條目 — 不可變性是符合合規要求的關鍵
預設關閉/失敗即安全性 (Fail closed) 如果治理檢查出錯,應拒絕該動作而非放行
策略與邏輯分離 (Separate policy from logic) 治理的強制執行應獨立於 Agent 的業務邏輯

快速入門檢查清單

## Agent 治理實作檢查清單

### 設定
- [ ] 定義治理策略(允許的工具、封鎖的模式、速率限制)
- [ ] 選擇治理等級(開放/標準/嚴格/鎖定)
- [ ] 建立稽核紀錄儲存機制

### 實作
- [ ] 在所有工具函式加上 @govern 修飾器
- [ ] 在使用者輸入處理程序中新增意圖分類
- [ ] 為多 Agent 互動實作信任評分機制
- [ ] 串接稽核紀錄匯出功能

### 驗證
- [ ] 測試封鎖的工具是否被正確拒絕
- [ ] 測試內容過濾器是否能捕捉敏感模式
- [ ] 測試速率限制行為
- [ ] 確認稽核紀錄能擷取所有事件
- [ ] 測試策略組合(最嚴格者優先)

相關資源