Spaces:
Sleeping
Sleeping
Commit ·
ecea7e2
1
Parent(s): 26471a0
fix: optimized Dockerfile, backend AI service, and gitignore
Browse files- .gitignore +0 -3
- Dockerfile +0 -36
- FlowAPI.Application/Services/AIService.cs +3 -466
.gitignore
CHANGED
|
@@ -16,6 +16,3 @@ bridge_log.txt
|
|
| 16 |
gemini_profile_bridge/
|
| 17 |
*.sqlite-shm
|
| 18 |
*.sqlite-wal
|
| 19 |
-
# Ignore SQLite database files to avoid checking them in
|
| 20 |
-
taskflow.db
|
| 21 |
-
/app/data/
|
|
|
|
| 16 |
gemini_profile_bridge/
|
| 17 |
*.sqlite-shm
|
| 18 |
*.sqlite-wal
|
|
|
|
|
|
|
|
|
Dockerfile
CHANGED
|
@@ -20,44 +20,8 @@ WORKDIR /app
|
|
| 20 |
EXPOSE 8080
|
| 21 |
EXPOSE 8081
|
| 22 |
|
| 23 |
-
# Install Python, pip, and system dependencies for Camoufox (Playwright/Firefox)
|
| 24 |
-
RUN apt-get update && apt-get install -y \
|
| 25 |
-
python3 \
|
| 26 |
-
python3-pip \
|
| 27 |
-
python3-venv \
|
| 28 |
-
curl \
|
| 29 |
-
libgtk-3-0 \
|
| 30 |
-
libasound2 \
|
| 31 |
-
libdbus-1-3 \
|
| 32 |
-
libx11-xcb1 \
|
| 33 |
-
libxcomposite1 \
|
| 34 |
-
libxdamage1 \
|
| 35 |
-
libxrandr2 \
|
| 36 |
-
libxtst6 \
|
| 37 |
-
libnss3 \
|
| 38 |
-
libatk1.0-0 \
|
| 39 |
-
libatk-bridge2.0-0 \
|
| 40 |
-
libdrm2 \
|
| 41 |
-
libgbm1 \
|
| 42 |
-
libxkbcommon0 \
|
| 43 |
-
libpango-1.0-0 \
|
| 44 |
-
libcairo2 \
|
| 45 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 46 |
-
|
| 47 |
-
# Set up python virtual environment to install packages cleanly
|
| 48 |
-
RUN python3 -m venv /opt/venv
|
| 49 |
-
ENV PATH="/opt/venv/bin:$PATH"
|
| 50 |
-
|
| 51 |
-
# Install camoufox python library and its dependencies
|
| 52 |
-
RUN pip3 install --no-cache-dir camoufox
|
| 53 |
-
# Pre-download Camoufox/Playwright browser engines so they are ready
|
| 54 |
-
RUN python3 -m camoufox fetch
|
| 55 |
-
|
| 56 |
# Copy published .NET app
|
| 57 |
COPY --from=build /app/publish .
|
| 58 |
|
| 59 |
-
# Explicitly copy the python bridge script to ensure it is in the run directory
|
| 60 |
-
COPY --from=build /src/FlowAPI/gemini_bridge.py .
|
| 61 |
-
|
| 62 |
# Set entrypoint
|
| 63 |
ENTRYPOINT ["dotnet", "FlowAPI.dll"]
|
|
|
|
| 20 |
EXPOSE 8080
|
| 21 |
EXPOSE 8081
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
# Copy published .NET app
|
| 24 |
COPY --from=build /app/publish .
|
| 25 |
|
|
|
|
|
|
|
|
|
|
| 26 |
# Set entrypoint
|
| 27 |
ENTRYPOINT ["dotnet", "FlowAPI.dll"]
|
FlowAPI.Application/Services/AIService.cs
CHANGED
|
@@ -35,480 +35,17 @@ namespace FlowAPI.Application.Services
|
|
| 35 |
|
| 36 |
public async Task<AIPathResponseDto> GenerateAlternativePathAsync(GenerateAlternativeRequestDto request)
|
| 37 |
{
|
| 38 |
-
|
| 39 |
-
var graph = await _graphRepo.GetByIdAsync(request.GraphId);
|
| 40 |
-
if (graph == null) throw new Exception("Graph not found.");
|
| 41 |
-
|
| 42 |
-
// 2. Check Premium Status (REQ-03) - Bypassed for regular users for now
|
| 43 |
-
var user = await _userRepo.GetByIdAsync(graph.UserId);
|
| 44 |
-
if (user == null)
|
| 45 |
-
{
|
| 46 |
-
throw new Exception("User not found.");
|
| 47 |
-
}
|
| 48 |
-
|
| 49 |
-
// 3. Prepare AI Prompt
|
| 50 |
-
string prompt = $"Given a goal graph '{graph.Title}', the node {request.FailedNodeId} is blocked. " +
|
| 51 |
-
"Generate an alternative sequence of 3-5 steps to bypass this obstacle.";
|
| 52 |
-
|
| 53 |
-
return new AIPathResponseDto
|
| 54 |
-
{
|
| 55 |
-
SuggestedNodes = new()
|
| 56 |
-
{
|
| 57 |
-
new() { Id = Guid.NewGuid(), Label = "AI: Search for alternative resources", PosX = 100, PosY = 100 },
|
| 58 |
-
new() { Id = Guid.NewGuid(), Label = "AI: Contact external consultant", PosX = 200, PosY = 150 }
|
| 59 |
-
}
|
| 60 |
-
};
|
| 61 |
}
|
| 62 |
|
| 63 |
public async Task<FullGraphResponseDto> GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request)
|
| 64 |
{
|
| 65 |
-
|
| 66 |
-
// 1. Check User Premium Status or just allow AI generation
|
| 67 |
-
var user = await _userRepo.GetByIdAsync(request.UserId);
|
| 68 |
-
if (user == null) throw new Exception("User not found.");
|
| 69 |
-
|
| 70 |
-
// 2. Formulate Prompt for Gemini
|
| 71 |
-
string promptText = $"You are an expert strategist and goal decomposition AI. Your task is to break down the user's goal into a sequential, logical tree or path of actionable tasks in Ukrainian.\n\n" +
|
| 72 |
-
$"User Goal: \"{request.Goal}\"\n\n" +
|
| 73 |
-
$"Create a structured, detailed roadmap of 6 to 12 sequential tasks (nodes) and their directed connections (edges) that lead the user to their goal.\n\n" +
|
| 74 |
-
$"Guidelines:\n" +
|
| 75 |
-
$"- Ensure all labels and description text are written in clear, natural Ukrainian.\n" +
|
| 76 |
-
$"- Avoid short, basic, generic titles. Write detailed, rich, and highly actionable labels for each node.\n" +
|
| 77 |
-
$"- Do NOT use the \"habit\" type under any circumstances. It is strictly forbidden. The allowed node types are \"sketch\" (standard task/goal) and \"condition\" (a decision/choice branch).\n" +
|
| 78 |
-
$"- Use \"condition\" nodes appropriately and dynamically when the path requires making a choice, evaluating options, or taking a different approach depending on criteria (e.g. \"Чи є досвід у програмуванні?\" or \"Вибір платформи\").\n" +
|
| 79 |
-
$"- A \"condition\" node can have custom choices (options) instead of just simple binary branches! To specify custom choices/branches for a condition node, include an \"options\" array containing option objects with custom \"id\" and \"label\" properties (e.g. \"options\": [ {{ \"id\": \"opt-ios\", \"label\": \"iOS\" }}, {{ \"id\": \"opt-android\", \"label\": \"Android\" }}, {{ \"id\": \"opt-web\", \"label\": \"Web\" }} ]).\n" +
|
| 80 |
-
$"- Outgoing edges from a \"condition\" node MUST map to the choice options by using the option's index inside the edge's \"condition\" field:\n" +
|
| 81 |
-
$" * The first option (index 0) corresponds to edge \"condition\": \"True\".\n" +
|
| 82 |
-
$" * The second option (index 1) corresponds to edge \"condition\": \"False\".\n" +
|
| 83 |
-
$" * The third option (index 2) corresponds to edge \"condition\": \"Blocked\".\n" +
|
| 84 |
-
$" * Any subsequent options (indices i >= 3) correspond to edge \"condition\": \"i\" (as a string, e.g. \"3\", \"4\", etc.).\n" +
|
| 85 |
-
$"- For coordinates, lay out the nodes visually flowing from top to bottom. Increase 'posY' by approximately 200-240 units for each sequential step. Vary 'posX' (e.g., between 200 and 700) if there are parallel branches or decision paths.\n" +
|
| 86 |
-
$"- Every node must have a unique string 'id' (like \"node_1\", \"node_2\") and a dynamic 'type' property (defaults to \"sketch\").\n" +
|
| 87 |
-
$"- All nodes must be reachable via edges starting from the initial steps.\n\n" +
|
| 88 |
-
$"Provide the output strictly in a valid JSON format following this schema, with no additional explanation, no markdown text outside the JSON, and no other content:\n" +
|
| 89 |
-
$"{{\n" +
|
| 90 |
-
$" \"title\": \"Коротка та приваблива назва дорожньої карти\",\n" +
|
| 91 |
-
$" \"description\": \"Короткий опис стратегії\",\n" +
|
| 92 |
-
$" \"nodes\": [\n" +
|
| 93 |
-
$" {{ \"id\": \"node_1\", \"label\": \"Детальний перший крок\", \"posX\": 450, \"posY\": 100, \"type\": \"sketch\" }},\n" +
|
| 94 |
-
$" {{ \"id\": \"node_2\", \"label\": \"Оберіть платформу для розробки\", \"posX\": 450, \"posY\": 300, \"type\": \"condition\", \"options\": [ {{ \"id\": \"opt-web\", \"label\": \"Web\" }}, {{ \"id\": \"opt-mobile\", \"label\": \"Mobile\" }}, {{ \"id\": \"opt-desktop\", \"label\": \"Desktop\" }} ] }},\n" +
|
| 95 |
-
$" {{ \"id\": \"node_3\", \"label\": \"Освоєння HTML, CSS та JavaScript\", \"posX\": 200, \"posY\": 520, \"type\": \"sketch\" }},\n" +
|
| 96 |
-
$" {{ \"id\": \"node_4\", \"label\": \"Вивчення Swift або Kotlin\", \"posX\": 450, \"posY\": 520, \"type\": \"sketch\" }},\n" +
|
| 97 |
-
$" {{ \"id\": \"node_5\", \"label\": \"Вивчення C# та .NET для настільних вікон\", \"posX\": 700, \"posY\": 520, \"type\": \"sketch\" }}\n" +
|
| 98 |
-
$" ],\n" +
|
| 99 |
-
$" \"edges\": [\n" +
|
| 100 |
-
$" {{ \"from\": \"node_1\", \"to\": \"node_2\", \"condition\": \"True\" }},\n" +
|
| 101 |
-
$" {{ \"from\": \"node_2\", \"to\": \"node_3\", \"condition\": \"True\" }},\n" +
|
| 102 |
-
$" {{ \"from\": \"node_2\", \"to\": \"node_4\", \"condition\": \"False\" }},\n" +
|
| 103 |
-
$" {{ \"from\": \"node_2\", \"to\": \"node_5\", \"condition\": \"Blocked\" }}\n" +
|
| 104 |
-
$" ]\n" +
|
| 105 |
-
$"}}";
|
| 106 |
-
|
| 107 |
-
// 3. Send Prompt via Persistent Bridge
|
| 108 |
-
string rawResponseJson = await _bridgeManager.SendPromptAsync(promptText, isNewChat: true, timeoutSeconds: 120);
|
| 109 |
-
|
| 110 |
-
// 7. Parse Bridge Message
|
| 111 |
-
using var jsonDoc = JsonDocument.Parse(rawResponseJson);
|
| 112 |
-
var root = jsonDoc.RootElement;
|
| 113 |
-
if (root.GetProperty("status").GetString() != "success")
|
| 114 |
-
{
|
| 115 |
-
string errMsg = root.TryGetProperty("error", out var errVal) ? errVal.GetString() ?? "Unknown error" : "Bridge generation failed";
|
| 116 |
-
throw new Exception("AI bridge returned error: " + errMsg);
|
| 117 |
-
}
|
| 118 |
-
|
| 119 |
-
string aiContent = root.GetProperty("content").GetString() ?? string.Empty;
|
| 120 |
-
string cleanJson = CleanJson(aiContent);
|
| 121 |
-
|
| 122 |
-
if (string.IsNullOrWhiteSpace(cleanJson))
|
| 123 |
-
{
|
| 124 |
-
throw new Exception("The AI bridge returned empty content. Please try generating again.");
|
| 125 |
-
}
|
| 126 |
-
|
| 127 |
-
// 8. Deserialize AI Roadmap Structure
|
| 128 |
-
AIGoalGraphResponse? parsedData;
|
| 129 |
-
try
|
| 130 |
-
{
|
| 131 |
-
parsedData = JsonSerializer.Deserialize<AIGoalGraphResponse>(cleanJson, new JsonSerializerOptions
|
| 132 |
-
{
|
| 133 |
-
PropertyNameCaseInsensitive = true
|
| 134 |
-
});
|
| 135 |
-
}
|
| 136 |
-
catch (JsonException ex)
|
| 137 |
-
{
|
| 138 |
-
string preview = aiContent.Length > 200 ? aiContent.Substring(0, 200) + "..." : aiContent;
|
| 139 |
-
throw new Exception($"Failed to parse AI response as JSON. Content: '{preview}'. Error: {ex.Message}", ex);
|
| 140 |
-
}
|
| 141 |
-
|
| 142 |
-
if (parsedData == null || parsedData.Nodes == null || parsedData.Nodes.Count == 0)
|
| 143 |
-
{
|
| 144 |
-
throw new Exception("The AI response did not contain a valid nodes list.");
|
| 145 |
-
}
|
| 146 |
-
|
| 147 |
-
// 9. Map temporary String IDs to Database GUIDs
|
| 148 |
-
var guidMap = new Dictionary<string, Guid>();
|
| 149 |
-
var nodeDtos = new List<NodeDto>();
|
| 150 |
-
|
| 151 |
-
for (int i = 0; i < parsedData.Nodes.Count; i++)
|
| 152 |
-
{
|
| 153 |
-
var aiNode = parsedData.Nodes[i];
|
| 154 |
-
var newGuid = Guid.NewGuid();
|
| 155 |
-
guidMap[aiNode.Id] = newGuid;
|
| 156 |
-
|
| 157 |
-
// Coordinate layout will be handled by the layout engine later
|
| 158 |
-
double finalX = aiNode.PosX;
|
| 159 |
-
double finalY = aiNode.PosY;
|
| 160 |
-
|
| 161 |
-
string? decisionJson = null;
|
| 162 |
-
if (aiNode.Type == "condition")
|
| 163 |
-
{
|
| 164 |
-
var optionsList = new List<object>();
|
| 165 |
-
if (aiNode.Options != null && aiNode.Options.Count > 0)
|
| 166 |
-
{
|
| 167 |
-
foreach (var opt in aiNode.Options)
|
| 168 |
-
{
|
| 169 |
-
optionsList.Add(new { id = opt.Id, label = opt.Label });
|
| 170 |
-
}
|
| 171 |
-
}
|
| 172 |
-
else
|
| 173 |
-
{
|
| 174 |
-
optionsList.Add(new { id = "opt-yes", label = "Так" });
|
| 175 |
-
optionsList.Add(new { id = "opt-no", label = "Ні" });
|
| 176 |
-
}
|
| 177 |
-
|
| 178 |
-
decisionJson = JsonSerializer.Serialize(new
|
| 179 |
-
{
|
| 180 |
-
options = optionsList,
|
| 181 |
-
selected = new string[] { },
|
| 182 |
-
multiSelect = false
|
| 183 |
-
}, serializeOptions);
|
| 184 |
-
}
|
| 185 |
-
|
| 186 |
-
nodeDtos.Add(new NodeDto
|
| 187 |
-
{
|
| 188 |
-
Id = newGuid,
|
| 189 |
-
Label = aiNode.Label,
|
| 190 |
-
PosX = finalX,
|
| 191 |
-
PosY = finalY,
|
| 192 |
-
Type = aiNode.Type ?? "sketch",
|
| 193 |
-
State = 0,
|
| 194 |
-
Decision = decisionJson
|
| 195 |
-
});
|
| 196 |
-
}
|
| 197 |
-
|
| 198 |
-
var edgeDtos = new List<EdgeDto>();
|
| 199 |
-
if (parsedData.Edges != null)
|
| 200 |
-
{
|
| 201 |
-
foreach (var aiEdge in parsedData.Edges)
|
| 202 |
-
{
|
| 203 |
-
if (guidMap.TryGetValue(aiEdge.From, out var fromGuid) &&
|
| 204 |
-
guidMap.TryGetValue(aiEdge.To, out var toGuid))
|
| 205 |
-
{
|
| 206 |
-
edgeDtos.Add(new EdgeDto
|
| 207 |
-
{
|
| 208 |
-
Id = Guid.NewGuid(),
|
| 209 |
-
FromNodeId = fromGuid,
|
| 210 |
-
ToNodeId = toGuid,
|
| 211 |
-
Condition = aiEdge.Condition ?? "True"
|
| 212 |
-
});
|
| 213 |
-
}
|
| 214 |
-
}
|
| 215 |
-
}
|
| 216 |
-
|
| 217 |
-
// 10. Apply Automated Beautiful Layout
|
| 218 |
-
ApplyBeautifulLayout(nodeDtos, edgeDtos);
|
| 219 |
-
|
| 220 |
-
// 11. Persist using existing GraphService
|
| 221 |
-
var createDto = new CreateGraphDto
|
| 222 |
-
{
|
| 223 |
-
UserId = request.UserId,
|
| 224 |
-
Title = string.IsNullOrWhiteSpace(parsedData.Title) ? request.Goal : parsedData.Title,
|
| 225 |
-
Description = string.IsNullOrWhiteSpace(parsedData.Description) ? "AI generated roadmap" : parsedData.Description
|
| 226 |
-
};
|
| 227 |
-
|
| 228 |
-
var createdGraph = await _graphService.CreateAsync(createDto, request.UserId);
|
| 229 |
-
|
| 230 |
-
var fullGraphDto = new FullGraphResponseDto
|
| 231 |
-
{
|
| 232 |
-
Id = createdGraph.Id,
|
| 233 |
-
UserId = createdGraph.UserId,
|
| 234 |
-
Title = createdGraph.Title,
|
| 235 |
-
Description = createdGraph.Description,
|
| 236 |
-
CreatedAt = createdGraph.CreatedAt,
|
| 237 |
-
Nodes = nodeDtos,
|
| 238 |
-
Edges = edgeDtos
|
| 239 |
-
};
|
| 240 |
-
|
| 241 |
-
bool saveSuccess = await _graphService.SaveFullGraphAsync(createdGraph.Id, fullGraphDto, request.UserId);
|
| 242 |
-
if (!saveSuccess)
|
| 243 |
-
{
|
| 244 |
-
throw new Exception("Graph was created, but failed to save the sequential roadmap steps.");
|
| 245 |
-
}
|
| 246 |
-
|
| 247 |
-
return fullGraphDto;
|
| 248 |
}
|
| 249 |
|
| 250 |
public async Task<AICanvasAssistResponseDto> CanvasAssistAsync(AICanvasAssistRequestDto request)
|
| 251 |
{
|
| 252 |
-
|
| 253 |
-
var graph = await _graphRepo.GetByIdWithDetailsAsync(request.GraphId);
|
| 254 |
-
if (graph == null) throw new Exception("Graph not found.");
|
| 255 |
-
|
| 256 |
-
// 2. Prepare serialization of active nodes and edges
|
| 257 |
-
var currentNodesList = graph.Nodes.Select(n => new {
|
| 258 |
-
id = n.Id.ToString(),
|
| 259 |
-
label = n.Label,
|
| 260 |
-
posX = n.PosX,
|
| 261 |
-
posY = n.PosY,
|
| 262 |
-
type = n.Type,
|
| 263 |
-
state = n.State.ToString()
|
| 264 |
-
}).ToList();
|
| 265 |
-
|
| 266 |
-
var currentEdgesList = graph.Edges.Select(e => new {
|
| 267 |
-
id = e.Id.ToString(),
|
| 268 |
-
from = e.FromNodeId.ToString(),
|
| 269 |
-
to = e.ToNodeId.ToString(),
|
| 270 |
-
condition = e.Condition.ToString()
|
| 271 |
-
}).ToList();
|
| 272 |
-
|
| 273 |
-
var serializeOptions = new JsonSerializerOptions
|
| 274 |
-
{
|
| 275 |
-
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
|
| 276 |
-
};
|
| 277 |
-
|
| 278 |
-
// 4. Formulate Prompt for Gemini
|
| 279 |
-
string promptText = $"You are an expert strategist and goal decomposition AI.\n" +
|
| 280 |
-
$"The user has an active strategy roadmap titled \"{graph.Title}\" with the description \"{graph.Description}\" in Ukrainian.\n\n" +
|
| 281 |
-
$"Current Canvas Structure (in Ukrainian):\n" +
|
| 282 |
-
$"- Nodes: {JsonSerializer.Serialize(currentNodesList, serializeOptions)}\n" +
|
| 283 |
-
$"- Edges: {JsonSerializer.Serialize(currentEdgesList, serializeOptions)}\n\n" +
|
| 284 |
-
$"User Request: \"{request.UserPrompt}\"\n\n" +
|
| 285 |
-
$"Analyze the current roadmap, and satisfy the user's request. Suggest adding new steps, alternative/branching paths, or decision conditions.\n" +
|
| 286 |
-
$"Create a list of NEW nodes and edges that should be added/merged into the canvas to satisfy the request.\n\n" +
|
| 287 |
-
$"Guidelines:\n" +
|
| 288 |
-
$"- Ensure all labels and description text are written in clear, natural Ukrainian.\n" +
|
| 289 |
-
$"- Avoid short, basic, generic titles. Write detailed, rich, and highly actionable labels for each node.\n" +
|
| 290 |
-
$"- Do NOT use the \"habit\" type under any circumstances. It is strictly forbidden. The allowed node types are \"sketch\" (standard task/goal) and \"condition\" (a decision/choice branch).\n" +
|
| 291 |
-
$"- Use \"condition\" nodes appropriately and dynamically when the user request or alternative path requires a choice, criteria evaluation, or conditional gate.\n" +
|
| 292 |
-
$"- A \"condition\" node can have custom choices (options) instead of just simple binary branches! To specify custom choices/branches for a condition node, include an \"options\" array containing option objects with custom \"id\" and \"label\" properties (e.g. \"options\": [ {{ \"id\": \"opt-ios\", \"label\": \"iOS\" }}, {{ \"id\": \"opt-android\", \"label\": \"Android\" }}, {{ \"id\": \"opt-web\", \"label\": \"Web\" }} ]).\n" +
|
| 293 |
-
$"- Outgoing edges from a \"condition\" node MUST map to the choice options by using the option's index inside the edge's \"condition\" field:\n" +
|
| 294 |
-
$" * The first option (index 0) corresponds to edge \"condition\": \"True\".\n" +
|
| 295 |
-
$" * The second option (index 1) corresponds to edge \"condition\": \"False\".\n" +
|
| 296 |
-
$" * The third option (index 2) corresponds to edge \"condition\": \"Blocked\".\n" +
|
| 297 |
-
$" * Any subsequent options (indices i >= 3) correspond to edge \"condition\": \"i\" (as a string, e.g. \"3\", \"4\", etc.).\n" +
|
| 298 |
-
$"- For coordinates of new nodes, calculate 'posX' and 'posY' relative to nearby nodes so they flow nicely. Use values that don't directly overlap existing coordinates.\n" +
|
| 299 |
-
$"- Every new node must have a unique string 'id' starting with \"new_node_\" (like \"new_node_1\", \"new_node_2\") and a dynamic 'type' property (defaults to \"sketch\").\n" +
|
| 300 |
-
$"- You can also use existing node IDs (from the current structure) in the 'from' and 'to' fields of the new edges to link the new nodes into the existing flow!\n" +
|
| 301 |
-
$"- All new edges should connect new nodes to each other, or to existing nodes.\n\n" +
|
| 302 |
-
$"Provide the output strictly in a valid JSON format following this schema, with no explanation, no markdown text outside the JSON, and no other content:\n" +
|
| 303 |
-
$"{{\n" +
|
| 304 |
-
$" \"newNodes\": [\n" +
|
| 305 |
-
$" {{ \"id\": \"new_node_1\", \"label\": \"Детальний новий крок для розширення\", \"posX\": 450, \"posY\": 300, \"type\": \"sketch\" }},\n" +
|
| 306 |
-
$" {{ \"id\": \"new_node_2\", \"label\": \"Нова умова вибору середовища\", \"posX\": 450, \"posY\": 520, \"type\": \"condition\", \"options\": [ {{ \"id\": \"opt-react\", \"label\": \"React\" }}, {{ \"id\": \"opt-vue\", \"label\": \"Vue\" }}, {{ \"id\": \"opt-angular\", \"label\": \"Angular\" }} ] }},\n" +
|
| 307 |
-
$" {{ \"id\": \"new_node_3\", \"label\": \"Вивчення React hooks та JSX\", \"posX\": 200, \"posY\": 740, \"type\": \"sketch\" }},\n" +
|
| 308 |
-
$" {{ \"id\": \"new_node_4\", \"label\": \"Вивчення Composition API у Vue\", \"posX\": 450, \"posY\": 740, \"type\": \"sketch\" }},\n" +
|
| 309 |
-
$" {{ \"id\": \"new_node_5\", \"label\": \"Вивчення TypeScript та RxJS в Angular\", \"posX\": 700, \"posY\": 740, \"type\": \"sketch\" }}\n" +
|
| 310 |
-
$" ],\n" +
|
| 311 |
-
$" \"newEdges\": [\n" +
|
| 312 |
-
$" {{ \"from\": \"existing_node_id_here\", \"to\": \"new_node_1\" }},\n" +
|
| 313 |
-
$" {{ \"from\": \"new_node_1\", \"to\": \"new_node_2\" }},\n" +
|
| 314 |
-
$" {{ \"from\": \"new_node_2\", \"to\": \"new_node_3\", \"condition\": \"True\" }},\n" +
|
| 315 |
-
$" {{ \"from\": \"new_node_2\", \"to\": \"new_node_4\", \"condition\": \"False\" }},\n" +
|
| 316 |
-
$" {{ \"from\": \"new_node_2\", \"to\": \"new_node_5\", \"condition\": \"Blocked\" }}\n" +
|
| 317 |
-
$" ]\n" +
|
| 318 |
-
$"}}";
|
| 319 |
-
|
| 320 |
-
// 3. Send Prompt via Persistent Bridge
|
| 321 |
-
string rawResponseJson = await _bridgeManager.SendPromptAsync(promptText, isNewChat: true, timeoutSeconds: 120);
|
| 322 |
-
if (string.IsNullOrEmpty(rawResponseJson))
|
| 323 |
-
{
|
| 324 |
-
throw new Exception("Did not receive a valid response block from the Gemini Bridge.");
|
| 325 |
-
}
|
| 326 |
-
|
| 327 |
-
// Parse Bridge Message
|
| 328 |
-
using var jsonDoc = JsonDocument.Parse(rawResponseJson);
|
| 329 |
-
var root = jsonDoc.RootElement;
|
| 330 |
-
|
| 331 |
-
if (root.GetProperty("status").GetString() != "success")
|
| 332 |
-
{
|
| 333 |
-
string errMsg = root.TryGetProperty("error", out var errVal) ? errVal.GetString() ?? "Unknown error" : "Bridge generation failed";
|
| 334 |
-
throw new Exception("AI bridge returned error: " + errMsg);
|
| 335 |
-
}
|
| 336 |
-
|
| 337 |
-
string aiContent = root.GetProperty("content").GetString() ?? string.Empty;
|
| 338 |
-
string cleanJson = CleanJson(aiContent);
|
| 339 |
-
|
| 340 |
-
if (string.IsNullOrWhiteSpace(cleanJson))
|
| 341 |
-
{
|
| 342 |
-
throw new Exception("The AI bridge returned empty canvas assist content. Please try generating again.");
|
| 343 |
-
}
|
| 344 |
-
|
| 345 |
-
// Deserialize AI Assist Response Structure
|
| 346 |
-
AICanvasAssistResponseInternal? parsedData;
|
| 347 |
-
try
|
| 348 |
-
{
|
| 349 |
-
parsedData = JsonSerializer.Deserialize<AICanvasAssistResponseInternal>(cleanJson, new JsonSerializerOptions
|
| 350 |
-
{
|
| 351 |
-
PropertyNameCaseInsensitive = true
|
| 352 |
-
});
|
| 353 |
-
}
|
| 354 |
-
catch (JsonException ex)
|
| 355 |
-
{
|
| 356 |
-
string preview = aiContent.Length > 200 ? aiContent.Substring(0, 200) + "..." : aiContent;
|
| 357 |
-
throw new Exception($"Failed to parse Canvas Assist AI response as JSON. Content: '{preview}'. Error: {ex.Message}", ex);
|
| 358 |
-
}
|
| 359 |
-
|
| 360 |
-
if (parsedData == null || parsedData.NewNodes == null)
|
| 361 |
-
{
|
| 362 |
-
throw new Exception("The AI response did not contain a valid newNodes list.");
|
| 363 |
-
}
|
| 364 |
-
|
| 365 |
-
// Map temporary IDs to database GUIDs
|
| 366 |
-
var guidMap = new Dictionary<string, Guid>();
|
| 367 |
-
var newNodesEntities = new List<FlowAPI.Domain.Entities.TaskNode>();
|
| 368 |
-
var nodeDtos = new List<NodeDto>();
|
| 369 |
-
|
| 370 |
-
for (int i = 0; i < parsedData.NewNodes.Count; i++)
|
| 371 |
-
{
|
| 372 |
-
var aiNode = parsedData.NewNodes[i];
|
| 373 |
-
var newGuid = Guid.NewGuid();
|
| 374 |
-
guidMap[aiNode.Id] = newGuid;
|
| 375 |
-
|
| 376 |
-
string? decisionJson = null;
|
| 377 |
-
if (aiNode.Type == "condition")
|
| 378 |
-
{
|
| 379 |
-
var optionsList = new List<object>();
|
| 380 |
-
if (aiNode.Options != null && aiNode.Options.Count > 0)
|
| 381 |
-
{
|
| 382 |
-
foreach (var opt in aiNode.Options)
|
| 383 |
-
{
|
| 384 |
-
optionsList.Add(new { id = opt.Id, label = opt.Label });
|
| 385 |
-
}
|
| 386 |
-
}
|
| 387 |
-
else
|
| 388 |
-
{
|
| 389 |
-
optionsList.Add(new { id = "opt-yes", label = "Так" });
|
| 390 |
-
optionsList.Add(new { id = "opt-no", label = "Ні" });
|
| 391 |
-
}
|
| 392 |
-
|
| 393 |
-
decisionJson = JsonSerializer.Serialize(new
|
| 394 |
-
{
|
| 395 |
-
options = optionsList,
|
| 396 |
-
selected = new string[] { },
|
| 397 |
-
multiSelect = false
|
| 398 |
-
}, serializeOptions);
|
| 399 |
-
}
|
| 400 |
-
|
| 401 |
-
var nodeEntity = new FlowAPI.Domain.Entities.TaskNode
|
| 402 |
-
{
|
| 403 |
-
Id = newGuid,
|
| 404 |
-
GraphId = request.GraphId,
|
| 405 |
-
Label = aiNode.Label,
|
| 406 |
-
PosX = aiNode.PosX,
|
| 407 |
-
PosY = aiNode.PosY,
|
| 408 |
-
Type = aiNode.Type ?? "sketch",
|
| 409 |
-
State = FlowAPI.Domain.Enums.NodeState.Pending,
|
| 410 |
-
Decision = decisionJson,
|
| 411 |
-
CreatedAt = DateTime.UtcNow
|
| 412 |
-
};
|
| 413 |
-
newNodesEntities.Add(nodeEntity);
|
| 414 |
-
|
| 415 |
-
nodeDtos.Add(new NodeDto
|
| 416 |
-
{
|
| 417 |
-
Id = newGuid,
|
| 418 |
-
Label = aiNode.Label,
|
| 419 |
-
PosX = aiNode.PosX,
|
| 420 |
-
PosY = aiNode.PosY,
|
| 421 |
-
Type = aiNode.Type ?? "sketch",
|
| 422 |
-
State = 0,
|
| 423 |
-
Decision = decisionJson
|
| 424 |
-
});
|
| 425 |
-
}
|
| 426 |
-
|
| 427 |
-
var newEdgesEntities = new List<FlowAPI.Domain.Entities.Edge>();
|
| 428 |
-
var edgeDtos = new List<EdgeDto>();
|
| 429 |
-
|
| 430 |
-
if (parsedData.NewEdges != null)
|
| 431 |
-
{
|
| 432 |
-
foreach (var aiEdge in parsedData.NewEdges)
|
| 433 |
-
{
|
| 434 |
-
Guid fromGuid;
|
| 435 |
-
if (Guid.TryParse(aiEdge.From, out var fromParsed))
|
| 436 |
-
{
|
| 437 |
-
fromGuid = fromParsed;
|
| 438 |
-
}
|
| 439 |
-
else if (guidMap.TryGetValue(aiEdge.From, out var mappedFrom))
|
| 440 |
-
{
|
| 441 |
-
fromGuid = mappedFrom;
|
| 442 |
-
}
|
| 443 |
-
else
|
| 444 |
-
{
|
| 445 |
-
continue;
|
| 446 |
-
}
|
| 447 |
-
|
| 448 |
-
Guid toGuid;
|
| 449 |
-
if (Guid.TryParse(aiEdge.To, out var toParsed))
|
| 450 |
-
{
|
| 451 |
-
toGuid = toParsed;
|
| 452 |
-
}
|
| 453 |
-
else if (guidMap.TryGetValue(aiEdge.To, out var mappedTo))
|
| 454 |
-
{
|
| 455 |
-
toGuid = mappedTo;
|
| 456 |
-
}
|
| 457 |
-
else
|
| 458 |
-
{
|
| 459 |
-
continue;
|
| 460 |
-
}
|
| 461 |
-
|
| 462 |
-
var edgeGuid = Guid.NewGuid();
|
| 463 |
-
var edgeEntity = new FlowAPI.Domain.Entities.Edge
|
| 464 |
-
{
|
| 465 |
-
Id = edgeGuid,
|
| 466 |
-
GraphId = request.GraphId,
|
| 467 |
-
FromNodeId = fromGuid,
|
| 468 |
-
ToNodeId = toGuid,
|
| 469 |
-
Condition = Enum.TryParse<FlowAPI.Domain.Enums.EdgeCondition>(aiEdge.Condition, true, out var conditionEnum) ? conditionEnum : FlowAPI.Domain.Enums.EdgeCondition.True
|
| 470 |
-
};
|
| 471 |
-
newEdgesEntities.Add(edgeEntity);
|
| 472 |
-
|
| 473 |
-
edgeDtos.Add(new EdgeDto
|
| 474 |
-
{
|
| 475 |
-
Id = edgeGuid,
|
| 476 |
-
FromNodeId = fromGuid,
|
| 477 |
-
ToNodeId = toGuid,
|
| 478 |
-
Condition = aiEdge.Condition ?? "True"
|
| 479 |
-
});
|
| 480 |
-
}
|
| 481 |
-
}
|
| 482 |
-
|
| 483 |
-
// Apply Automated Beautiful Layout to the entire combined graph
|
| 484 |
-
var allNodes = graph.Nodes.Concat(newNodesEntities).ToList();
|
| 485 |
-
var allEdges = graph.Edges.Concat(newEdgesEntities).ToList();
|
| 486 |
-
|
| 487 |
-
ApplyBeautifulLayout(allNodes, allEdges);
|
| 488 |
-
|
| 489 |
-
// Update the DTOs with the beautifully laid out coordinates so the frontend places them perfectly
|
| 490 |
-
foreach (var dto in nodeDtos)
|
| 491 |
-
{
|
| 492 |
-
var entity = allNodes.FirstOrDefault(n => n.Id == dto.Id);
|
| 493 |
-
if (entity != null)
|
| 494 |
-
{
|
| 495 |
-
dto.PosX = entity.PosX;
|
| 496 |
-
dto.PosY = entity.PosY;
|
| 497 |
-
}
|
| 498 |
-
}
|
| 499 |
-
|
| 500 |
-
// Persist directly using repository
|
| 501 |
-
bool saveSuccess = await _graphRepo.UpsertFullGraphAsync(request.GraphId, allNodes, allEdges);
|
| 502 |
-
if (!saveSuccess)
|
| 503 |
-
{
|
| 504 |
-
throw new Exception("Failed to persist newly suggested AI canvas elements to database.");
|
| 505 |
-
}
|
| 506 |
-
|
| 507 |
-
return new AICanvasAssistResponseDto
|
| 508 |
-
{
|
| 509 |
-
NewNodes = nodeDtos,
|
| 510 |
-
NewEdges = edgeDtos
|
| 511 |
-
};
|
| 512 |
}
|
| 513 |
|
| 514 |
private string CleanJson(string text)
|
|
|
|
| 35 |
|
| 36 |
public async Task<AIPathResponseDto> GenerateAlternativePathAsync(GenerateAlternativeRequestDto request)
|
| 37 |
{
|
| 38 |
+
throw new Exception("Функція ШІ тимчасово недоступна. Ми працюємо над її покращенням!");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
}
|
| 40 |
|
| 41 |
public async Task<FullGraphResponseDto> GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request)
|
| 42 |
{
|
| 43 |
+
throw new Exception("Функція ШІ тимчасово недоступна. Ми працюємо над її покращенням!");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
}
|
| 45 |
|
| 46 |
public async Task<AICanvasAssistResponseDto> CanvasAssistAsync(AICanvasAssistRequestDto request)
|
| 47 |
{
|
| 48 |
+
throw new Exception("Функція ШІ тимчасово недоступна. Ми працюємо над її покращенням!");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
}
|
| 50 |
|
| 51 |
private string CleanJson(string text)
|