-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathProgram.cs
More file actions
138 lines (114 loc) · 4.62 KB
/
Copy pathProgram.cs
File metadata and controls
138 lines (114 loc) · 4.62 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
using System.Text;
using Azure;
using Azure.AI.Agents.Persistent;
using Azure.AI.Projects;
using Azure.Identity;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseHttpsRedirection();
app.MapPost("/run-agent", async (HttpContext context, IConfiguration configuration) =>
{
string? originalToken = ExtractBearerToken(context);
// Read configuration values
var azureAISettings = configuration.GetSection("AzureAI");
var endpoint = new Uri(azureAISettings["Endpoint"]!);
var tenantId = azureAISettings["TenantId"]!;
var clientId = azureAISettings["ClientId"]!;
var clientSecret = azureAISettings["ClientSecret"]!;
var connId = azureAISettings["ConnectionId"]!;
// Use the acquired token with OnBehalfOfCredential
var projectClient = new AIProjectClient(endpoint, new OnBehalfOfCredential(tenantId, clientId, clientSecret, originalToken));
PersistentAgentsClient agentClient = projectClient.GetPersistentAgentsClient();
// try with many fabric agents!
MicrosoftFabricToolDefinition fabricTool = new(
new FabricDataAgentToolParameters(
connId
)
);
PersistentAgent agent = await agentClient.Administration.CreateAgentAsync(
model: "gpt-4.1",
name: $"my-agent-{Guid.NewGuid()}",
instructions: "You are a helpful agent.",
tools: [fabricTool]);
PersistentAgentThread thread = await agentClient.Threads.CreateThreadAsync();
// Create message to thread
PersistentThreadMessage message = await agentClient.Messages.CreateMessageAsync(
thread.Id,
MessageRole.User,
"What insights can you provide from the Fabric resource?");
// Run the agent
ThreadRun run = await agentClient.Runs.CreateRunAsync(thread, agent);
do
{
await Task.Delay(TimeSpan.FromMilliseconds(500));
run = await agentClient.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued
|| run.Status == RunStatus.InProgress);
AsyncPageable<PersistentThreadMessage> messages = agentClient.Messages.GetMessagesAsync(
threadId: thread.Id,
order: ListSortOrder.Ascending
);
var responseBuilder = new StringBuilder();
await foreach (PersistentThreadMessage threadMessage in messages)
{
AppendMessages(responseBuilder, threadMessage);
}
return new { Message = "Success", TokenExists = !string.IsNullOrEmpty(originalToken), AgentResponse = responseBuilder.ToString() };
})
.WithName("GetWeatherForecast");
app.Run();
static string? ExtractBearerToken(HttpContext context)
{
var authHeader = context.Request.Headers.Authorization.FirstOrDefault();
string? originalToken = null;
if (authHeader != null && authHeader.StartsWith("Bearer "))
{
originalToken = authHeader.Substring("Bearer ".Length).Trim();
}
return originalToken;
}
static void AppendMessages(StringBuilder responseBuilder, PersistentThreadMessage threadMessage)
{
responseBuilder.Append($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
foreach (MessageContent contentItem in threadMessage.ContentItems)
{
if (contentItem is MessageTextContent textItem)
{
string response = textItem.Text;
if (textItem.Annotations != null)
{
foreach (MessageTextAnnotation annotation in textItem.Annotations)
{
if (annotation is MessageTextUriCitationAnnotation uriAnnotation)
{
response = response.Replace(uriAnnotation.Text, $" [{uriAnnotation.UriCitation.Title}]({uriAnnotation.UriCitation.Uri})");
}
}
}
responseBuilder.Append($"Agent response: {response}");
}
else if (contentItem is MessageImageFileContent imageFileItem)
{
responseBuilder.Append($"<image from ID: {imageFileItem.FileId}>");
}
responseBuilder.AppendLine();
}
}
// Configuration class for Azure AI settings
public class AzureAISettings
{
public string Endpoint { get; set; } = string.Empty;
public string TenantId { get; set; } = string.Empty;
public string ClientId { get; set; } = string.Empty;
public string ClientSecret { get; set; } = string.Empty;
public string ConnectionId { get; set; } = string.Empty;
}