Microsoft.Agents.AI.LocalCodeAct 會在代理程式環境中的子程序內執行產生的 Python 程式碼。 它提供 CodeAct 提供者模式,且不需 Hyperlight 訪客執行時。
此整合採用 CodeAct 模式,並依賴主機環境進行隔離。
Warning
Local CodeAct 不是安全沙盒。 僅在外部容器、虛擬機或受管理主機環境提供程序、檔案系統、網路及憑證隔離的地方執行。
安裝套件
dotnet add package Microsoft.Agents.AI.LocalCodeAct --prerelease
該套件需要明確的 Python 執行檔路徑。
設定供應商
透過 LocalCodeActProviderOptions註冊主機工具。 產生的程式碼只能透過 await call_tool(...) 呼叫這些工具。 對綁定的子程序執行時及擷取輸出施加執行限制。
new Dictionary<string, object> { ["id"] = 3, ["name"] = "Charlie", ["role"] = "admin" },
],
["products"] =
[
new Dictionary<string, object> { ["id"] = 101, ["name"] = "Widget", ["price"] = 9.99 },
new Dictionary<string, object> { ["id"] = 102, ["name"] = "Gadget", ["price"] = 19.99 },
],
};
return data.TryGetValue(table, out var rows) ? rows : [];
}
// ── LocalCodeAct provider with sandbox-only host tools ───────────────────────
var codeActOptions = new LocalCodeActProviderOptions
{
Tools =
[
AIFunctionFactory.Create(Compute, name: "compute"),
AIFunctionFactory.Create(FetchData, name: "fetch_data"),
],
ExecutionLimits = new ProcessExecutionLimits { TimeoutSeconds = 5 },
};
var codeAct = new LocalCodeActProvider(pythonExecutable, codeActOptions);
// ── Build the hosted agent ───────────────────────────────────────────────────
// WARNING: DefaultAzureCredential is convenient for development but requires careful
// consideration in production. Consider a specific credential (for example
// ManagedIdentityCredential) to avoid latency, unintended credential probing, and
// fallback security risks.
AIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
縱深防禦控制
地方法典規定:
- 可設定允許與封鎖之匯入和內建項目的 AST 驗證。
- 直接執行 Python 子程序,無需呼叫 shell。
- 時間、輸出、結果及擷取檔案大小限制。
- 明確的主機-工具註冊。
- 唯讀與讀寫檔案掛載。
- 可配置的工作目錄與子程序環境。
這些控制措施降低風險,但無法提供遏制。 保持啟用驗證,傳入受限的環境字典,僅暴露有限的主機端工具,並在強健的外部沙盒中執行該程序。
選擇 CodeAct 執行階段
| Runtime | 當…時,選擇它 |
|---|---|
| 超光速 | 你需要一個獨立的沙盒,並有檔案系統和網路控制。 |
| Local CodeAct | 你的 .NET 代理程式已經運行在外部沙盒環境中。 |
| 蒙提 | 你需要一個跨平台的限制直譯器來處理 Python 代理。 |