This commit is contained in:
root
2025-10-07 16:11:20 +05:00
parent f800d1d6a5
commit a65bd39499
2 changed files with 51 additions and 21 deletions
@@ -13,19 +13,14 @@ import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import kz.konturai.parser.dto.ChartData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import java.util.Objects;
@Service
public class OpenAiChartService {
// 1. Инициализируем логгер для этого класса
private static final Logger logger = LoggerFactory.getLogger(OpenAiChartService.class);
private final WebClient webClient;
@@ -137,14 +132,40 @@ public class OpenAiChartService {
+ learningsAsString + "\n---";
}
// private String buildChartDataPrompt(String learningsAsString) {
// return "You are an AI data analyst. Carefully analyze the following text.
// Find all sets of numerical data suitable for simple bar or pie charts. For
// EACH data set you find, create a JSON object."
// +
// " Return ONLY a JSON array of these objects. The structure of each object
// MUST STRICTLY be: " +
// "{\"chartType\": \"bar\" or \"pie\", \"title\": \"Chart Title\", \"labels\":
// [\"Label 1\"], \"data\": [number1]}. "
// +
// "DO NOT omit any keys." +
// "\n\n" +
// "Example of a correct response:\n" +
// "[{\"chartType\":\"bar\",\"title\":\"Growth by
// Year\",\"labels\":[\"2023\",\"2024\"],\"data\":[100,150]}]"
// +
// "\n\n" +
// "If no suitable data is found, return an empty array [].\n\n" +
// "Text to analyze:\n---\n" +
// learningsAsString + "\n---";
// }
private String buildChartDataPrompt(String learningsAsString) {
return "You are an AI data analyst. Carefully analyze the following text. Find all sets of numerical data suitable for simple bar or pie charts. For EACH data set you find, create a JSON object."
+
" Return ONLY a JSON array of these objects. The structure of each object MUST STRICTLY be: " +
"{\"chartType\": \"bar\" or \"pie\", \"title\": \"Chart Title\", \"labels\": [\"Label 1\"], \"data\": [number1]}. "
+
"DO NOT omit any keys." +
"\n\n" +
// --- НОВЫЕ ВАЖНЫЕ ПРАВИЛА ---
"IMPORTANT RULES:\n" +
"1. The 'data' array MUST contain ONLY NUMBERS (e.g., 1.08), not text like 'KZT1.08 trillion'.\n" +
"2. DO NOT omit any keys.\n\n" +
// --- КОНЕЦ НОВЫХ ПРАВИЛ ---
"Example of a correct response:\n" +
"[{\"chartType\":\"bar\",\"title\":\"Growth by Year\",\"labels\":[\"2023\",\"2024\"],\"data\":[100,150]}]"
+
@@ -92,19 +92,28 @@ public class ReportSynthesisService {
}
private String buildTextPrompt(String originalQuery, String learningsAsString, String lang) {
return "Ты — профессиональный AI-аналитик. Твоя задача — написать подробный и структурированный отчёт на основе предоставленных данных. Не добавляй никаких предисловий или комментариев от себя, просто верни готовый отчёт.\n\n"
+ "### Тема исследования:\n\n"
+ originalQuery + "\n\n"
+ "### Собранные данные (тезисы):\n\n"
+ learningsAsString + "\n\n"
+ "### Твоя задача:\n\n"
+ "1. **Язык:** Напиши отчёт полностью на " + (lang == null ? "русском" : lang)
+ " языке.\n"
+ "2. **Структура:** Отчёт должен иметь чёткую структуру: введение, основная часть с несколькими разделами и подразделами, и заключение.\n"
+ "3. **Форматирование:** Используй Markdown. Для главных заголовков разделов используй `##`, для подзаголовков — `###`. Для списков используй `-`.\n"
+ "4. **Стиль:** Преврати разрозненные тезисы в единую, связную и хорошо написанную статью. Не просто перечисляй факты, а анализируй и обобщай их.\n"
+ "5. **Ограничение:** Используй только ту информацию, которая дана в собранных данных. Не придумывай ничего от себя.\n\n"
+ "Начинай отчёт с главного заголовка.";
return "You are a professional AI analyst. Your task is to write a detailed, structured, and well-written report based on the provided data."
+
"\n\n" +
"IMPORTANT: Do not ask any clarifying questions at the end. Do not write any personal introductions or conclusions outside of the report's content. Your response must be ONLY the report itself and nothing more."
+
"\n\n" +
"### Research Topic:\n" +
originalQuery + "\n\n" +
"### Collected Data (Learnings):\n" +
learningsAsString + "\n\n" +
"### Your Task:\n" +
"1. **Language:** Write the report entirely in the " + (lang == null ? "English" : lang)
+ " language.\n" +
"2. **Structure:** The report must have a clear structure: an introduction, a main body with several sections and subsections, and a conclusion.\n"
+
"3. **Formatting:** Use Markdown. For main section headings, use `##`. For subsections, use `###`. For lists, use `-`.\n"
+
"4. **Style:** Transform the disjointed learnings into a single, cohesive, and well-written article. Do not just list the facts; analyze, summarize, and build a logical narrative.\n"
+
"5. **Constraint:** Use ONLY the information provided in the collected data. Do not add any information that is not present in the source learnings.\n\n"
+
"Start the report with a main title (using `#`).";
}
private String buildChartDataPrompt(String learningsAsString) {