Spaces:
Running
Running
Commit ·
90e1fa5
1
Parent(s): 8b1a825
gemini integration
Browse filesFiles changed (3)
29 unmodified lines3031323334353629 unmodified lines
public class AICanvasAssistResponseDto { public string Explanation { get; set; } = string.Empty; public List<NodeDto> NewNodes { get; set; } = new(); public List<EdgeDto> NewEdges { get; set; } = new(); }8 unmodified lines9101112131415161718197 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081093 unmodified lines113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195381961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632644326526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636748368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486168 unmodified lines6556566572232242252262272282292302316586596606616626636646656666676682372382392402412422432442452462476696706716726736746756762546776782562572582592602612622632642652662676796806816826836846852706866872722732746886896906916926938 unmodified linesusing System.Text.Unicode;using System.Text.RegularExpressions;using System.Threading.Tasks;using System.Net.Http;using FlowAPI.Application.DTOs.AI;using FlowAPI.Application.DTOs.Graph;using FlowAPI.Application.DTOs.TaskNode;using FlowAPI.Application.DTOs.Edge;using FlowAPI.Application.Interfaces;using Microsoft.Extensions.Configuration;
7 unmodified lines private readonly IGraphService _graphService; private readonly IGeminiBridgeManager _bridgeManager;
private const string GoalResponseSchema = @"{ ""type"": ""object"", ""properties"": { ""title"": { ""type"": ""string"" }, ""description"": { ""type"": ""string"" }, ""explanation"": { ""type"": ""string"" }, ""nodes"": { ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""id"": { ""type"": ""string"" }, ""label"": { ""type"": ""string"" }, ""description"": { ""type"": ""string"" }, ""type"": { ""type"": ""string"", ""enum"": [""sketch"", ""condition"", ""habit""] }, ""decision"": { ""type"": ""string"" }, ""dependsOn"": { ""type"": ""string"" }, ""color"": { ""type"": ""string"", ""enum"": [""default"", ""yellow"", ""blue"", ""green"", ""pink"", ""purple"", ""orange"", ""white""] } }, ""required"": [""id"", ""label"", ""description"", ""type""] } }, ""edges"": { ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""from"": { ""type"": ""string"" }, ""to"": { ""type"": ""string"" }, ""relationship"": { ""type"": ""string"", ""enum"": [""sequential"", ""subgoal""] }, ""condition"": { ""type"": ""string"" } }, ""required"": [""from"", ""to"", ""relationship""] } } }, ""required"": [""title"", ""description"", ""explanation"", ""nodes"", ""edges""]}";
private const string AssistResponseSchema = @"{ ""type"": ""object"", ""properties"": { ""explanation"": { ""type"": ""string"" }, ""newNodes"": { ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""id"": { ""type"": ""string"" }, ""label"": { ""type"": ""string"" }, ""description"": { ""type"": ""string"" }, ""type"": { ""type"": ""string"", ""enum"": [""sketch"", ""condition"", ""habit""] }, ""decision"": { ""type"": ""string"" }, ""color"": { ""type"": ""string"", ""enum"": [""default"", ""yellow"", ""blue"", ""green"", ""pink"", ""purple"", ""orange"", ""white""] } }, ""required"": [""id"", ""label"", ""description"", ""type""] } }, ""newEdges"": { ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""from"": { ""type"": ""string"" }, ""to"": { ""type"": ""string"" }, ""relationship"": { ""type"": ""string"", ""enum"": [""sequential"", ""subgoal""] }, ""condition"": { ""type"": ""string"" } }, ""required"": [""from"", ""to"", ""relationship""] } } }, ""required"": [""explanation"", ""newNodes"", ""newEdges""]}";
public AIService(IUserRepository userRepo, IGraphRepository graphRepo, IConfiguration config, IGraphService graphService, IGeminiBridgeManager bridgeManager) { _userRepo = userRepo;3 unmodified lines _bridgeManager = bridgeManager; }
private async Task<string> CallGeminiApiAsync(string prompt, string? systemInstruction = null, string? responseSchemaJson = null) { var apiKey = _config["Gemini:ApiKey"] ?? Environment.GetEnvironmentVariable("GEMINI_API_KEY"); if (string.IsNullOrEmpty(apiKey)) { throw new Exception("Gemini API key is not configured. Please add Gemini:ApiKey to appsettings.json or set GEMINI_API_KEY environment variable."); }
var model = _config["Gemini:Model"] ?? "gemini-1.5-flash"; var url = $"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={apiKey}";
var parts = new List<object> { new { text = prompt } }; var contents = new[] { new { parts = parts } }; object? generationConfig = null; if (responseSchemaJson != null) { generationConfig = new { responseMimeType = "application/json", responseSchema = JsonSerializer.Deserialize<object>(responseSchemaJson) }; } else { generationConfig = new { responseMimeType = "application/json" }; }
object requestBody; if (!string.IsNullOrEmpty(systemInstruction)) { requestBody = new { contents = contents, systemInstruction = new { parts = new[] { new { text = systemInstruction } } }, generationConfig = generationConfig }; } else { requestBody = new { contents = contents, generationConfig = generationConfig }; }
using var httpClient = new HttpClient(); var jsonPayload = JsonSerializer.Serialize(requestBody); var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(url, content); var responseString = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode) { throw new Exception($"Gemini API error (Status {response.StatusCode}): {responseString}"); }
using var doc = JsonDocument.Parse(responseString); var textResponse = doc.RootElement .GetProperty("candidates")[0] .GetProperty("content") .GetProperty("parts")[0] .GetProperty("text") .GetString();
if (string.IsNullOrEmpty(textResponse)) { throw new Exception("Empty response received from Gemini API."); }
return textResponse; }
public async Task<AIPathResponseDto> GenerateAlternativePathAsync(GenerateAlternativeRequestDto request) { throw new Exception("Функція ШІ тимчасово недоступна. Ми працюємо над її покращенням!"); var graph = await _graphRepo.GetByIdWithDetailsAsync(request.GraphId); if (graph == null) { throw new Exception("Graph not found."); }
var failedNode = graph.Nodes.FirstOrDefault(n => n.Id == request.FailedNodeId); if (failedNode == null) { throw new Exception("Target node not found."); }
var prompt = $"В нашей дорожной карте произошел сбой на шаге: \"{failedNode.Label}\" (Описание: \"{failedNode.Description}\").\n" + $"Предложи альтернативный обходной путь из 2-3 шагов, чтобы пользователь мог продолжить движение к цели.\n" + $"Предоставь только новые шаги (NewNodes) и новые связи (NewEdges) для их интеграции.";
var systemInstruction = "You are a Roadmap Strategist AI Agent. You design failover alternative paths for failed tasks in a roadmap."; var responseJson = await CallGeminiApiAsync(prompt, systemInstruction, AssistResponseSchema); responseJson = CleanJson(responseJson);
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var rawAssist = JsonSerializer.Deserialize<GeminiAssistResponse>(responseJson, options) ?? throw new Exception("Failed to deserialize AI alternative path response from Gemini.");
var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase); idMap[failedNode.Id.ToString()] = failedNode.Id;
foreach (var node in rawAssist.NewNodes) { if (!idMap.ContainsKey(node.Id)) { idMap[node.Id] = Guid.NewGuid(); } }
var mappedNodes = rawAssist.NewNodes.Select(node => new TaskNodeResponseDto { Id = idMap[node.Id], Label = node.Label, PosX = failedNode.PosX + 300, PosY = failedNode.PosY + 150, State = FlowAPI.Domain.Enums.NodeState.Pending, CreatedAt = DateTime.UtcNow }).ToList();
var mappedEdges = new List<EdgeResponseDto>(); foreach (var edge in rawAssist.NewEdges) { if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid)) { mappedEdges.Add(new EdgeResponseDto { Id = Guid.NewGuid(), FromNodeId = fromGuid, ToNodeId = toGuid, Condition = edge.Relationship == "subgoal" ? "subgoals-source" : "True" }); } }
return new AIPathResponseDto { SuggestedNodes = mappedNodes, SuggestedEdges = mappedEdges }; }
public async Task<FullGraphResponseDto> GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request) { throw new Exception("Функція ШІ тимчасово недоступна. Ми працюємо над її покращенням!"); if (string.IsNullOrWhiteSpace(request.Goal)) { throw new ArgumentException("Goal description cannot be empty."); }
// 1. Build prompt for Gemini var prompt = $"Пользователь хочет достичь следующей цели: \"{request.Goal}\". " + "Составь подробную иерархическую дорожную карту с последовательными шагами, ветвлениями решений (condition) и полезными привычками (habit). " + "Каждому узлу (Node) дай понятное короткое название и подробное описание (как файлы в папках воркспейса разработчика), чтобы сразу загружать нужный контекст. " + "В поле explanation напиши подробный вдохновляющий ответ от лица Агента-Стратега, рассказывающий о шагах и структуре сгенерированного плана.";
// 2. Call Gemini API 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."; var responseJson = await CallGeminiApiAsync(prompt, systemInstruction, GoalResponseSchema); responseJson = CleanJson(responseJson);
// 3. Deserialize response var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var rawGraph = JsonSerializer.Deserialize<GeminiGoalResponse>(responseJson, options) ?? throw new Exception("Failed to deserialize generated roadmap graph from Gemini.");
// 4. Create the Graph record in the database first var createDto = new CreateGraphDto { Title = string.IsNullOrWhiteSpace(rawGraph.Title) ? request.Goal : rawGraph.Title, Description = string.IsNullOrWhiteSpace(rawGraph.Description) ? "Дорожная карта, сгенерированная AI Агентом" : rawGraph.Description }; var graphResponse = await _graphService.CreateAsync(createDto, request.UserId); var graphId = graphResponse.Id;
// 5. Map Gemini string IDs to GUIDs var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase); foreach (var node in rawGraph.Nodes) { if (!idMap.ContainsKey(node.Id)) { idMap[node.Id] = Guid.NewGuid(); } }
// 6. Construct DTO lists var mappedNodes = rawGraph.Nodes.Select(node => new NodeDto { Id = idMap[node.Id], Label = node.Label, PosX = 0, PosY = 0, Type = node.Type ?? "sketch", State = 0, // Pending Decision = node.Decision, Description = node.Description, Color = node.Color ?? "default", IsPinned = false }).ToList();
var mappedEdges = new List<EdgeDto>(); foreach (var edge in rawGraph.Edges) { if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid)) { mappedEdges.Add(new EdgeDto { Id = Guid.NewGuid(), FromNodeId = fromGuid, ToNodeId = toGuid, Condition = edge.Relationship == "subgoal" ? "subgoals-source" : (string.IsNullOrWhiteSpace(edge.Condition) ? "True" : edge.Condition) }); } }
// 7. Calculate layouts ApplyBeautifulLayout(mappedNodes, mappedEdges);
// 8. Save fully generated graph to DB var fullGraphDto = new FullGraphResponseDto { Id = graphId, UserId = request.UserId, Title = createDto.Title, Description = createDto.Description, CreatedAt = DateTime.UtcNow, Nodes = mappedNodes, Edges = mappedEdges };
await _graphService.SaveFullGraphAsync(graphId, fullGraphDto, request.UserId);
// 9. Update roadmap description with explanation from strategist var graphEntity = await _graphRepo.GetByIdAsync(graphId); if (graphEntity != null) { graphEntity.Description = rawGraph.Explanation; await _graphRepo.UpdateAsync(graphEntity); fullGraphDto.Description = rawGraph.Explanation; }
return fullGraphDto; }
public async Task<AICanvasAssistResponseDto> CanvasAssistAsync(AICanvasAssistRequestDto request) { throw new Exception("Функція ШІ тимчасово недоступна. Ми працюємо над її покращенням!"); var graph = await _graphRepo.GetByIdWithDetailsAsync(request.GraphId); if (graph == null) { throw new Exception("Graph not found."); }
// 1. Serialize existing nodes and edges for Gemini context var existingNodesText = new StringBuilder(); existingNodesText.AppendLine("Текущие узлы на доске:"); foreach (var node in graph.Nodes) { existingNodesText.AppendLine($"- ID: \"{node.Id}\", Название: \"{node.Label}\", Тип: \"{node.Type}\", Состояние: \"{node.State}\", Описание: \"{node.Description}\""); }
var existingEdgesText = new StringBuilder(); existingEdgesText.AppendLine("Текущие связи на доске:"); foreach (var edge in graph.Edges) { existingEdgesText.AppendLine($"- От: \"{edge.FromNodeId}\", К: \"{edge.ToNodeId}\", Условие: \"{edge.Condition}\""); }
// 2. Build the prompt var prompt = $"Пользователь делает запрос к Агенту-Стратегу на изменение холста дорожной карты:\n" + $"Запрос пользователя: \"{request.UserPrompt}\"\n\n" + $"{existingNodesText}\n" + $"{existingEdgesText}\n\n" + $"Твоя задача — сгенерировать новые узлы (NewNodes) и новые связи (NewEdges) для добавления на холст, чтобы удовлетворить запрос пользователя.\n" + $"Связи 'relationship' могут быть 'sequential' или 'subgoal'.\n" + $"Придумывай новые уникальные буквенно-цифровые ID для новых узлов (например: new_step_1).\n" + $"Связи могут идти от существующих узлов к новым, от новых к новым, или от новых к существующим. Используй ID существующих узлов без изменений, если ссылаешься на них.\n" + $"В поле explanation подробно опиши в формате markdown, что именно и почему ты добавил на холст.";
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."; var responseJson = await CallGeminiApiAsync(prompt, systemInstruction, AssistResponseSchema); responseJson = CleanJson(responseJson);
// 3. Deserialize Gemini response var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var rawAssist = JsonSerializer.Deserialize<GeminiAssistResponse>(responseJson, options) ?? throw new Exception("Failed to deserialize AI Assist response from Gemini.");
// 4. Map string IDs to Guids var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase); // Map existing node Guids to themselves so they remain stable foreach (var node in graph.Nodes) { idMap[node.Id.ToString()] = node.Id; }
// Generate new Guids for new node IDs foreach (var node in rawAssist.NewNodes) { if (!idMap.ContainsKey(node.Id)) { idMap[node.Id] = Guid.NewGuid(); } }
// 5. Construct DTO nodes list var mappedNewNodes = rawAssist.NewNodes.Select(node => new NodeDto { Id = idMap[node.Id], Label = node.Label, PosX = 0, PosY = 0, Type = node.Type ?? "sketch", State = 0, // Pending Decision = node.Decision, Description = node.Description, Color = node.Color ?? "default", IsPinned = false }).ToList();
// 6. Construct DTO edges list var mappedNewEdges = new List<EdgeDto>(); foreach (var edge in rawAssist.NewEdges) { if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid)) { mappedNewEdges.Add(new EdgeDto { Id = Guid.NewGuid(), FromNodeId = fromGuid, ToNodeId = toGuid, Condition = edge.Relationship == "subgoal" ? "subgoals-source" : (string.IsNullOrWhiteSpace(edge.Condition) ? "True" : edge.Condition) }); } }
// 7. Positioning/Layout: // Find max PosY of existing nodes to place the new ones below double maxPosY = 100; if (graph.Nodes.Count > 0) { maxPosY = graph.Nodes.Max(n => n.PosY); }
// Run layout engine on the new nodes/edges ApplyBeautifulLayout(mappedNewNodes, mappedNewEdges);
// Shift all new nodes below the existing nodes double shiftY = maxPosY + 250; foreach (var node in mappedNewNodes) { node.PosY += shiftY; }
return new AICanvasAssistResponseDto { Explanation = rawAssist.Explanation, NewNodes = mappedNewNodes, NewEdges = mappedNewEdges }; }
private string CleanJson(string text)168 unmodified lines } }
private class AIGoalGraphResponse { public string Title { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public List<AINodeDto> Nodes { get; set; } = new(); public List<AIEdgeDto> Edges { get; set; } = new(); }
private class AIOptionDto private class GeminiNode { public string Id { get; set; } = string.Empty; public string Label { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public string Type { get; set; } = "sketch"; public string? Decision { get; set; } public string? DependsOn { get; set; } public string? Color { get; set; } }
private class AINodeDto { public string Id { get; set; } = string.Empty; public string Label { get; set; } = string.Empty; public double PosX { get; set; } public double PosY { get; set; } public string? Type { get; set; } public List<AIOptionDto>? Options { get; set; } }
private class AIEdgeDto private class GeminiEdge { public string From { get; set; } = string.Empty; public string To { get; set; } = string.Empty; public string Relationship { get; set; } = "sequential"; public string? Condition { get; set; } }
private class AICanvasAssistResponseInternal private class GeminiGoalResponse { public List<AINewNodeInternalDto> NewNodes { get; set; } = new(); public List<AINewEdgeInternalDto> NewEdges { get; set; } = new(); }
private class AINewNodeInternalDto { public string Id { get; set; } = string.Empty; public string Label { get; set; } = string.Empty; public double PosX { get; set; } public double PosY { get; set; } public string? Type { get; set; } public List<AIOptionDto>? Options { get; set; } public string Title { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public string Explanation { get; set; } = string.Empty; public List<GeminiNode> Nodes { get; set; } = new(); public List<GeminiEdge> Edges { get; set; } = new(); }
private class AINewEdgeInternalDto private class GeminiAssistResponse { public string From { get; set; } = string.Empty; public string To { get; set; } = string.Empty; public string? Condition { get; set; } public string Explanation { get; set; } = string.Empty; public List<GeminiNode> NewNodes { get; set; } = new(); public List<GeminiEdge> NewEdges { get; set; } = new(); } }}21 unmodified lines2223242526272829303121 unmodified lines "OpenAI": { "ApiKey": "" }, "Gemini": { "ApiKey": "AQ.Ab8RN6Iwv-IEeUHzINPr9-F7EstlZ28kTI55QjNbbzmDYWW-cw", "Model": "gemini-1.5-flash" }, "Stripe": { "SecretKey": "", "WebhookSecret": ""FlowAPI.Application/DTOs/AI/AIDtos.cs+1
FlowAPI.Application/Services/AIService.cs+456-40
FlowAPI/appsettings.json+4