Spaces:
Sleeping
Sleeping
Commit ·
90e1fa5
1
Parent(s): 8b1a825
gemini integration
Browse files
FlowAPI.Application/DTOs/AI/AIDtos.cs
CHANGED
|
@@ -30,6 +30,7 @@ namespace FlowAPI.Application.DTOs.AI
|
|
| 30 |
|
| 31 |
public class AICanvasAssistResponseDto
|
| 32 |
{
|
|
|
|
| 33 |
public List<NodeDto> NewNodes { get; set; } = new();
|
| 34 |
public List<EdgeDto> NewEdges { get; set; } = new();
|
| 35 |
}
|
|
|
|
| 30 |
|
| 31 |
public class AICanvasAssistResponseDto
|
| 32 |
{
|
| 33 |
+
public string Explanation { get; set; } = string.Empty;
|
| 34 |
public List<NodeDto> NewNodes { get; set; } = new();
|
| 35 |
public List<EdgeDto> NewEdges { get; set; } = new();
|
| 36 |
}
|
FlowAPI.Application/Services/AIService.cs
CHANGED
|
@@ -9,8 +9,11 @@ using System.Text.Encodings.Web;
|
|
| 9 |
using System.Text.Unicode;
|
| 10 |
using System.Text.RegularExpressions;
|
| 11 |
using System.Threading.Tasks;
|
|
|
|
| 12 |
using FlowAPI.Application.DTOs.AI;
|
| 13 |
using FlowAPI.Application.DTOs.Graph;
|
|
|
|
|
|
|
| 14 |
using FlowAPI.Application.Interfaces;
|
| 15 |
using Microsoft.Extensions.Configuration;
|
| 16 |
|
|
@@ -24,6 +27,83 @@ namespace FlowAPI.Application.Services
|
|
| 24 |
private readonly IGraphService _graphService;
|
| 25 |
private readonly IGeminiBridgeManager _bridgeManager;
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
public AIService(IUserRepository userRepo, IGraphRepository graphRepo, IConfiguration config, IGraphService graphService, IGeminiBridgeManager bridgeManager)
|
| 28 |
{
|
| 29 |
_userRepo = userRepo;
|
|
@@ -33,19 +113,374 @@ namespace FlowAPI.Application.Services
|
|
| 33 |
_bridgeManager = bridgeManager;
|
| 34 |
}
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
public async Task<AIPathResponseDto> GenerateAlternativePathAsync(GenerateAlternativeRequestDto request)
|
| 37 |
{
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
}
|
| 40 |
|
| 41 |
public async Task<FullGraphResponseDto> GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request)
|
| 42 |
{
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
}
|
| 45 |
|
| 46 |
public async Task<AICanvasAssistResponseDto> CanvasAssistAsync(AICanvasAssistRequestDto request)
|
| 47 |
{
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
}
|
| 50 |
|
| 51 |
private string CleanJson(string text)
|
|
@@ -220,58 +655,39 @@ namespace FlowAPI.Application.Services
|
|
| 220 |
}
|
| 221 |
}
|
| 222 |
|
| 223 |
-
private class
|
| 224 |
-
{
|
| 225 |
-
public string Title { get; set; } = string.Empty;
|
| 226 |
-
public string Description { get; set; } = string.Empty;
|
| 227 |
-
public List<AINodeDto> Nodes { get; set; } = new();
|
| 228 |
-
public List<AIEdgeDto> Edges { get; set; } = new();
|
| 229 |
-
}
|
| 230 |
-
|
| 231 |
-
private class AIOptionDto
|
| 232 |
{
|
| 233 |
public string Id { get; set; } = string.Empty;
|
| 234 |
public string Label { get; set; } = string.Empty;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
}
|
| 236 |
|
| 237 |
-
private class
|
| 238 |
-
{
|
| 239 |
-
public string Id { get; set; } = string.Empty;
|
| 240 |
-
public string Label { get; set; } = string.Empty;
|
| 241 |
-
public double PosX { get; set; }
|
| 242 |
-
public double PosY { get; set; }
|
| 243 |
-
public string? Type { get; set; }
|
| 244 |
-
public List<AIOptionDto>? Options { get; set; }
|
| 245 |
-
}
|
| 246 |
-
|
| 247 |
-
private class AIEdgeDto
|
| 248 |
{
|
| 249 |
public string From { get; set; } = string.Empty;
|
| 250 |
public string To { get; set; } = string.Empty;
|
|
|
|
| 251 |
public string? Condition { get; set; }
|
| 252 |
}
|
| 253 |
|
| 254 |
-
private class
|
| 255 |
{
|
| 256 |
-
public
|
| 257 |
-
public
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
{
|
| 262 |
-
public string Id { get; set; } = string.Empty;
|
| 263 |
-
public string Label { get; set; } = string.Empty;
|
| 264 |
-
public double PosX { get; set; }
|
| 265 |
-
public double PosY { get; set; }
|
| 266 |
-
public string? Type { get; set; }
|
| 267 |
-
public List<AIOptionDto>? Options { get; set; }
|
| 268 |
}
|
| 269 |
|
| 270 |
-
private class
|
| 271 |
{
|
| 272 |
-
public string
|
| 273 |
-
public
|
| 274 |
-
public
|
| 275 |
}
|
| 276 |
}
|
| 277 |
}
|
|
|
|
| 9 |
using System.Text.Unicode;
|
| 10 |
using System.Text.RegularExpressions;
|
| 11 |
using System.Threading.Tasks;
|
| 12 |
+
using System.Net.Http;
|
| 13 |
using FlowAPI.Application.DTOs.AI;
|
| 14 |
using FlowAPI.Application.DTOs.Graph;
|
| 15 |
+
using FlowAPI.Application.DTOs.TaskNode;
|
| 16 |
+
using FlowAPI.Application.DTOs.Edge;
|
| 17 |
using FlowAPI.Application.Interfaces;
|
| 18 |
using Microsoft.Extensions.Configuration;
|
| 19 |
|
|
|
|
| 27 |
private readonly IGraphService _graphService;
|
| 28 |
private readonly IGeminiBridgeManager _bridgeManager;
|
| 29 |
|
| 30 |
+
private const string GoalResponseSchema = @"
|
| 31 |
+
{
|
| 32 |
+
""type"": ""object"",
|
| 33 |
+
""properties"": {
|
| 34 |
+
""title"": { ""type"": ""string"" },
|
| 35 |
+
""description"": { ""type"": ""string"" },
|
| 36 |
+
""explanation"": { ""type"": ""string"" },
|
| 37 |
+
""nodes"": {
|
| 38 |
+
""type"": ""array"",
|
| 39 |
+
""items"": {
|
| 40 |
+
""type"": ""object"",
|
| 41 |
+
""properties"": {
|
| 42 |
+
""id"": { ""type"": ""string"" },
|
| 43 |
+
""label"": { ""type"": ""string"" },
|
| 44 |
+
""description"": { ""type"": ""string"" },
|
| 45 |
+
""type"": { ""type"": ""string"", ""enum"": [""sketch"", ""condition"", ""habit""] },
|
| 46 |
+
""decision"": { ""type"": ""string"" },
|
| 47 |
+
""dependsOn"": { ""type"": ""string"" },
|
| 48 |
+
""color"": { ""type"": ""string"", ""enum"": [""default"", ""yellow"", ""blue"", ""green"", ""pink"", ""purple"", ""orange"", ""white""] }
|
| 49 |
+
},
|
| 50 |
+
""required"": [""id"", ""label"", ""description"", ""type""]
|
| 51 |
+
}
|
| 52 |
+
},
|
| 53 |
+
""edges"": {
|
| 54 |
+
""type"": ""array"",
|
| 55 |
+
""items"": {
|
| 56 |
+
""type"": ""object"",
|
| 57 |
+
""properties"": {
|
| 58 |
+
""from"": { ""type"": ""string"" },
|
| 59 |
+
""to"": { ""type"": ""string"" },
|
| 60 |
+
""relationship"": { ""type"": ""string"", ""enum"": [""sequential"", ""subgoal""] },
|
| 61 |
+
""condition"": { ""type"": ""string"" }
|
| 62 |
+
},
|
| 63 |
+
""required"": [""from"", ""to"", ""relationship""]
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
},
|
| 67 |
+
""required"": [""title"", ""description"", ""explanation"", ""nodes"", ""edges""]
|
| 68 |
+
}";
|
| 69 |
+
|
| 70 |
+
private const string AssistResponseSchema = @"
|
| 71 |
+
{
|
| 72 |
+
""type"": ""object"",
|
| 73 |
+
""properties"": {
|
| 74 |
+
""explanation"": { ""type"": ""string"" },
|
| 75 |
+
""newNodes"": {
|
| 76 |
+
""type"": ""array"",
|
| 77 |
+
""items"": {
|
| 78 |
+
""type"": ""object"",
|
| 79 |
+
""properties"": {
|
| 80 |
+
""id"": { ""type"": ""string"" },
|
| 81 |
+
""label"": { ""type"": ""string"" },
|
| 82 |
+
""description"": { ""type"": ""string"" },
|
| 83 |
+
""type"": { ""type"": ""string"", ""enum"": [""sketch"", ""condition"", ""habit""] },
|
| 84 |
+
""decision"": { ""type"": ""string"" },
|
| 85 |
+
""color"": { ""type"": ""string"", ""enum"": [""default"", ""yellow"", ""blue"", ""green"", ""pink"", ""purple"", ""orange"", ""white""] }
|
| 86 |
+
},
|
| 87 |
+
""required"": [""id"", ""label"", ""description"", ""type""]
|
| 88 |
+
}
|
| 89 |
+
},
|
| 90 |
+
""newEdges"": {
|
| 91 |
+
""type"": ""array"",
|
| 92 |
+
""items"": {
|
| 93 |
+
""type"": ""object"",
|
| 94 |
+
""properties"": {
|
| 95 |
+
""from"": { ""type"": ""string"" },
|
| 96 |
+
""to"": { ""type"": ""string"" },
|
| 97 |
+
""relationship"": { ""type"": ""string"", ""enum"": [""sequential"", ""subgoal""] },
|
| 98 |
+
""condition"": { ""type"": ""string"" }
|
| 99 |
+
},
|
| 100 |
+
""required"": [""from"", ""to"", ""relationship""]
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
},
|
| 104 |
+
""required"": [""explanation"", ""newNodes"", ""newEdges""]
|
| 105 |
+
}";
|
| 106 |
+
|
| 107 |
public AIService(IUserRepository userRepo, IGraphRepository graphRepo, IConfiguration config, IGraphService graphService, IGeminiBridgeManager bridgeManager)
|
| 108 |
{
|
| 109 |
_userRepo = userRepo;
|
|
|
|
| 113 |
_bridgeManager = bridgeManager;
|
| 114 |
}
|
| 115 |
|
| 116 |
+
private async Task<string> CallGeminiApiAsync(string prompt, string? systemInstruction = null, string? responseSchemaJson = null)
|
| 117 |
+
{
|
| 118 |
+
var apiKey = _config["Gemini:ApiKey"] ?? Environment.GetEnvironmentVariable("GEMINI_API_KEY");
|
| 119 |
+
if (string.IsNullOrEmpty(apiKey))
|
| 120 |
+
{
|
| 121 |
+
throw new Exception("Gemini API key is not configured. Please add Gemini:ApiKey to appsettings.json or set GEMINI_API_KEY environment variable.");
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
var model = _config["Gemini:Model"] ?? "gemini-1.5-flash";
|
| 125 |
+
var url = $"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={apiKey}";
|
| 126 |
+
|
| 127 |
+
var parts = new List<object> { new { text = prompt } };
|
| 128 |
+
var contents = new[] { new { parts = parts } };
|
| 129 |
+
|
| 130 |
+
object? generationConfig = null;
|
| 131 |
+
if (responseSchemaJson != null)
|
| 132 |
+
{
|
| 133 |
+
generationConfig = new
|
| 134 |
+
{
|
| 135 |
+
responseMimeType = "application/json",
|
| 136 |
+
responseSchema = JsonSerializer.Deserialize<object>(responseSchemaJson)
|
| 137 |
+
};
|
| 138 |
+
}
|
| 139 |
+
else
|
| 140 |
+
{
|
| 141 |
+
generationConfig = new
|
| 142 |
+
{
|
| 143 |
+
responseMimeType = "application/json"
|
| 144 |
+
};
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
object requestBody;
|
| 148 |
+
if (!string.IsNullOrEmpty(systemInstruction))
|
| 149 |
+
{
|
| 150 |
+
requestBody = new
|
| 151 |
+
{
|
| 152 |
+
contents = contents,
|
| 153 |
+
systemInstruction = new { parts = new[] { new { text = systemInstruction } } },
|
| 154 |
+
generationConfig = generationConfig
|
| 155 |
+
};
|
| 156 |
+
}
|
| 157 |
+
else
|
| 158 |
+
{
|
| 159 |
+
requestBody = new
|
| 160 |
+
{
|
| 161 |
+
contents = contents,
|
| 162 |
+
generationConfig = generationConfig
|
| 163 |
+
};
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
using var httpClient = new HttpClient();
|
| 167 |
+
var jsonPayload = JsonSerializer.Serialize(requestBody);
|
| 168 |
+
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
|
| 169 |
+
|
| 170 |
+
var response = await httpClient.PostAsync(url, content);
|
| 171 |
+
var responseString = await response.Content.ReadAsStringAsync();
|
| 172 |
+
|
| 173 |
+
if (!response.IsSuccessStatusCode)
|
| 174 |
+
{
|
| 175 |
+
throw new Exception($"Gemini API error (Status {response.StatusCode}): {responseString}");
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
using var doc = JsonDocument.Parse(responseString);
|
| 179 |
+
var textResponse = doc.RootElement
|
| 180 |
+
.GetProperty("candidates")[0]
|
| 181 |
+
.GetProperty("content")
|
| 182 |
+
.GetProperty("parts")[0]
|
| 183 |
+
.GetProperty("text")
|
| 184 |
+
.GetString();
|
| 185 |
+
|
| 186 |
+
if (string.IsNullOrEmpty(textResponse))
|
| 187 |
+
{
|
| 188 |
+
throw new Exception("Empty response received from Gemini API.");
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
return textResponse;
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
public async Task<AIPathResponseDto> GenerateAlternativePathAsync(GenerateAlternativeRequestDto request)
|
| 195 |
{
|
| 196 |
+
var graph = await _graphRepo.GetByIdWithDetailsAsync(request.GraphId);
|
| 197 |
+
if (graph == null)
|
| 198 |
+
{
|
| 199 |
+
throw new Exception("Graph not found.");
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
var failedNode = graph.Nodes.FirstOrDefault(n => n.Id == request.FailedNodeId);
|
| 203 |
+
if (failedNode == null)
|
| 204 |
+
{
|
| 205 |
+
throw new Exception("Target node not found.");
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
var prompt = $"В нашей дорожной карте произошел сбой на шаге: \"{failedNode.Label}\" (Описание: \"{failedNode.Description}\").\n" +
|
| 209 |
+
$"Предложи альтернативный обходной путь из 2-3 шагов, чтобы пользователь мог продолжить движение к цели.\n" +
|
| 210 |
+
$"Предоставь только новые шаги (NewNodes) и новые связи (NewEdges) для их интеграции.";
|
| 211 |
+
|
| 212 |
+
var systemInstruction = "You are a Roadmap Strategist AI Agent. You design failover alternative paths for failed tasks in a roadmap.";
|
| 213 |
+
var responseJson = await CallGeminiApiAsync(prompt, systemInstruction, AssistResponseSchema);
|
| 214 |
+
responseJson = CleanJson(responseJson);
|
| 215 |
+
|
| 216 |
+
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
| 217 |
+
var rawAssist = JsonSerializer.Deserialize<GeminiAssistResponse>(responseJson, options)
|
| 218 |
+
?? throw new Exception("Failed to deserialize AI alternative path response from Gemini.");
|
| 219 |
+
|
| 220 |
+
var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
|
| 221 |
+
idMap[failedNode.Id.ToString()] = failedNode.Id;
|
| 222 |
+
|
| 223 |
+
foreach (var node in rawAssist.NewNodes)
|
| 224 |
+
{
|
| 225 |
+
if (!idMap.ContainsKey(node.Id))
|
| 226 |
+
{
|
| 227 |
+
idMap[node.Id] = Guid.NewGuid();
|
| 228 |
+
}
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
var mappedNodes = rawAssist.NewNodes.Select(node => new TaskNodeResponseDto
|
| 232 |
+
{
|
| 233 |
+
Id = idMap[node.Id],
|
| 234 |
+
Label = node.Label,
|
| 235 |
+
PosX = failedNode.PosX + 300,
|
| 236 |
+
PosY = failedNode.PosY + 150,
|
| 237 |
+
State = FlowAPI.Domain.Enums.NodeState.Pending,
|
| 238 |
+
CreatedAt = DateTime.UtcNow
|
| 239 |
+
}).ToList();
|
| 240 |
+
|
| 241 |
+
var mappedEdges = new List<EdgeResponseDto>();
|
| 242 |
+
foreach (var edge in rawAssist.NewEdges)
|
| 243 |
+
{
|
| 244 |
+
if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid))
|
| 245 |
+
{
|
| 246 |
+
mappedEdges.Add(new EdgeResponseDto
|
| 247 |
+
{
|
| 248 |
+
Id = Guid.NewGuid(),
|
| 249 |
+
FromNodeId = fromGuid,
|
| 250 |
+
ToNodeId = toGuid,
|
| 251 |
+
Condition = edge.Relationship == "subgoal" ? "subgoals-source" : "True"
|
| 252 |
+
});
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
return new AIPathResponseDto
|
| 257 |
+
{
|
| 258 |
+
SuggestedNodes = mappedNodes,
|
| 259 |
+
SuggestedEdges = mappedEdges
|
| 260 |
+
};
|
| 261 |
}
|
| 262 |
|
| 263 |
public async Task<FullGraphResponseDto> GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request)
|
| 264 |
{
|
| 265 |
+
if (string.IsNullOrWhiteSpace(request.Goal))
|
| 266 |
+
{
|
| 267 |
+
throw new ArgumentException("Goal description cannot be empty.");
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
// 1. Build prompt for Gemini
|
| 271 |
+
var prompt = $"Пользователь хочет достичь следующей цели: \"{request.Goal}\". " +
|
| 272 |
+
"Составь подробную иерархическую дорожную карту с последовательными шагами, ветвлениями решений (condition) и полезными привычками (habit). " +
|
| 273 |
+
"Каждому узлу (Node) дай понятное короткое название и подробное описание (как файлы в папках воркспейса разработчика), чтобы сразу загружать нужный контекст. " +
|
| 274 |
+
"В поле explanation напиши подробный вдохновляющий ответ от лица Агента-Стратега, рассказывающий о шагах и структуре сгенерированного плана.";
|
| 275 |
+
|
| 276 |
+
// 2. Call Gemini API
|
| 277 |
+
var systemInstruction = "You are a Roadmap Strategist AI Agent. You design detailed, clean, and logical task roadmaps represented as graphs (nodes and edges). You write rich, folder-workspace style descriptions for every node.";
|
| 278 |
+
var responseJson = await CallGeminiApiAsync(prompt, systemInstruction, GoalResponseSchema);
|
| 279 |
+
responseJson = CleanJson(responseJson);
|
| 280 |
+
|
| 281 |
+
// 3. Deserialize response
|
| 282 |
+
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
| 283 |
+
var rawGraph = JsonSerializer.Deserialize<GeminiGoalResponse>(responseJson, options)
|
| 284 |
+
?? throw new Exception("Failed to deserialize generated roadmap graph from Gemini.");
|
| 285 |
+
|
| 286 |
+
// 4. Create the Graph record in the database first
|
| 287 |
+
var createDto = new CreateGraphDto
|
| 288 |
+
{
|
| 289 |
+
Title = string.IsNullOrWhiteSpace(rawGraph.Title) ? request.Goal : rawGraph.Title,
|
| 290 |
+
Description = string.IsNullOrWhiteSpace(rawGraph.Description) ? "Дорожная карта, сгенерированная AI Агентом" : rawGraph.Description
|
| 291 |
+
};
|
| 292 |
+
var graphResponse = await _graphService.CreateAsync(createDto, request.UserId);
|
| 293 |
+
var graphId = graphResponse.Id;
|
| 294 |
+
|
| 295 |
+
// 5. Map Gemini string IDs to GUIDs
|
| 296 |
+
var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
|
| 297 |
+
foreach (var node in rawGraph.Nodes)
|
| 298 |
+
{
|
| 299 |
+
if (!idMap.ContainsKey(node.Id))
|
| 300 |
+
{
|
| 301 |
+
idMap[node.Id] = Guid.NewGuid();
|
| 302 |
+
}
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
// 6. Construct DTO lists
|
| 306 |
+
var mappedNodes = rawGraph.Nodes.Select(node => new NodeDto
|
| 307 |
+
{
|
| 308 |
+
Id = idMap[node.Id],
|
| 309 |
+
Label = node.Label,
|
| 310 |
+
PosX = 0,
|
| 311 |
+
PosY = 0,
|
| 312 |
+
Type = node.Type ?? "sketch",
|
| 313 |
+
State = 0, // Pending
|
| 314 |
+
Decision = node.Decision,
|
| 315 |
+
Description = node.Description,
|
| 316 |
+
Color = node.Color ?? "default",
|
| 317 |
+
IsPinned = false
|
| 318 |
+
}).ToList();
|
| 319 |
+
|
| 320 |
+
var mappedEdges = new List<EdgeDto>();
|
| 321 |
+
foreach (var edge in rawGraph.Edges)
|
| 322 |
+
{
|
| 323 |
+
if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid))
|
| 324 |
+
{
|
| 325 |
+
mappedEdges.Add(new EdgeDto
|
| 326 |
+
{
|
| 327 |
+
Id = Guid.NewGuid(),
|
| 328 |
+
FromNodeId = fromGuid,
|
| 329 |
+
ToNodeId = toGuid,
|
| 330 |
+
Condition = edge.Relationship == "subgoal"
|
| 331 |
+
? "subgoals-source"
|
| 332 |
+
: (string.IsNullOrWhiteSpace(edge.Condition) ? "True" : edge.Condition)
|
| 333 |
+
});
|
| 334 |
+
}
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
// 7. Calculate layouts
|
| 338 |
+
ApplyBeautifulLayout(mappedNodes, mappedEdges);
|
| 339 |
+
|
| 340 |
+
// 8. Save fully generated graph to DB
|
| 341 |
+
var fullGraphDto = new FullGraphResponseDto
|
| 342 |
+
{
|
| 343 |
+
Id = graphId,
|
| 344 |
+
UserId = request.UserId,
|
| 345 |
+
Title = createDto.Title,
|
| 346 |
+
Description = createDto.Description,
|
| 347 |
+
CreatedAt = DateTime.UtcNow,
|
| 348 |
+
Nodes = mappedNodes,
|
| 349 |
+
Edges = mappedEdges
|
| 350 |
+
};
|
| 351 |
+
|
| 352 |
+
await _graphService.SaveFullGraphAsync(graphId, fullGraphDto, request.UserId);
|
| 353 |
+
|
| 354 |
+
// 9. Update roadmap description with explanation from strategist
|
| 355 |
+
var graphEntity = await _graphRepo.GetByIdAsync(graphId);
|
| 356 |
+
if (graphEntity != null)
|
| 357 |
+
{
|
| 358 |
+
graphEntity.Description = rawGraph.Explanation;
|
| 359 |
+
await _graphRepo.UpdateAsync(graphEntity);
|
| 360 |
+
fullGraphDto.Description = rawGraph.Explanation;
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
return fullGraphDto;
|
| 364 |
}
|
| 365 |
|
| 366 |
public async Task<AICanvasAssistResponseDto> CanvasAssistAsync(AICanvasAssistRequestDto request)
|
| 367 |
{
|
| 368 |
+
var graph = await _graphRepo.GetByIdWithDetailsAsync(request.GraphId);
|
| 369 |
+
if (graph == null)
|
| 370 |
+
{
|
| 371 |
+
throw new Exception("Graph not found.");
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
// 1. Serialize existing nodes and edges for Gemini context
|
| 375 |
+
var existingNodesText = new StringBuilder();
|
| 376 |
+
existingNodesText.AppendLine("Текущие узлы на доске:");
|
| 377 |
+
foreach (var node in graph.Nodes)
|
| 378 |
+
{
|
| 379 |
+
existingNodesText.AppendLine($"- ID: \"{node.Id}\", Название: \"{node.Label}\", Тип: \"{node.Type}\", Состояние: \"{node.State}\", Описание: \"{node.Description}\"");
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
var existingEdgesText = new StringBuilder();
|
| 383 |
+
existingEdgesText.AppendLine("Текущие связи на доске:");
|
| 384 |
+
foreach (var edge in graph.Edges)
|
| 385 |
+
{
|
| 386 |
+
existingEdgesText.AppendLine($"- От: \"{edge.FromNodeId}\", К: \"{edge.ToNodeId}\", Условие: \"{edge.Condition}\"");
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
// 2. Build the prompt
|
| 390 |
+
var prompt = $"Пользователь делает запрос к Агенту-Стратегу на изменение холста дорожной карты:\n" +
|
| 391 |
+
$"Запрос пользователя: \"{request.UserPrompt}\"\n\n" +
|
| 392 |
+
$"{existingNodesText}\n" +
|
| 393 |
+
$"{existingEdgesText}\n\n" +
|
| 394 |
+
$"Твоя задача — сгенерировать новые узлы (NewNodes) и новые связи (NewEdges) для добавления на холст, чтобы удовлетворить запрос пользователя.\n" +
|
| 395 |
+
$"Связи 'relationship' могут быть 'sequential' или 'subgoal'.\n" +
|
| 396 |
+
$"Придумывай новые уникальные буквенно-цифровые ID для новых узлов (например: new_step_1).\n" +
|
| 397 |
+
$"Связи могут идти от существующих узлов к новым, от новых к новым, или от новых к существующим. Используй ID существующих узлов без изменений, если ссылаешься на них.\n" +
|
| 398 |
+
$"В поле explanation подробно опиши в формате markdown, что именно и почему ты добавил на холст.";
|
| 399 |
+
|
| 400 |
+
var systemInstruction = "You are a Roadmap Strategist AI Agent. You modify and extend existing roadmaps. You analyze the current canvas state and user instructions, then return ONLY the newly added nodes and edges in JSON format, along with a detailed explanation of changes.";
|
| 401 |
+
var responseJson = await CallGeminiApiAsync(prompt, systemInstruction, AssistResponseSchema);
|
| 402 |
+
responseJson = CleanJson(responseJson);
|
| 403 |
+
|
| 404 |
+
// 3. Deserialize Gemini response
|
| 405 |
+
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
| 406 |
+
var rawAssist = JsonSerializer.Deserialize<GeminiAssistResponse>(responseJson, options)
|
| 407 |
+
?? throw new Exception("Failed to deserialize AI Assist response from Gemini.");
|
| 408 |
+
|
| 409 |
+
// 4. Map string IDs to Guids
|
| 410 |
+
var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
|
| 411 |
+
|
| 412 |
+
// Map existing node Guids to themselves so they remain stable
|
| 413 |
+
foreach (var node in graph.Nodes)
|
| 414 |
+
{
|
| 415 |
+
idMap[node.Id.ToString()] = node.Id;
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
// Generate new Guids for new node IDs
|
| 419 |
+
foreach (var node in rawAssist.NewNodes)
|
| 420 |
+
{
|
| 421 |
+
if (!idMap.ContainsKey(node.Id))
|
| 422 |
+
{
|
| 423 |
+
idMap[node.Id] = Guid.NewGuid();
|
| 424 |
+
}
|
| 425 |
+
}
|
| 426 |
+
|
| 427 |
+
// 5. Construct DTO nodes list
|
| 428 |
+
var mappedNewNodes = rawAssist.NewNodes.Select(node => new NodeDto
|
| 429 |
+
{
|
| 430 |
+
Id = idMap[node.Id],
|
| 431 |
+
Label = node.Label,
|
| 432 |
+
PosX = 0,
|
| 433 |
+
PosY = 0,
|
| 434 |
+
Type = node.Type ?? "sketch",
|
| 435 |
+
State = 0, // Pending
|
| 436 |
+
Decision = node.Decision,
|
| 437 |
+
Description = node.Description,
|
| 438 |
+
Color = node.Color ?? "default",
|
| 439 |
+
IsPinned = false
|
| 440 |
+
}).ToList();
|
| 441 |
+
|
| 442 |
+
// 6. Construct DTO edges list
|
| 443 |
+
var mappedNewEdges = new List<EdgeDto>();
|
| 444 |
+
foreach (var edge in rawAssist.NewEdges)
|
| 445 |
+
{
|
| 446 |
+
if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid))
|
| 447 |
+
{
|
| 448 |
+
mappedNewEdges.Add(new EdgeDto
|
| 449 |
+
{
|
| 450 |
+
Id = Guid.NewGuid(),
|
| 451 |
+
FromNodeId = fromGuid,
|
| 452 |
+
ToNodeId = toGuid,
|
| 453 |
+
Condition = edge.Relationship == "subgoal"
|
| 454 |
+
? "subgoals-source"
|
| 455 |
+
: (string.IsNullOrWhiteSpace(edge.Condition) ? "True" : edge.Condition)
|
| 456 |
+
});
|
| 457 |
+
}
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
// 7. Positioning/Layout:
|
| 461 |
+
// Find max PosY of existing nodes to place the new ones below
|
| 462 |
+
double maxPosY = 100;
|
| 463 |
+
if (graph.Nodes.Count > 0)
|
| 464 |
+
{
|
| 465 |
+
maxPosY = graph.Nodes.Max(n => n.PosY);
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
// Run layout engine on the new nodes/edges
|
| 469 |
+
ApplyBeautifulLayout(mappedNewNodes, mappedNewEdges);
|
| 470 |
+
|
| 471 |
+
// Shift all new nodes below the existing nodes
|
| 472 |
+
double shiftY = maxPosY + 250;
|
| 473 |
+
foreach (var node in mappedNewNodes)
|
| 474 |
+
{
|
| 475 |
+
node.PosY += shiftY;
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
return new AICanvasAssistResponseDto
|
| 479 |
+
{
|
| 480 |
+
Explanation = rawAssist.Explanation,
|
| 481 |
+
NewNodes = mappedNewNodes,
|
| 482 |
+
NewEdges = mappedNewEdges
|
| 483 |
+
};
|
| 484 |
}
|
| 485 |
|
| 486 |
private string CleanJson(string text)
|
|
|
|
| 655 |
}
|
| 656 |
}
|
| 657 |
|
| 658 |
+
private class GeminiNode
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 659 |
{
|
| 660 |
public string Id { get; set; } = string.Empty;
|
| 661 |
public string Label { get; set; } = string.Empty;
|
| 662 |
+
public string Description { get; set; } = string.Empty;
|
| 663 |
+
public string Type { get; set; } = "sketch";
|
| 664 |
+
public string? Decision { get; set; }
|
| 665 |
+
public string? DependsOn { get; set; }
|
| 666 |
+
public string? Color { get; set; }
|
| 667 |
}
|
| 668 |
|
| 669 |
+
private class GeminiEdge
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 670 |
{
|
| 671 |
public string From { get; set; } = string.Empty;
|
| 672 |
public string To { get; set; } = string.Empty;
|
| 673 |
+
public string Relationship { get; set; } = "sequential";
|
| 674 |
public string? Condition { get; set; }
|
| 675 |
}
|
| 676 |
|
| 677 |
+
private class GeminiGoalResponse
|
| 678 |
{
|
| 679 |
+
public string Title { get; set; } = string.Empty;
|
| 680 |
+
public string Description { get; set; } = string.Empty;
|
| 681 |
+
public string Explanation { get; set; } = string.Empty;
|
| 682 |
+
public List<GeminiNode> Nodes { get; set; } = new();
|
| 683 |
+
public List<GeminiEdge> Edges { get; set; } = new();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 684 |
}
|
| 685 |
|
| 686 |
+
private class GeminiAssistResponse
|
| 687 |
{
|
| 688 |
+
public string Explanation { get; set; } = string.Empty;
|
| 689 |
+
public List<GeminiNode> NewNodes { get; set; } = new();
|
| 690 |
+
public List<GeminiEdge> NewEdges { get; set; } = new();
|
| 691 |
}
|
| 692 |
}
|
| 693 |
}
|
FlowAPI/appsettings.json
CHANGED
|
@@ -22,6 +22,10 @@
|
|
| 22 |
"OpenAI": {
|
| 23 |
"ApiKey": ""
|
| 24 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
"Stripe": {
|
| 26 |
"SecretKey": "",
|
| 27 |
"WebhookSecret": ""
|
|
|
|
| 22 |
"OpenAI": {
|
| 23 |
"ApiKey": ""
|
| 24 |
},
|
| 25 |
+
"Gemini": {
|
| 26 |
+
"ApiKey": "AQ.Ab8RN6Iwv-IEeUHzINPr9-F7EstlZ28kTI55QjNbbzmDYWW-cw",
|
| 27 |
+
"Model": "gemini-1.5-flash"
|
| 28 |
+
},
|
| 29 |
"Stripe": {
|
| 30 |
"SecretKey": "",
|
| 31 |
"WebhookSecret": ""
|