-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathworkflow_hitl_checkpoint.py
More file actions
226 lines (188 loc) · 7.72 KB
/
workflow_hitl_checkpoint.py
File metadata and controls
226 lines (188 loc) · 7.72 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
"""Content review workflow with checkpoints and human-in-the-loop resume.
Demonstrates: FileCheckpointStorage, on_checkpoint_save/restore,
workflow.run(checkpoint_id=...), and pause/resume across process restarts.
A brief is turned into a prompt for an AI copywriter. The copywriter drafts
release notes, and a review gateway requests human approval. If rejected,
the human provides revision guidance and the loop repeats. Checkpoints are
saved at every superstep so the workflow survives process restarts.
Run:
uv run examples/workflow_hitl_checkpoint.py
"""
import asyncio
import os
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any
from agent_framework import (
Agent,
AgentExecutor,
AgentExecutorRequest,
AgentExecutorResponse,
AgentResponseUpdate,
Executor,
FileCheckpointStorage,
Message,
WorkflowBuilder,
WorkflowContext,
handler,
response_handler,
)
from agent_framework.openai import OpenAIChatClient
from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider
from dotenv import load_dotenv
load_dotenv(override=True)
API_HOST = os.getenv("API_HOST", "github")
# Configure the chat client based on the API host
async_credential = None
if API_HOST == "azure":
async_credential = DefaultAzureCredential()
token_provider = get_bearer_token_provider(async_credential, "https://cognitiveservices.azure.com/.default")
client = OpenAIChatClient(
base_url=f"{os.environ['AZURE_OPENAI_ENDPOINT']}/openai/v1/",
api_key=token_provider,
model_id=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT"],
)
elif API_HOST == "github":
client = OpenAIChatClient(
base_url="https://models.github.ai/inference",
api_key=os.environ["GITHUB_TOKEN"],
model_id=os.getenv("GITHUB_MODEL", "openai/gpt-5-mini"),
)
else:
client = OpenAIChatClient(
api_key=os.environ["OPENAI_API_KEY"], model_id=os.environ.get("OPENAI_MODEL", "gpt-5-mini")
)
# Directory for checkpoint files (easy to inspect and delete)
CHECKPOINT_DIR = Path(__file__).parent / "checkpoints"
CHECKPOINT_DIR.mkdir(parents=True, exist_ok=True)
# --- Executors ---
class BriefPreparer(Executor):
"""Normalizes the user brief and sends an AgentExecutorRequest to the writer."""
def __init__(self, id: str, agent_id: str) -> None:
super().__init__(id=id)
self._agent_id = agent_id
@handler
async def prepare(self, brief: str, ctx: WorkflowContext[AgentExecutorRequest, str]) -> None:
normalized = " ".join(brief.split()).strip()
if not normalized.endswith("."):
normalized += "."
ctx.set_state("brief", normalized)
prompt = (
"You are drafting product release notes. Summarise the brief below in two sentences. "
"Keep it positive and end with a call to action.\n\n"
f"BRIEF: {normalized}"
)
await ctx.send_message(
AgentExecutorRequest(messages=[Message("user", text=prompt)], should_respond=True),
target_id=self._agent_id,
)
@dataclass
class HumanApprovalRequest:
"""Sent to the human reviewer for approval."""
prompt: str = ""
draft: str = ""
iteration: int = 0
class ReviewGateway(Executor):
"""Routes agent drafts to humans and optionally back for revisions."""
def __init__(self, id: str, writer_id: str) -> None:
super().__init__(id=id)
self._writer_id = writer_id
self._iteration = 0
@handler
async def on_agent_response(self, response: AgentExecutorResponse, ctx: WorkflowContext) -> None:
self._iteration += 1
await ctx.request_info(
request_data=HumanApprovalRequest(
prompt="Review the draft. Reply 'approve' or provide edit instructions.",
draft=response.agent_response.text,
iteration=self._iteration,
),
response_type=str,
)
@response_handler
async def on_human_feedback(
self,
original_request: HumanApprovalRequest,
feedback: str,
ctx: WorkflowContext[AgentExecutorRequest | str, str],
) -> None:
reply = feedback.strip()
if len(reply) == 0 or reply.lower() == "approve":
await ctx.yield_output(original_request.draft)
return
# Loop back to the writer with revision guidance
prompt = (
"Revise the launch note. Respond with the new copy only.\n\n"
f"Previous draft:\n{original_request.draft}\n\n"
f"Human guidance: {reply}"
)
await ctx.send_message(
AgentExecutorRequest(messages=[Message("user", text=prompt)], should_respond=True),
target_id=self._writer_id,
)
async def on_checkpoint_save(self) -> dict[str, Any]:
return {"iteration": self._iteration}
async def on_checkpoint_restore(self, state: dict[str, Any]) -> None:
self._iteration = state.get("iteration", 0)
# --- Main ---
async def main() -> None:
"""Run the checkpoint HITL workflow."""
storage = FileCheckpointStorage(storage_path=CHECKPOINT_DIR)
writer_agent = Agent(
name="writer",
instructions="Write concise, warm release notes that sound human and helpful.",
client=client,
)
writer = AgentExecutor(writer_agent)
review_gateway = ReviewGateway(id="review_gateway", writer_id="writer")
prepare_brief = BriefPreparer(id="prepare_brief", agent_id="writer")
workflow = (
WorkflowBuilder(
name="content_review",
max_iterations=6,
start_executor=prepare_brief,
checkpoint_storage=storage,
)
.add_edge(prepare_brief, writer)
.add_edge(writer, review_gateway)
.add_edge(review_gateway, writer) # revisions loop
.build()
)
# Check if there are existing checkpoints to resume from
checkpoints = await storage.list_checkpoints(workflow_name=workflow.name)
if checkpoints:
sorted_cps = sorted(checkpoints, key=lambda cp: datetime.fromisoformat(cp.timestamp))
latest = sorted_cps[-1]
print(f"📂 Found {len(sorted_cps)} checkpoint(s). Resuming from latest: {latest.checkpoint_id}")
stream = workflow.run(checkpoint_id=latest.checkpoint_id, stream=True)
else:
brief = (
"Introduce our new compact air fryer with a 5-quart basket. Mention the $89 price, "
"highlight the rapid air technology that crisps food with 95% less oil, "
"and invite customers to pre-order."
)
print(f"▶️ Starting workflow with brief: {brief}\n")
stream = workflow.run(brief, stream=True)
while True:
pending: dict[str, HumanApprovalRequest] = {}
async for event in stream:
if event.type == "request_info" and isinstance(event.data, HumanApprovalRequest):
pending[event.request_id] = event.data
elif event.type == "output" and not isinstance(event.data, AgentResponseUpdate):
print(f"\n✅ Workflow completed:\n{event.data}")
if not pending:
break
responses: dict[str, str] = {}
for request_id, request in pending.items():
print("\n" + "=" * 60)
print(f"💬 Human approval needed (iteration {request.iteration})")
print(request.prompt)
print(f"\nDraft:\n---\n{request.draft}\n---")
response = input("Type 'approve' or enter revision guidance: ").strip()
responses[request_id] = response
stream = workflow.run(stream=True, responses=responses)
if async_credential:
await async_credential.close()
if __name__ == "__main__":
asyncio.run(main())