-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAIIntegrationController.cs
More file actions
78 lines (70 loc) · 2.47 KB
/
Copy pathAIIntegrationController.cs
File metadata and controls
78 lines (70 loc) · 2.47 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
using AIIntegrationServer.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.AI;
using System.Text.Json;
namespace AIIntegrationServer.Controllers;
[ApiController]
public class AiIntegrationController(
IChatClient chatClient,
ILogger<AiIntegrationController> logger) : ControllerBase
{
[HttpPost("/api/ai/grid-column")]
public Task<IActionResult> GridColumn(
[FromBody] AIIntegrationRequest request,
CancellationToken cancellationToken)
=> RunAsync(
request,
new ChatOptions { Temperature = 0.7f },
"AI column request failed",
cancellationToken);
[HttpPost("/api/ai/assistant")]
public Task<IActionResult> Assistant(
[FromBody] AIIntegrationRequest request,
CancellationToken cancellationToken)
=> RunAsync(
request,
new ChatOptions
{
Temperature = 0.0f,
ResponseFormat = BuildAssistantResponseFormat(request.Data),
},
"AI assistant request failed",
cancellationToken
);
private async Task<IActionResult> RunAsync(
AIIntegrationRequest request,
ChatOptions options,
string errorMessage,
CancellationToken cancellationToken)
{
try
{
var response = await chatClient.GetResponseAsync(
[
new ChatMessage(ChatRole.System, request.Prompt.System),
new ChatMessage(ChatRole.User, request.Prompt.User),
],
options,
cancellationToken: cancellationToken);
var rawContent = response.Text ?? string.Empty;
return Ok(new AIIntegrationResponse { Content = rawContent });
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
logger.LogError(ex, errorMessage);
return StatusCode(502, new { error = "AI service failed." });
}
}
private static ChatResponseFormat BuildAssistantResponseFormat(JsonElement? data)
=> data is { ValueKind: JsonValueKind.Object } element
&& element.TryGetProperty("responseSchema", out var schema)
? new ChatResponseFormatJson(
schema,
"assistant_response",
"DevExtreme AI Assistant response schema")
: ChatResponseFormat.Json;
}