-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathProgram.cs
More file actions
354 lines (276 loc) · 13.3 KB
/
Program.cs
File metadata and controls
354 lines (276 loc) · 13.3 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Projects.OpenAI;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI.Workflows;
using OpenAI.Assistants;
using OpenAI.Responses;
using DotNetEnv;
using Azure.AI.Agents.Persistent;
// Load environment variables
Env.Load("../../../../.env");
var azure_foundry_endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set.");
var azure_foundry_model_id = "gpt-4.1-mini";
var bing_conn_id = Environment.GetEnvironmentVariable("BING_CONNECTION_ID") ?? throw new InvalidOperationException("BING_CONNECTION_ID is not set.");
// Agent instructions
const string EvangelistInstructions = @"
You are a technology evangelist create a first draft for a technical tutorials.
1. Each knowledge point in the outline must include a link. Follow the link to access the content related to the knowledge point in the outline. Expand on that content.
2. Each knowledge point must be explained in detail.
3. Rewrite the content according to the entry requirements, including the title, outline, and corresponding content. It is not necessary to follow the outline in full order.
4. The content must be more than 200 words.
4. Output draft as Markdown format. set 'draft_content' to the draft content.
5. return result as JSON with fields 'draft_content' (string).";
const string ContentReviewerInstructions = @"
You are a content reviewer and need to check whether the tutorial's draft content meets the following requirements:
1. The draft content less than 200 words, set 'review_result' to 'No' and 'reason' to 'Content is too short'. If the draft content is more than 200 words, set 'review_result' to 'Yes' and 'reason' to 'The content is good'.
2. set 'draft_content' to the original draft content.
3. return result as JSON with fields 'review_result' ('Yes' or 'No' ) and 'reason' (string) and 'draft_content' (string).";
const string PublisherInstructions = @"
You are the content publisher ,run code to save the tutorial's draft content as a Markdown file. Saved file's name is marked with current date and time, such as yearmonthdayhourminsec. Note that if it is 1-9, you need to add 0, such as 20240101123045.md.
";
string OUTLINE_Content = @"
# Introduce AI Agent
## What's AI Agent
https://github.com/microsoft/ai-agents-for-beginners/tree/main/01-intro-to-ai-agents
***Note*** Don's create any sample code
## Introduce Azure AI Foundry Agent Service
https://learn.microsoft.com/en-us/azure/ai-foundry/agents/overview
***Note*** Don's create any sample code
## Microsoft Agent Framework
https://github.com/microsoft/agent-framework/tree/main/docs/docs-templates
***Note*** Don's create any sample code
";
AIProjectClient aiProjectClient = new(
new Uri(azure_foundry_endpoint),
new AzureCliCredential());
var connectionName = Environment.GetEnvironmentVariable("BING_CONNECTION_NAME");
Console.WriteLine($"Using Bing Connection: {connectionName}");
AIProjectConnection bingConnectionName = aiProjectClient.Connections.GetConnection(connectionName: connectionName);
// Console.WriteLine($"Using Bing Connection ID: {bing_conn_id}");
// Configure Bing Grounding Tool
BingGroundingAgentTool bingGroundingAgentTool = new(new BingGroundingSearchToolOptions(
searchConfigurations: [new Azure.AI.Projects.OpenAI.BingGroundingSearchConfiguration(projectConnectionId: bingConnectionName.Id)]
)
);
AIAgent evangelistagent = await aiProjectClient.CreateAIAgentAsync(
name: "dotNETEvangelist",
creationOptions: new AgentVersionCreationOptions(
new PromptAgentDefinition(model: azure_foundry_model_id)
{
Instructions = EvangelistInstructions,
Tools = {
bingGroundingAgentTool,
}
})
);
// var conttent_ResponseFormat = ChatResponseFormat.ForJsonSchema(AIJsonUtilities.CreateJsonSchema(typeof(ContentResult)), "ContentResult", "Content Result with DraftContent");
// var content_option = new ChatOptions{
// ResponseFormat = conttent_ResponseFormat
// };
AIAgent contentRevieweragent = await aiProjectClient.CreateAIAgentAsync(
name: "dotNETContentReviewer",
creationOptions: new AgentVersionCreationOptions(
new PromptAgentDefinition(model: azure_foundry_model_id)
{
Instructions = ContentReviewerInstructions,
})
);
AIAgent publisheragent = await aiProjectClient.CreateAIAgentAsync(
name: "dotNETPublisher",
creationOptions: new AgentVersionCreationOptions(
new PromptAgentDefinition(model: azure_foundry_model_id)
{
Instructions = PublisherInstructions,
Tools = {
ResponseTool.CreateCodeInterpreterTool(
new CodeInterpreterToolContainer(
CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration(fileIds: [])
)
),
},
})
);
// Create the three specialized agents
// var evangelistMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
// model: azure_foundry_model_id,
// name: "dotNETEvangelist",
// instructions: EvangelistInstructions,
// tools: [bingGroundingTool]
// );
// var contentReviewerMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
// model: azure_foundry_model_id,
// name: "dotNETContentReviewer",
// instructions: ContentReviewerInstructions
// );
// var publisherMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
// model: azure_foundry_model_id,
// name: "dotNETPublisher",
// instructions: PublisherInstructions,
// tools: [new CodeInterpreterToolDefinition()]
// );
// AIAgent publisheragent = await agentsClient.GetAIAgentAsync(publisher_agentId);
// Create the three specialized agents
// var evangelistMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
// model: azure_foundry_model_id,
// name: "Evangelist",
// instructions: EvangelistInstructions,
// tools: [bingGroundingTool]
// );
// var contentReviewerMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
// model: azure_foundry_model_id,
// name: "ContentReviewer",
// instructions: ContentReviewerInstructions
// );
// var publisherMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
// model: azure_foundry_model_id,
// name: "Publisher",
// instructions: PublisherInstructions,
// tools: [new CodeInterpreterToolDefinition()]
// );
// string evangelist_agentId = evangelistMetadata.Value.Id;
// string contentReviewer_agentId = contentReviewerMetadata.Value.Id;
// string publisher_agentId = publisherMetadata.Value.Id;
// // Get AI Agents
// AIAgent evangelistagent = await persistentAgentsClient.GetAIAgentAsync(evangelist_agentId, new()
// {
// // ResponseFormat = ChatResponseFormat.ForJsonSchema(AIJsonUtilities.CreateJsonSchema(typeof(ContentResult)), "ContentResult", "Content Result with DraftContent"),
// });
// AIAgent contentRevieweragent = await persistentAgentsClient.GetAIAgentAsync(contentReviewer_agentId, new()
// {
// ResponseFormat = ChatResponseFormat.ForJsonSchema(AIJsonUtilities.CreateJsonSchema(typeof(ReviewResult)), "ReviewResult", "Review Result From DraftContent")
// });
// AIAgent publisheragent = await persistentAgentsClient.GetAIAgentAsync(publisher_agentId);
// Create executors
var draftExecutor = new DraftExecutor(evangelistagent);
var contentReviewerExecutor = new ContentReviewExecutor(contentRevieweragent);
var publishExecutor = new PublishExecutor(publisheragent);
var sendReviewerExecutor = new SendReviewExecutor();
// Build workflow with conditional logic
var workflow = new WorkflowBuilder(draftExecutor)
.AddEdge(draftExecutor, contentReviewerExecutor)
.AddEdge(contentReviewerExecutor, publishExecutor, condition: GetCondition(expectedResult: "Yes"))
.AddEdge(contentReviewerExecutor, sendReviewerExecutor, condition: GetCondition(expectedResult: "No"))
.WithOutputFrom(publishExecutor, sendReviewerExecutor)
.Build();
// Prepare prompt
string prompt = @"You need to write a draft based on the following outline and the content provided in the link corresponding to the outline.
After draft create , the reviewer check it , if it meets the requirements, it will be submitted to the publisher and save it as a Markdown file,
otherwise need to rewrite draft until it meets the requirements.
The provided outline content and related links is as follows:" + OUTLINE_Content;
Console.WriteLine("Starting workflow...");
// Execute workflow
var chat = new ChatMessage(ChatRole.User, prompt);
await using StreamingRun run = await InProcessExecution.RunStreamingAsync(workflow, chat);
// Process workflow events
await run.TrySendMessageAsync(new TurnToken(emitEvents: true));
await foreach (WorkflowEvent evt in run.WatchStreamAsync().ConfigureAwait(false))
{
if (evt is WorkflowOutputEvent outputEvent)
{
Console.WriteLine($"{outputEvent}");
}
}
// Mermaid
Console.WriteLine("\nMermaid string: \n=======");
var mermaid = workflow.ToMermaidString();
Console.WriteLine(mermaid);
Console.WriteLine("=======");
// DOT - Save to file instead of stdout to avoid pipe issues
var dotString = workflow.ToDotString();
var dotFilePath = "workflow.dot";
File.WriteAllText(dotFilePath, dotString);
Console.WriteLine($"\nDOT graph saved to: {dotFilePath}");
Console.WriteLine("To generate image: dot -Tsvg workflow.dot -o workflow.svg");
Console.WriteLine(" dot -Tpng workflow.dot -o workflow.png");
// Helper function for conditional routing
static Func<object?, bool> GetCondition(string expectedResult) =>
reviewResult => reviewResult is ReviewResult review && review.Result == expectedResult;
// Data Models
public class ContentResult
{
[JsonPropertyName("draft_content")]
public string DraftContent { get; set; } = string.Empty;
}
public class ReviewResult
{
[JsonPropertyName("review_result")]
public string Result { get; set; } = string.Empty;
[JsonPropertyName("reason")]
public string Reason { get; set; } = string.Empty;
[JsonPropertyName("draft_content")]
public string DraftContent { get; set; } = string.Empty;
}
// Executor: Draft Creation
public partial class DraftExecutor : Executor
{
private readonly AIAgent _evangelistAgent;
public DraftExecutor(AIAgent evangelistAgent) : base("DraftExecutor")
{
this._evangelistAgent = evangelistAgent;
}
[MessageHandler]
public async ValueTask<ContentResult> HandleAsync(ChatMessage message, IWorkflowContext context, CancellationToken cancellationToken = default)
{
Console.WriteLine($"DraftExecutor .......loading \n" + message.Text);
var response = await this._evangelistAgent.RunAsync(message);
Console.WriteLine($"DraftExecutor response: {response.Text}");
ContentResult contentResult = new ContentResult { DraftContent = Convert.ToString(response) ?? "" };
Console.WriteLine($"DraftExecutor generated content: {contentResult.DraftContent}");
return contentResult;
}
}
// Executor: Content Review
public partial class ContentReviewExecutor : Executor
{
private readonly AIAgent _contentReviewerAgent;
public ContentReviewExecutor(AIAgent contentReviewerAgent) : base("ContentReviewExecutor")
{
this._contentReviewerAgent = contentReviewerAgent;
}
[MessageHandler]
public async ValueTask<ReviewResult> HandleAsync(ContentResult content, IWorkflowContext context, CancellationToken cancellationToken = default)
{
Console.WriteLine($"ContentReviewExecutor .......loading");
var response = await this._contentReviewerAgent.RunAsync(content.DraftContent);
var reviewResult = JsonSerializer.Deserialize<ReviewResult>(response.Text)
?? throw new InvalidOperationException("Failed to deserialize review result");
Console.WriteLine($"ContentReviewExecutor review result: {reviewResult.Result}, reason: {reviewResult.Reason}");
return reviewResult;
}
}
// Executor: Publishing
public partial class PublishExecutor : Executor
{
private readonly AIAgent _publishAgent;
public PublishExecutor(AIAgent publishAgent) : base("PublishExecutor")
{
this._publishAgent = publishAgent;
}
[MessageHandler]
public async ValueTask HandleAsync(ReviewResult review, IWorkflowContext context, CancellationToken cancellationToken = default)
{
Console.WriteLine($"PublishExecutor .......loading");
var response = await this._publishAgent.RunAsync(review.DraftContent);
Console.WriteLine($"Response from PublishExecutor: {response.Text}");
await context.YieldOutputAsync($"Publishing result: {response.Text}");
}
}
// Executor: Send Review Notification
public partial class SendReviewExecutor : Executor
{
public SendReviewExecutor() : base("SendReviewExecutor")
{
}
[MessageHandler]
public async ValueTask HandleAsync(ReviewResult message, IWorkflowContext context, CancellationToken cancellationToken = default) =>
await context.YieldOutputAsync($"Draft content needs revision: {message.Reason}");
}