Skip to content

Commit 7797f00

Browse files
feat: add 5 standalone one-file runnable framework quickstarts
* Initial plan * feat: add 5 standalone one-file runnable framework quickstarts Co-authored-by: imran-siddique <45405841+imran-siddique@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: imran-siddique <45405841+imran-siddique@users.noreply.github.com>
1 parent 858228e commit 7797f00

File tree

5 files changed

+391
-0
lines changed

5 files changed

+391
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
"""
4+
AutoGen Agents with Trust Verification — Quickstart
5+
====================================================
6+
7+
pip install ai-agent-compliance[full] pyautogen
8+
python examples/quickstart/autogen_governed.py
9+
10+
Shows a real policy violation being caught during message routing,
11+
then a safe message passing verification, with a printed audit trail.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import sys
17+
from datetime import datetime
18+
from pathlib import Path
19+
20+
_REPO_ROOT = Path(__file__).resolve().parent.parent.parent
21+
sys.path.insert(0, str(_REPO_ROOT / "packages" / "agent-os" / "src"))
22+
23+
from agent_os.integrations import AutoGenKernel
24+
from agent_os.integrations.base import GovernancePolicy, PolicyViolationError
25+
26+
# ── 1. Define a governance policy ─────────────────────────────────────────
27+
policy = GovernancePolicy(
28+
name="autogen-demo-policy",
29+
blocked_patterns=["api_key=", "password="], # block credential leaks
30+
max_tool_calls=5,
31+
)
32+
33+
kernel = AutoGenKernel(policy=policy)
34+
ctx = kernel.create_context("autogen-assistant")
35+
audit: list[dict] = []
36+
37+
print("=" * 60)
38+
print(" AutoGen Agents — Governance Quickstart")
39+
print("=" * 60)
40+
41+
# ── 2. Policy violation: credential leak in message ───────────────────────
42+
print("\n[1] Agent message containing a credential leak …")
43+
msg = {"role": "assistant", "content": "Here is your token: api_key=sk-abc123"}
44+
allowed, reason = kernel.pre_execute(ctx, msg)
45+
if not allowed:
46+
print(f" 🚫 BLOCKED — {reason}")
47+
audit.append({"ts": datetime.now().isoformat(), "msg": "api_key leak", "status": "BLOCKED"})
48+
49+
# ── 3. Policy violation: call budget exhausted ────────────────────────────
50+
print("\n[2] Agent conversation budget exhausted …")
51+
ctx.call_count = policy.max_tool_calls
52+
allowed, reason = kernel.pre_execute(ctx, {"role": "assistant", "content": "Let me help."})
53+
if not allowed:
54+
print(f" 🚫 BLOCKED — {reason}")
55+
audit.append({"ts": datetime.now().isoformat(), "msg": "budget exceeded", "status": "BLOCKED"})
56+
ctx.call_count = 0
57+
58+
# ── 4. Compliant message passes ───────────────────────────────────────────
59+
print("\n[3] Safe agent message passes trust verification …")
60+
msg = {"role": "assistant", "content": "Here is a summary of the quarterly report."}
61+
allowed, reason = kernel.pre_execute(ctx, msg)
62+
if allowed:
63+
print(" ✅ ALLOWED — trust verification passed")
64+
audit.append({"ts": datetime.now().isoformat(), "msg": "quarterly summary", "status": "ALLOWED"})
65+
66+
# ── 5. Health check ───────────────────────────────────────────────────────
67+
health = kernel.health_check()
68+
print(f"\n[4] Kernel health: status={health['status']!r}, "
69+
f"backend={health['backend']!r}")
70+
71+
# ── 6. Audit trail ────────────────────────────────────────────────────────
72+
print("\n── Audit Trail ──────────────────────────────────────────")
73+
for i, entry in enumerate(audit, 1):
74+
print(f" [{i}] {entry['ts']} msg={entry['msg']!r} status={entry['status']}")
75+
76+
print("\n🎉 AutoGen governance demo complete.")
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
"""
4+
CrewAI Crew with Governance Middleware — Quickstart
5+
====================================================
6+
7+
pip install ai-agent-compliance[full] crewai
8+
python examples/quickstart/crewai_governed.py
9+
10+
Shows a real policy violation being caught, then a compliant run succeeding,
11+
with a printed audit trail.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import sys
17+
from datetime import datetime
18+
from pathlib import Path
19+
20+
_REPO_ROOT = Path(__file__).resolve().parent.parent.parent
21+
sys.path.insert(0, str(_REPO_ROOT / "packages" / "agent-os" / "src"))
22+
23+
from agent_os.integrations import CrewAIKernel
24+
from agent_os.integrations.base import GovernancePolicy, PolicyViolationError
25+
26+
# ── 1. Define a governance policy ─────────────────────────────────────────
27+
policy = GovernancePolicy(
28+
name="crewai-demo-policy",
29+
blocked_patterns=["DROP TABLE", "rm -rf"], # dangerous SQL/shell commands
30+
max_tool_calls=3,
31+
require_human_approval=False,
32+
)
33+
34+
kernel = CrewAIKernel(policy=policy)
35+
ctx = kernel.create_context("crewai-demo-crew")
36+
audit: list[dict] = []
37+
38+
print("=" * 60)
39+
print(" CrewAI Crew — Governance Quickstart")
40+
print("=" * 60)
41+
42+
# ── 2. Policy violation: blocked content pattern ───────────────────────────
43+
print("\n[1] Crew task with a dangerous SQL injection pattern …")
44+
allowed, reason = kernel.pre_execute(ctx, "Execute: DROP TABLE users")
45+
if not allowed:
46+
print(f" 🚫 BLOCKED — {reason}")
47+
audit.append({"ts": datetime.now().isoformat(), "task": "DROP TABLE users", "status": "BLOCKED"})
48+
49+
# ── 3. Policy violation: call budget exhausted ────────────────────────────
50+
print("\n[2] Exhausting the call budget …")
51+
ctx.call_count = policy.max_tool_calls # simulate budget consumed
52+
allowed, reason = kernel.pre_execute(ctx, "Summarise quarterly reports")
53+
if not allowed:
54+
print(f" 🚫 BLOCKED — {reason}")
55+
audit.append({"ts": datetime.now().isoformat(), "task": "summarise reports", "status": "BLOCKED"})
56+
ctx.call_count = 0 # reset for next check
57+
58+
# ── 4. Compliant task succeeds ────────────────────────────────────────────
59+
print("\n[3] Safe crew task passes policy check …")
60+
allowed, reason = kernel.pre_execute(ctx, "Summarise the quarterly financial reports")
61+
if allowed:
62+
print(" ✅ ALLOWED — policy check passed")
63+
audit.append({"ts": datetime.now().isoformat(), "task": "summarise reports", "status": "ALLOWED"})
64+
65+
# ── 5. Audit trail ────────────────────────────────────────────────────────
66+
print("\n── Audit Trail ──────────────────────────────────────────")
67+
for i, entry in enumerate(audit, 1):
68+
print(f" [{i}] {entry['ts']} task={entry['task']!r} status={entry['status']}")
69+
70+
print("\n🎉 CrewAI governance demo complete.")
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
"""
4+
Google ADK Agent with Policy Gates — Quickstart
5+
================================================
6+
7+
pip install ai-agent-compliance[full] google-adk
8+
python examples/quickstart/google_adk_governed.py
9+
10+
Shows real policy violations being caught by ADK governance callbacks,
11+
then a compliant call succeeding, with a printed audit trail.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import sys
17+
from pathlib import Path
18+
19+
_REPO_ROOT = Path(__file__).resolve().parent.parent.parent
20+
sys.path.insert(0, str(_REPO_ROOT / "packages" / "agent-os" / "src"))
21+
22+
from agent_os.integrations.google_adk_adapter import GoogleADKKernel
23+
24+
# ── 1. Define a governance policy ─────────────────────────────────────────
25+
kernel = GoogleADKKernel(
26+
max_tool_calls=10,
27+
allowed_tools=["search", "summarize"], # explicit allowlist
28+
blocked_tools=["exec_code", "shell"], # explicit blocklist
29+
blocked_patterns=["DROP TABLE", "rm -rf"], # ban dangerous strings
30+
max_budget=5.0, # cost cap per session
31+
on_violation=lambda _e: None, # collect silently; printed below
32+
)
33+
34+
print("=" * 60)
35+
print(" Google ADK Agent — Governance Quickstart")
36+
print("=" * 60)
37+
38+
# ── 2. Policy violation: blocked tool ────────────────────────────────────
39+
print("\n[1] ADK callback — blocked tool ('shell') invoked by agent …")
40+
result = kernel.before_tool_callback(tool_name="shell", tool_args={}, agent_name="adk-agent")
41+
if result and result.get("error"):
42+
print(f" 🚫 BLOCKED — {result['error']}")
43+
44+
# ── 3. Policy violation: tool not on allowlist ────────────────────────────
45+
print("\n[2] ADK callback — tool not on allowlist ('web_scraper') …")
46+
result = kernel.before_tool_callback(tool_name="web_scraper", tool_args={}, agent_name="adk-agent")
47+
if result and result.get("error"):
48+
print(f" 🚫 BLOCKED — {result['error']}")
49+
50+
# ── 4. Policy violation: blocked content in tool arguments ────────────────
51+
print("\n[3] ADK callback — tool argument contains dangerous pattern …")
52+
result = kernel.before_tool_callback(
53+
tool_name="search",
54+
tool_args={"query": "DROP TABLE sessions; SELECT 1"},
55+
agent_name="adk-agent",
56+
)
57+
if result and result.get("error"):
58+
print(f" 🚫 BLOCKED — {result['error']}")
59+
60+
# ── 5. Compliant tool call passes all policy gates ────────────────────────
61+
print("\n[4] ADK callback — allowed tool with safe arguments …")
62+
result = kernel.before_tool_callback(
63+
tool_name="search",
64+
tool_args={"query": "AI governance best practices"},
65+
agent_name="adk-agent",
66+
)
67+
if result is None:
68+
print(" ✅ ALLOWED — all policy gates passed")
69+
70+
# ── 6. Audit trail from kernel ────────────────────────────────────────────
71+
stats = kernel.get_stats()
72+
violations = kernel.get_violations()
73+
print(f"\n── Kernel Stats ─────────────────────────────────────────")
74+
print(f" violations={stats['violations']} audit_events={stats['audit_events']}")
75+
76+
print("\n── Audit Trail ──────────────────────────────────────────")
77+
for i, v in enumerate(violations, 1):
78+
print(f" [{i}] BLOCKED policy={v.policy_name!r} reason={v.description!r}")
79+
for j, entry in enumerate(kernel.get_audit_log()[-1:], len(violations) + 1):
80+
print(f" [{j}] ALLOWED tool={entry.details.get('tool')!r} agent={entry.agent_name!r}")
81+
82+
print("\n🎉 Google ADK governance demo complete.")
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
"""
4+
LangChain Agent with Policy Enforcement — Quickstart
5+
=====================================================
6+
7+
pip install ai-agent-compliance[full] langchain langchain-openai
8+
python examples/quickstart/langchain_governed.py
9+
10+
Shows a real policy violation being caught, then a compliant call succeeding,
11+
with a printed audit trail.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import sys
17+
from datetime import datetime
18+
from pathlib import Path
19+
20+
# Allow running from the repo root without installing the toolkit.
21+
_REPO_ROOT = Path(__file__).resolve().parent.parent.parent
22+
sys.path.insert(0, str(_REPO_ROOT / "packages" / "agent-os" / "src"))
23+
24+
from agent_os.integrations import LangChainKernel
25+
from agent_os.integrations.base import GovernancePolicy, PolicyViolationError
26+
27+
# ── 1. Define a strict governance policy ──────────────────────────────────
28+
policy = GovernancePolicy(
29+
name="langchain-demo-policy",
30+
blocked_patterns=["DROP TABLE", "rm -rf"], # ban dangerous patterns
31+
require_human_approval=False,
32+
max_tool_calls=5,
33+
)
34+
35+
kernel = LangChainKernel(policy=policy)
36+
ctx = kernel.create_context("langchain-demo-agent")
37+
audit: list[dict] = []
38+
39+
print("=" * 60)
40+
print(" LangChain Agent — Governance Quickstart")
41+
print("=" * 60)
42+
43+
# ── 2. Policy violation: blocked content pattern ──────────────────────────
44+
print("\n[1] Agent task containing a dangerous SQL pattern …")
45+
allowed, reason = kernel.pre_execute(ctx, "Execute: DROP TABLE users; SELECT 1")
46+
if not allowed:
47+
print(f" 🚫 BLOCKED — {reason}")
48+
audit.append({"ts": datetime.now().isoformat(), "input": "DROP TABLE", "status": "BLOCKED"})
49+
50+
# ── 3. Policy violation: call budget exhausted ────────────────────────────
51+
print("\n[2] Exceeding the maximum call budget …")
52+
ctx.call_count = policy.max_tool_calls
53+
allowed, reason = kernel.pre_execute(ctx, "Summarise the quarterly report")
54+
if not allowed:
55+
print(f" 🚫 BLOCKED — {reason}")
56+
audit.append({"ts": datetime.now().isoformat(), "input": "summarise reports", "status": "BLOCKED"})
57+
ctx.call_count = 0 # reset for the next check
58+
59+
# ── 4. Compliant call succeeds ────────────────────────────────────────────
60+
print("\n[3] Safe agent input passes policy check …")
61+
allowed, reason = kernel.pre_execute(ctx, "What is the weather in London today?")
62+
if allowed:
63+
print(" ✅ ALLOWED — policy check passed")
64+
audit.append({"ts": datetime.now().isoformat(), "input": "weather query", "status": "ALLOWED"})
65+
66+
# ── 5. Print audit trail ──────────────────────────────────────────────────
67+
print("\n── Audit Trail ──────────────────────────────────────────")
68+
for i, entry in enumerate(audit, 1):
69+
print(f" [{i}] {entry['ts']} input={entry['input']!r} status={entry['status']}")
70+
71+
print("\n🎉 LangChain governance demo complete.")
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
"""
4+
OpenAI Agents SDK with Guardrails — Quickstart
5+
===============================================
6+
7+
pip install ai-agent-compliance[full] openai-agents
8+
python examples/quickstart/openai_agents_governed.py
9+
10+
Shows a real policy violation being caught by a tool guard, then a compliant
11+
tool call succeeding, with a printed audit trail.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import asyncio
17+
import sys
18+
from datetime import datetime
19+
from pathlib import Path
20+
21+
_REPO_ROOT = Path(__file__).resolve().parent.parent.parent
22+
sys.path.insert(0, str(_REPO_ROOT / "packages" / "agent-os" / "src"))
23+
24+
from agent_os.integrations.openai_agents_sdk import (
25+
GovernancePolicy,
26+
OpenAIAgentsKernel,
27+
PolicyViolationError,
28+
)
29+
30+
# ── 1. Define a strict governance policy ──────────────────────────────────
31+
policy = GovernancePolicy(
32+
allowed_tools=["file_search", "code_interpreter"], # explicit allowlist
33+
blocked_tools=["shell_exec", "network_request"], # explicit blocklist
34+
blocked_patterns=["DROP TABLE", "rm -rf"], # ban dangerous strings
35+
max_tool_calls=10,
36+
)
37+
38+
kernel = OpenAIAgentsKernel(policy=policy, on_violation=lambda _e: None)
39+
guard = kernel.create_tool_guard()
40+
audit: list[dict] = []
41+
42+
print("=" * 60)
43+
print(" OpenAI Agents SDK — Governance Quickstart")
44+
print("=" * 60)
45+
46+
47+
async def main() -> None:
48+
# ── 2. Policy violation: blocked tool (not in allowlist) ──────────────
49+
print("\n[1] Guarded tool call to a disallowed function ('web_search') …")
50+
51+
@guard
52+
async def web_search(query: str) -> str:
53+
return f"results for {query}"
54+
55+
try:
56+
await web_search("AI governance news")
57+
except PolicyViolationError as exc:
58+
print(f" 🚫 BLOCKED — {exc}")
59+
audit.append({"ts": datetime.now().isoformat(), "tool": "web_search", "status": "BLOCKED"})
60+
61+
# ── 3. Policy violation: blocked content in argument ──────────────────
62+
print("\n[2] Allowed tool called with a dangerous argument …")
63+
64+
@guard
65+
async def code_interpreter(code: str) -> str:
66+
return "executed"
67+
68+
try:
69+
await code_interpreter("import os; os.system('rm -rf /')")
70+
except PolicyViolationError as exc:
71+
print(f" 🚫 BLOCKED — {exc}")
72+
audit.append({"ts": datetime.now().isoformat(), "tool": "code_interpreter", "status": "BLOCKED"})
73+
74+
# ── 4. Compliant tool call succeeds ───────────────────────────────────
75+
print("\n[3] Allowed tool called with safe content …")
76+
77+
@guard
78+
async def file_search(query: str) -> list[str]:
79+
return ["Q4_report.pdf", "annual_summary.pdf"]
80+
81+
result = await file_search("Find Q4 financial reports")
82+
print(f" ✅ ALLOWED — guardrails passed, found: {result}")
83+
audit.append({"ts": datetime.now().isoformat(), "tool": "file_search", "status": "ALLOWED"})
84+
85+
# ── 5. Audit trail ────────────────────────────────────────────────────
86+
print("\n── Audit Trail ──────────────────────────────────────────")
87+
for i, entry in enumerate(audit, 1):
88+
print(f" [{i}] {entry['ts']} tool={entry['tool']!r} status={entry['status']}")
89+
print("\n🎉 OpenAI Agents SDK governance demo complete.")
90+
91+
92+
asyncio.run(main())

0 commit comments

Comments
 (0)