-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProgram.cs
More file actions
240 lines (205 loc) · 11.6 KB
/
Program.cs
File metadata and controls
240 lines (205 loc) · 11.6 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
// HumanInTheLoop — an agent tool that suspends execution via RequestApprovalAsync
// and resumes only after a human approves or rejects via console input.
//
// Run: dotnet run --project samples/MAF/HumanInTheLoop/HumanInTheLoop.csproj
using System.ClientModel;
using System.ComponentModel;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenAI;
using Temporalio.Extensions.Agents;
using Temporalio.Extensions.Agents.Session;
using Temporalio.Extensions.AI;
// OpenAI.Chat also defines ChatMessage and ChatRole; pin to the MEAI versions
// throughout this file so the conversation loop types remain unambiguous.
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;
using ChatRole = Microsoft.Extensions.AI.ChatRole;
// ── Configuration ────────────────────────────────────────────────────────────
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Warning);
var apiKey = builder.Configuration.GetValue<string>("OPENAI_API_KEY")
?? throw new InvalidOperationException(
"OPENAI_API_KEY is not configured. Set it with: " +
"dotnet user-secrets set \"OPENAI_API_KEY\" \"sk-...\" --project samples/MAF/HumanInTheLoop");
var apiBaseUrl = builder.Configuration.GetValue<string>("OPENAI_API_BASE_URL")
?? throw new InvalidOperationException("OPENAI_API_BASE_URL is not configured in appsettings.json.");
const string model = "gpt-4o-mini";
var temporalAddress = builder.Configuration.GetValue<string>("TEMPORAL_ADDRESS") ?? "localhost:7233";
var openAiClient = new OpenAIClient(
new ApiKeyCredential(apiKey),
new OpenAIClientOptions { Endpoint = new Uri(apiBaseUrl) });
// ── send_email tool — the heart of this sample ───────────────────────────────
// Before sending, the tool suspends the activity by sending a structured
// DurableApprovalRequest to the workflow. Execution resumes only when a human
// submits a decision via ITemporalAgentClient.SubmitApprovalAsync.
var sendEmailTool = AIFunctionFactory.Create(
async (
[Description("Recipient email address")] string to,
[Description("Email subject")] string subject,
[Description("Full email body")] string body) =>
{
var ctx = TemporalAgentContext.Current;
// This call sends a [WorkflowUpdate] and blocks until SubmitApprovalAsync
// is called from the approval console below, or until agent.ApprovalTimeout
// (effective: 23 h) elapses — at which point a rejected decision is returned.
var decision = await ctx.RequestApprovalAsync(new DurableApprovalRequest
{
RequestId = Guid.NewGuid().ToString("N"),
Description = $"Send email to {to}\nSubject: {subject}\n\nBody:\n{body}"
});
if (!decision.Approved)
{
var reason = decision.Reason ?? "no reason given";
return $"Email to {to} was rejected by reviewer ({reason}). Not sent.";
}
// In a real system this would call your SMTP / SendGrid / SES client.
Console.WriteLine();
Console.WriteLine($" [EMAIL SENT] To: {to}");
Console.WriteLine($" Subject: {subject}");
return $"Email successfully sent to {to}.";
},
name: "send_email",
description: "Sends an email to the specified recipient. Requires human approval before delivery.");
// ── Worker registration ──────────────────────────────────────────────────────
builder.Services.AddChatClient(openAiClient.GetChatClient(model).AsIChatClient());
builder.Services.AddTemporalClient(temporalAddress, "default");
builder.Services
.AddHostedTemporalWorker("hitl-sample")
.AddTemporalAgents(opts =>
{
// HITL requires timeouts that cover the full human review window. The
// underlying activity heartbeats during this period so the worker won't
// treat it as stuck — as long as DefaultHeartbeatTimeout < DefaultActivityTimeout.
opts.DefaultActivityTimeout = TimeSpan.FromHours(24);
opts.DefaultHeartbeatTimeout = TimeSpan.FromMinutes(5);
opts.DefaultApprovalTimeout = TimeSpan.FromHours(23); // must be < DefaultActivityTimeout so the activity outlives the approval window
opts.AddDurableAgent("EmailAssistant", agent =>
{
agent.Instructions = """
You are a helpful email assistant. Help users compose and send emails.
When the user wants to send an email, use the send_email tool.
Confirm the recipient, subject, and body content before calling the tool.
If a send is rejected, explain what happened and offer to revise.
""";
agent.ChatClient = sp => sp.GetRequiredService<IChatClient>();
agent.AddTool(sendEmailTool, opts => opts.NoRetry());
// Per-agent override of opts.DefaultApprovalTimeout. Demonstrates the v0.3
// builder slot — not required (would inherit opts.DefaultApprovalTimeout otherwise).
agent.ApprovalTimeout = TimeSpan.FromHours(23);
});
});
var host = builder.Build();
await host.StartAsync();
var appLifetime = host.Services.GetRequiredService<IHostApplicationLifetime>();
var ct = appLifetime.ApplicationStopping;
Console.WriteLine();
Console.WriteLine("╔═══════════════════════════════════════════════════╗");
Console.WriteLine("║ Email Assistant — HITL Approval Sample ║");
Console.WriteLine("╠═══════════════════════════════════════════════════╣");
Console.WriteLine("║ Ask the assistant to send an email. ║");
Console.WriteLine("║ When it tries, you will be prompted to ║");
Console.WriteLine("║ approve or reject before it is delivered. ║");
Console.WriteLine("║ Type 'quit' to exit. ║");
Console.WriteLine("╚═══════════════════════════════════════════════════╝");
Console.WriteLine();
// ── Resolve services ─────────────────────────────────────────────────────────
var proxy = host.Services.GetTemporalAgentProxy("EmailAssistant");
var client = host.Services.GetRequiredService<ITemporalAgentClient>();
// ── Conversation session ─────────────────────────────────────────────────────
// A single session means the agent remembers context across turns.
var session = await proxy.CreateSessionAsync();
if (session is not TemporalAgentSession temporalSession)
throw new InvalidOperationException("Failed to retrieve TemporalAgentSessionId from the created session.");
var sessionId = temporalSession.SessionId;
// ── Main conversation loop ───────────────────────────────────────────────────
while (true)
{
Console.Write("You: ");
var input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input)) continue;
if (input.Equals("quit", StringComparison.OrdinalIgnoreCase)) break;
IList<ChatMessage> userMessages = [new(ChatRole.User, input)];
// Start the agent call without awaiting — it may block inside the tool
// while waiting for human approval, so we need to stay responsive.
var agentTask = proxy.RunAsync(userMessages, session, null, ct);
Console.WriteLine("Assistant: (thinking...)");
// Poll for pending approvals while the agent is running.
// GetPendingApprovalAsync is a [WorkflowQuery] — it never blocks
// the workflow and is safe to call as frequently as needed.
while (!agentTask.IsCompleted)
{
await Task.Delay(TimeSpan.FromSeconds(1));
// Guard before the network call: the task may have completed during the delay.
if (agentTask.IsCompleted) break;
DurableApprovalRequest? pending = null;
try
{
pending = await client.GetPendingApprovalAsync(sessionId, ct);
}
catch (Temporalio.Exceptions.RpcException ex) when (ex.Code == Temporalio.Exceptions.RpcException.StatusCode.NotFound)
{
// The workflow may not have started yet on the very first poll.
// Retry on the next tick.
continue;
}
if (pending is null) continue;
// ── Approval gate ──────────────────────────────────────────────────
// The agent is now suspended inside the tool. Surface the request
// and wait for the human reviewer to decide.
Console.WriteLine();
Console.WriteLine(" ╔══════════════════════════════════════════════╗");
Console.WriteLine(" ║ ⚠ APPROVAL REQUIRED ║");
Console.WriteLine(" ╠══════════════════════════════════════════════╣");
if (pending.Description is { } desc)
{
foreach (var line in desc.Split('\n'))
{
var display = line.Length > 44 ? line[..41] + "..." : line;
Console.WriteLine($" ║ {display,-44}║");
}
}
Console.WriteLine(" ╚══════════════════════════════════════════════╝");
string choice;
do
{
Console.Write(" Decision [approve/reject]: ");
choice = (Console.ReadLine() ?? string.Empty).Trim().ToLowerInvariant();
}
while (choice is not "approve" and not "reject");
string? comment = null;
if (choice == "reject")
{
Console.Write(" Reason (optional, press Enter to skip): ");
comment = Console.ReadLine()?.Trim();
if (string.IsNullOrWhiteSpace(comment)) comment = null;
}
// SubmitApprovalAsync is a [WorkflowUpdate] — strongly consistent,
// validates the RequestId, and unblocks WaitConditionAsync in the workflow.
await client.SubmitApprovalAsync(sessionId, new DurableApprovalDecision
{
RequestId = pending.RequestId,
Approved = choice == "approve",
Reason = comment
});
Console.WriteLine(choice == "approve"
? "\n ✓ Approved — agent is resuming..."
: "\n ✗ Rejected — agent is resuming...");
Console.WriteLine();
}
AgentResponse response;
try
{
response = await agentTask;
}
catch (OperationCanceledException)
{
break;
}
Console.WriteLine($"Assistant: {response.Text}");
Console.WriteLine();
}
try { await host.StopAsync(); } catch (OperationCanceledException) { }