-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathProgram.cs
More file actions
222 lines (173 loc) · 7.7 KB
/
Copy pathProgram.cs
File metadata and controls
222 lines (173 loc) · 7.7 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
using System.ClientModel.Primitives;
using System.Collections.Concurrent;
using System.Data.Common;
using Azure.Identity;
using GitHub.Copilot;
using InterviewCoach.Agent;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.DevUI;
using Microsoft.Agents.AI.Hosting.AGUI.AspNetCore;
using Microsoft.Extensions.AI;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using OpenAI;
using OpenAI.Chat;
var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;
builder.AddServiceDefaults();
builder.Services.AddHttpClient("mcp-markitdown", client =>
{
client.BaseAddress = new Uri("http://mcp-markitdown");
});
builder.Services.AddKeyedSingleton<McpClient>("mcp-markitdown", (sp, obj) =>
{
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
var httpClient = sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("mcp-markitdown");
var endpoint = $"{httpClient.BaseAddress!.ToString().TrimEnd('/')}";
var clientTransportOptions = new HttpClientTransportOptions()
{
Endpoint = new Uri($"{endpoint}/mcp")
};
var clientTransport = new HttpClientTransport(clientTransportOptions, httpClient, loggerFactory);
var clientOptions = new McpClientOptions()
{
ClientInfo = new Implementation()
{
Name = "MCP MarkItDown Client",
Version = "1.0.0",
}
};
return McpClient.CreateAsync(clientTransport, clientOptions, loggerFactory).GetAwaiter().GetResult();
});
builder.Services.AddHttpClient("mcp-interview-data", client =>
{
client.BaseAddress = new Uri("https+http://mcp-interview-data");
});
builder.Services.AddKeyedSingleton<McpClient>("mcp-interview-data", (sp, obj) =>
{
var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
var httpClient = sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("mcp-interview-data");
var endpoint = builder.Environment.IsDevelopment() == true
? $"{httpClient.BaseAddress!.ToString().Replace("https+", string.Empty).TrimEnd('/')}"
: $"{httpClient.BaseAddress!.ToString().Replace("+http", string.Empty).TrimEnd('/')}";
var clientTransportOptions = new HttpClientTransportOptions()
{
Endpoint = new Uri($"{endpoint}/mcp")
};
var clientTransport = new HttpClientTransport(clientTransportOptions, httpClient, loggerFactory);
var clientOptions = new McpClientOptions()
{
ClientInfo = new Implementation()
{
Name = "MCP Interview Data Client",
Version = "1.0.0",
}
};
return McpClient.CreateAsync(clientTransport, clientOptions, loggerFactory).GetAwaiter().GetResult();
});
var llmProvider = Enum.TryParse<LlmProvider>(config[Constants.LlmProvider], ignoreCase: true, out var parsedProvider)
? parsedProvider
: throw new InvalidOperationException($"LLM provider not specified or invalid. Please set the '{Constants.LlmProvider}' configuration value.");
if (llmProvider == LlmProvider.MicrosoftFoundry)
{
var connection = new DbConnectionStringBuilder() { ConnectionString = config.GetConnectionString("chat") };
var cogServicesEndpoint = (connection.TryGetValue("Endpoint", out var endpointValue) ? endpointValue?.ToString() : throw new InvalidOperationException("Missing Foundry Endpoint")) ?? throw new InvalidOperationException("Missing Foundry Endpoint");
var uri = new Uri(cogServicesEndpoint);
var host = uri.Host.Split('.')[0];
var model = connection.TryGetValue("Deployment", out var modelValue) ? modelValue?.ToString() : throw new InvalidOperationException("Missing Foundry Model");
var credentialOptions = new DefaultAzureCredentialOptions();
if (config["AZURE_TENANT_ID"] is { } tenantId)
{
credentialOptions.TenantId = tenantId;
}
if (builder.Environment.IsDevelopment())
{
// Locally there is no Managed Identity, so the IMDS probe fails with an
// "unreachable network" error (169.254.169.254) that aborts the credential
// chain before it reaches the Azure CLI credential. Exclude it during local
// development so `az login` is used; it stays enabled when deployed to Azure.
credentialOptions.ExcludeManagedIdentityCredential = true;
}
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(credentialOptions),
"https://cognitiveservices.azure.com/.default");
#pragma warning disable OPENAI001
ChatClient client = new(
authenticationPolicy: tokenPolicy,
model: model,
options: new OpenAIClientOptions()
{
Endpoint = new($"{uri.Scheme}://{host}.openai.azure.com/openai/v1/"),
});
builder.Services.AddSingleton(client.AsIChatClient());
}
else if (llmProvider == LlmProvider.GitHubCopilot)
{
var githubToken = config[Constants.GitHubToken];
builder.Services.AddSingleton(_ => new CopilotClient(new CopilotClientOptions
{
BaseDirectory = Path.Combine(Path.GetTempPath(), "interview-coach-copilot"),
GitHubToken = githubToken,
Mode = CopilotClientMode.Empty,
UseLoggedInUser = string.IsNullOrWhiteSpace(githubToken),
}));
}
else
{
throw new NotSupportedException($"The specified LLM provider '{llmProvider}' is not supported.");
}
var agentBuilder = builder.AddAIAgent("coach");
builder.Services.AddOpenAIResponses();
builder.Services.AddOpenAIConversations();
// DevUI is intentionally configured for both development and production environments,
// so that the DevUI can be used to inspect the agent's state and behavior in production scenarios.
builder.Services.AddDevUI(options => options.AllowRemoteAccess = true);
builder.Services.AddAGUIServer();
var app = builder.Build();
app.MapDefaultEndpoints();
app.MapOpenAIResponses();
app.MapOpenAIConversations();
app.MapAGUIServer(agentBuilder, "ag-ui");
// DevUI is intentionally mapped for both development and production environments,
// so that the DevUI can be used to inspect the agent's state and behavior in production scenarios.
app.MapDevUI();
if (builder.Environment.IsDevelopment() == false)
{
app.UseHttpsRedirection();
}
// --- File Upload Endpoints ---
// In-memory store for uploaded files (ephemeral, session-scoped).
var uploadedFiles = new ConcurrentDictionary<string, (byte[] Content, string ContentType, string FileName)>();
var allowedExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
".pdf", ".docx", ".doc", ".txt", ".md", ".html"
};
app.MapPost("/upload", async (HttpRequest request) =>
{
if (!request.HasFormContentType)
return Results.BadRequest("Expected multipart/form-data.");
var form = await request.ReadFormAsync();
var file = form.Files.GetFile("file");
if (file is null || file.Length == 0)
return Results.BadRequest("No file provided.");
if (file.Length > 10 * 1024 * 1024)
return Results.Problem("File size exceeds 10 MB limit.", statusCode: 413);
var ext = Path.GetExtension(file.FileName);
if (!allowedExtensions.Contains(ext))
return Results.Problem($"File type '{ext}' is not supported.", statusCode: 415);
var fileId = Guid.NewGuid().ToString("N");
using var ms = new MemoryStream();
await file.CopyToAsync(ms);
uploadedFiles[fileId] = (ms.ToArray(), file.ContentType, file.FileName);
var url = $"{request.Scheme}://{request.Host}/uploads/{fileId}/{Uri.EscapeDataString(file.FileName)}";
return Results.Ok(new { url });
});
app.MapGet("/uploads/{fileId}/{fileName}", (string fileId, string fileName) =>
{
if (!uploadedFiles.TryGetValue(fileId, out var entry))
return Results.NotFound();
return Results.File(entry.Content, entry.ContentType, entry.FileName);
});
await app.RunAsync();