-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathopenai_agents_sdk_integration.py
More file actions
443 lines (351 loc) · 13.4 KB
/
Copy pathopenai_agents_sdk_integration.py
File metadata and controls
443 lines (351 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
"""OpenAI Agents SDK Integration Examples for Agent-Airlock.
This example demonstrates how to integrate Agent-Airlock with OpenAI's
Agents SDK for secure multi-agent workflows. Shows:
1. @function_tool + @Airlock pattern
2. Multi-agent handoffs with security
3. Guardrails integration
4. MCP tool integration
5. Manager pattern with secured sub-agents
Requirements:
pip install agent-airlock openai-agents
References:
- OpenAI Agents SDK: https://openai.github.io/openai-agents-python/
- GitHub: https://github.com/openai/openai-agents-python
- PyPI: https://pypi.org/project/openai-agents/
"""
from agent_airlock import (
READ_ONLY_POLICY,
Airlock,
AirlockConfig,
SecurityPolicy,
)
# Check if OpenAI Agents SDK is available
try:
from agents import Agent, Runner, function_tool
except ImportError:
print("OpenAI Agents SDK is required for this example.")
print("Install with: pip install openai-agents")
raise SystemExit(1) from None
# =============================================================================
# THE GOLDEN RULE: @Airlock MUST be closest to the function definition
# =============================================================================
#
# ✅ CORRECT:
# @function_tool
# @Airlock()
# def my_function(): ...
#
# ❌ WRONG:
# @Airlock()
# @function_tool
# def my_function(): ...
#
# The @function_tool decorator generates schema from function signature.
# @Airlock preserves the signature so schema generation works correctly.
# =============================================================================
# Configuration
config = AirlockConfig(
strict_mode=True, # Reject hallucinated arguments
mask_pii=True, # Mask PII in outputs
mask_secrets=True, # Mask API keys, passwords
)
# =============================================================================
# Example 1: Basic @function_tool + @Airlock pattern
# =============================================================================
@function_tool
@Airlock(config=config)
def get_weather(city: str, units: str = "celsius") -> str:
"""Get the current weather for a city.
Args:
city: Name of the city
units: Temperature units (celsius or fahrenheit)
"""
return f"Weather in {city}: 22°{units[0].upper()}, Sunny"
@function_tool
@Airlock(config=config)
def search_products(query: str, category: str = "all", limit: int = 10) -> str:
"""Search for products in the catalog.
Args:
query: Search query string
category: Product category filter
limit: Maximum number of results (1-100)
"""
return f"Found {limit} products matching '{query}' in category '{category}'"
# =============================================================================
# Example 2: Read-only tools for data retrieval
# =============================================================================
@function_tool
@Airlock(config=config, policy=READ_ONLY_POLICY)
def get_customer_info(customer_id: str) -> str:
"""Get customer information (read-only).
Args:
customer_id: The customer's unique identifier
"""
# PII will be masked in the output
return f"""
Customer {customer_id}:
- Name: John Doe
- Email: john.doe@example.com
- Phone: 555-123-4567
- Status: Active
"""
@function_tool
@Airlock(config=config, policy=READ_ONLY_POLICY)
def get_order_status(order_id: str) -> str:
"""Get the status of an order.
Args:
order_id: The order identifier
"""
return f"Order {order_id}: Shipped, arriving in 2 days"
# =============================================================================
# Example 3: Rate-limited tools for expensive operations
# =============================================================================
API_POLICY = SecurityPolicy(
allowed_tools=["*"],
rate_limits={
"call_external_api": "30/minute",
"send_notification": "10/minute",
},
)
@function_tool
@Airlock(config=config, policy=API_POLICY)
def call_external_api(endpoint: str, method: str = "GET") -> str:
"""Call an external API endpoint.
Rate limited to 30 calls per minute.
Args:
endpoint: API endpoint URL
method: HTTP method (GET, POST, PUT, DELETE)
"""
return f"Response from {method} {endpoint}: 200 OK"
@function_tool
@Airlock(config=config, policy=API_POLICY)
def send_notification(user_id: str, message: str, channel: str = "email") -> str: # noqa: ARG001
"""Send a notification to a user.
Rate limited to 10 per minute.
Args:
user_id: Target user ID
message: Notification message
channel: Notification channel (email, sms, push)
"""
return f"Notification sent to {user_id} via {channel}"
# =============================================================================
# Example 4: Sandboxed code execution
# =============================================================================
@function_tool
@Airlock(config=config, sandbox=True, sandbox_required=True)
def execute_code(code: str, language: str = "python") -> str:
"""Execute code in a secure sandbox.
SECURITY: Runs in isolated E2B Firecracker MicroVM.
Will NOT fall back to local execution.
Args:
code: Source code to execute
language: Programming language (python only for now)
"""
if language != "python":
return f"Error: Only Python is supported, got {language}"
import io
import sys
old_stdout = sys.stdout
sys.stdout = io.StringIO()
try:
exec(code) # noqa: S102 - Safe: sandbox_required=True
return sys.stdout.getvalue() or "Code executed successfully"
except Exception as e:
return f"Execution error: {e}"
finally:
sys.stdout = old_stdout
# =============================================================================
# Example 5: Creating secure agents with handoffs
# =============================================================================
def create_support_agents():
"""Create a support agent system with handoffs.
Architecture:
- Triage Agent: Routes to appropriate specialist
- Billing Agent: Handles billing questions (read-only)
- Technical Agent: Handles technical issues (can run code)
"""
# Define agent-specific tools
@function_tool
@Airlock(config=config, policy=READ_ONLY_POLICY)
def get_billing_info(account_id: str) -> str:
"""Get billing information for an account.
Args:
account_id: The account identifier
"""
return f"Account {account_id}: Balance $150.00, Next payment: Feb 15"
@function_tool
@Airlock(config=config, policy=READ_ONLY_POLICY)
def check_service_status(service: str) -> str:
"""Check the status of a service.
Args:
service: Service name to check
"""
return f"Service '{service}': All systems operational"
# Create specialized agents
billing_agent = Agent(
name="billing_agent",
instructions="You are a billing specialist. Help with billing questions.",
tools=[get_billing_info],
model="gpt-4o-mini",
)
technical_agent = Agent(
name="technical_agent",
instructions="You are a technical support specialist.",
tools=[check_service_status, execute_code],
model="gpt-4o-mini",
)
# Triage agent with handoffs
triage_agent = Agent(
name="triage_agent",
instructions="""You are a customer support triage agent.
Route billing questions to billing_agent.
Route technical issues to technical_agent.
""",
handoffs=[billing_agent, technical_agent],
model="gpt-4o-mini",
)
return triage_agent
# =============================================================================
# Example 6: Manager pattern - agents as tools
# =============================================================================
def create_manager_agent():
"""Create a manager agent that uses other agents as tools.
The manager orchestrates specialized agents to solve complex tasks.
Each sub-agent has its own security policies.
"""
# Create specialized agents
research_agent = Agent(
name="researcher",
instructions="You research topics and provide detailed information.",
tools=[search_products, get_customer_info],
model="gpt-4o-mini",
)
writer_agent = Agent(
name="writer",
instructions="You write clear, professional content.",
model="gpt-4o-mini",
)
# Manager agent with agents as tools
manager = Agent(
name="manager",
instructions="""You are a project manager coordinating a team.
Use the researcher for gathering information.
Use the writer for creating content.
""",
tools=[
research_agent.as_tool(
tool_name="research",
tool_description="Research a topic thoroughly",
),
writer_agent.as_tool(
tool_name="write",
tool_description="Write professional content",
),
],
model="gpt-4o",
)
return manager
# =============================================================================
# Example 7: Async tools for parallel execution
# =============================================================================
@function_tool
@Airlock(config=config)
async def async_fetch_data(url: str, timeout: int = 30) -> str: # noqa: ARG001
"""Fetch data from a URL asynchronously.
Args:
url: URL to fetch data from
timeout: Request timeout in seconds
"""
import asyncio
await asyncio.sleep(0.1) # Simulate async IO
return f"Fetched data from {url}"
@function_tool
@Airlock(config=config)
async def async_process_data(data: str, operation: str = "summarize") -> str:
"""Process data asynchronously.
Args:
data: Input data to process
operation: Processing operation (summarize, analyze, transform)
"""
import asyncio
await asyncio.sleep(0.1) # Simulate processing
return f"Processed '{data}' with {operation}: Result ready"
# =============================================================================
# Demo: Run the examples
# =============================================================================
async def demo_openai_agents():
"""Demonstrate Agent-Airlock with OpenAI Agents SDK."""
print("\n" + "=" * 60)
print("DEMO: OpenAI Agents SDK + Agent-Airlock")
print("=" * 60)
# Test 1: Tools are registered with Airlock protection
print("\n1. Tools registered with Airlock:")
print(f" get_weather: {type(get_weather).__name__}")
print(f" search_products: {type(search_products).__name__}")
print(" Note: FunctionTools are used by the Agent, not called directly")
# Test 2: Run with Agent - this is the real test
print("\n2. Running agent with secured tools (weather):")
try:
agent = Agent(
name="weather_agent",
instructions="You are a helpful weather assistant. Use the get_weather tool.",
tools=[get_weather],
model="gpt-4o-mini",
)
result = await Runner.run(agent, "What's the weather in Paris?")
print(f" Agent response: {result.final_output}")
except Exception as e:
print(f" Error: {e}")
# Test 3: Run with Agent - product search
print("\n3. Running agent with secured tools (products):")
try:
agent = Agent(
name="product_agent",
instructions="You are a product search assistant. Use the search_products tool.",
tools=[search_products],
model="gpt-4o-mini",
)
result = await Runner.run(agent, "Find me 5 laptops in the electronics category")
print(f" Agent response: {result.final_output}")
except Exception as e:
print(f" Error: {e}")
# Test 4: PII masking with customer info
print("\n4. Running agent with PII masking:")
try:
agent = Agent(
name="customer_agent",
instructions="You are a customer service agent. Use get_customer_info to look up customers.",
tools=[get_customer_info],
model="gpt-4o-mini",
)
result = await Runner.run(agent, "Get info for customer CUST-123")
print(f" Agent response: {result.final_output}")
print(" Note: Email/phone should be masked in the response")
except Exception as e:
print(f" Error: {e}")
# =============================================================================
# Main entry point
# =============================================================================
if __name__ == "__main__":
import asyncio
print("=" * 60)
print("Agent-Airlock + OpenAI Agents SDK Integration")
print("=" * 60)
print()
print("Secured Tools:")
print(" - get_weather: Basic weather lookup")
print(" - search_products: Product search with validation")
print(" - get_customer_info: Read-only, PII masking")
print(" - get_order_status: Read-only")
print(" - call_external_api: Rate limited (30/min)")
print(" - send_notification: Rate limited (10/min)")
print(" - execute_code: Sandboxed execution")
print()
print("Agent Patterns:")
print(" - Handoff pattern: Triage → Specialist agents")
print(" - Manager pattern: Agents as tools")
print()
asyncio.run(demo_openai_agents())
print("\n" + "=" * 60)
print("Examples complete!")
print("=" * 60)