Repository navigation
Expand file tree
/
Copy pathworkflow.py
More file actions
92 lines (73 loc) · 2.84 KB
/
Copy pathworkflow.py
File metadata and controls
92 lines (73 loc) · 2.84 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
"""Agent Framework middleware running in the Workflow.
Both middleware classes run inside the Workflow, next to the agent's loop, so
they must be deterministic: no clock, no I/O, no randomness. Middleware that
needs I/O calls ``await workflow.execute_activity(...)``.
"""
import posixpath
from collections.abc import Awaitable, Callable, Mapping
from datetime import timedelta
from agent_framework import (
Agent,
ChatContext,
ChatMiddleware,
FunctionInvocationContext,
FunctionMiddleware,
tool,
)
from temporalio import workflow
from temporalio.microsoft_agent_framework import TemporalChatClient
@tool
def delete_file(path: str) -> str:
"""Delete the file at the given path."""
return f"deleted {path}"
# @@@SNIPSTART python-microsoft-agent-framework-middleware-middleware
ALLOWED_PREFIX = "/tmp/"
REMINDER = "Answer in one short sentence."
class BlockOutsideTmp(FunctionMiddleware):
"""Refuses delete_file calls outside /tmp without running the tool."""
async def process(
self,
context: FunctionInvocationContext,
call_next: Callable[[], Awaitable[None]],
) -> None:
if context.function.name == "delete_file":
arguments = context.arguments
raw_path = str(
arguments.get("path", "")
if isinstance(arguments, Mapping)
else getattr(arguments, "path", "")
)
# Normalize first, so "/tmp/../etc/passwd" does not pass as /tmp.
path = posixpath.normpath(raw_path)
if not path.startswith(ALLOWED_PREFIX):
# Not calling call_next() skips the tool; the model gets this result.
context.result = f"Refused: {raw_path} is outside {ALLOWED_PREFIX}"
return
await call_next()
class AppendReminder(ChatMiddleware):
"""Adds a reminder to the instructions of every model call."""
async def process(
self, context: ChatContext, call_next: Callable[[], Awaitable[None]]
) -> None:
options = dict(context.options or {})
instructions = options.get("instructions") or ""
options["instructions"] = f"{instructions} {REMINDER}".strip()
context.options = options
await call_next()
# @@@SNIPEND
# @@@SNIPSTART python-microsoft-agent-framework-middleware-workflow
@workflow.defn
class MiddlewareWorkflow:
@workflow.run
async def run(self, prompt: str) -> str:
agent = Agent(
client=TemporalChatClient(
"gpt-4o-mini", start_to_close_timeout=timedelta(seconds=60)
),
instructions="You manage files. Use delete_file when asked to delete one.",
tools=[delete_file],
middleware=[BlockOutsideTmp(), AppendReminder()],
)
response = await agent.run(prompt)
return response.text
# @@@SNIPEND