BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr
Add AI email content generation module
hwliang67d20a58ccd1
diff --git a/conf/supplier/template/Anthropic/config.json b/conf/supplier/template/Anthropic/config.jsonnew file mode 100644index 00000000..bdfb37a9--- /dev/null+++ b/conf/supplier/template/Anthropic/config.json@@ -0,0 +1,13 @@+{+ "supplierTitle": "Anthropic",+ "supplierName": "Anthropic",+ "baseUrl": "",+ "baseUrlExample": "https://api.anthropic.com/v1/",+ "isUseUrlExample": true,+ "apiKey": "",+ "home": "https://www.anthropic.com",+ "help": "https://docs.anthropic.com/en/api/openai-sdk",+ "status": true,+ "sort": 3,+ "icon":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAB3VBMVEX6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf6+vf5+fb7+/j4+PXp6ebm5uTm5uPu7uvx8e78/PnPz8xISEc9PTw7OzpnZ2bv7+z9/frAwL5CQkE8PDyGhoUUFBQWFhYVFRUiIiL+/vvk5OI/Pz4YGBh3d3aGhoStrasdHR0ZGRkXFxc3Nzfd3dvMzMkpKSn19fJjY2JOTk01NTWfn5309PFfX17Pz80rKyuwsK54eHdVVVXw8O2pqaccHBuKiolCQkLq6ue+vrshISElJSXDw8Hj4+Ho6OVFRUSFhYTt7epNTUwVFRZ7e3qCgoCxsa8eHh4qKirOzsz///2WlpU6Ojng4N3JycYoKCf29vM2NjaZmZegoJ6ioqAgICAaGhqjo6Hz8/BbW1vS0tAuLi1ZWVjy8u+lpaQbGxuOjo0mJibHx8Th4d48PDtQUE+BgYB/f36AgH58fHs0NDR+fny1t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uTFAMTIESANMNkAyOzVCDL2NTIxMzEHMQHy4BIoEouAOoXEXTyQjWVAAAAAElFTkSuQmCC"+}\ No newline at end of filediff --git a/conf/supplier/template/Anthropic/embedding.json b/conf/supplier/template/Anthropic/embedding.jsonnew file mode 100644index 00000000..0637a088--- /dev/null+++ b/conf/supplier/template/Anthropic/embedding.json@@ -0,0 +1 @@+[]\ No newline at end of filediff --git a/conf/supplier/template/Anthropic/models.json b/conf/supplier/template/Anthropic/models.jsonnew file mode 100644index 00000000..f9492c84--- /dev/null+++ b/conf/supplier/template/Anthropic/models.json@@ -0,0 +1,20 @@+[+ {+ "title": "",+ "supplierName": "DeepSeek",+ "modelName": "deepseek-reasoner",+ "capability": [+ "llm"+ ],+ "status": false+ },+ {+ "title": "",+ "supplierName": "DeepSeek",+ "modelName": "deepseek-chat",+ "capability": [+ "llm"+ ],+ "status": true+ }+]\ No newline at end of filediff --git a/conf/supplier/template/DeepSeek/config.json b/conf/supplier/template/DeepSeek/config.jsonnew file mode 100644index 00000000..6f4133d6--- /dev/null+++ b/conf/supplier/template/DeepSeek/config.json@@ -0,0 +1,13 @@+{+ "supplierTitle": "DeepSeek",+ "supplierName": "DeepSeek",+ "baseUrl": "",+ "baseUrlExample": "https://api.deepseek.com/v1",+ "isUseUrlExample": true,+ "apiKey": "",+ "home": "https://www.deepseek.com",+ "help": "https://api-docs.deepseek.com",+ "status": true,+ "sort": 4,+ "icon":"data:image/gif;base64,R0lGODlhGAAYAPe6AE1s/k1q/kxr/k5r/v39/01u/kts/kxq/k1t/k5t/lZw/ktq/kxu/t/k/09q/vv8/09o/vn5/3qQ/mWA/kxt/k9s/k5s/k5u/rzC/09u/vP1/1Bj/tPW/1Nk/aOx/rvC/qa0/sjS/4qc/mN+/lF0/qa1/oaZ/0Zj/lNz/tDS/lBw/k5q/uPr/5ur/k1p/rPA/oOb/k9w/v7+/1Fs/tXc/1Bv/lNt/bzH/9nf/ufo/+br/nyU/vn6/3WU/tre/3mJ/mJp/nmQ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gH9+fXx7enl4d3Z1dHNycXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1JRUE9OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy4tLCsqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MCwoJCAcGBQQDAgEAACH5BAEAALoALAAAAAAYABgAAAj/AHUJHEiwoMGDCBMqXMiQIA9RhAaiMqLQx4swLZr00aQKg8AHW1wVNCSQFYwsAgbkEpALgIKBGhDUkiDQFqUiunLcoWAhl8+fASTp0CUDSKUDkDpVwURK160EAX5KzXXABg5dV6xEBTDgEaNBKrAUmiqVS4c1uvhkyGWAxBNdRxScwWUpQYyoPxHACTCLg649B4YkEgjAxMAGdAyk9KlFjhsIm0rlSkNgYIUpBe18aUQh1w8WgbogAABASGWBFxKcHriqzoZcBf7oymMm1xgRBFstkGUQEAoHuSKF+lQm1wwmBEFA6HHQERIGAhSBMRBgwgOCowAsUXLQC5ufFaDcYjCIKNYJPwIXiUkhMIoLnw6IIDzFgMwHgXEKvBE4wWeSQwhFsEMBl7wixSQAZMJJAzTQsoIFsOARAUIe1GDKAgD4NIAAVITgRAmepCJIQm3MIYEaaIwQBCh6NOTiizDGeFBAADs="+}\ No newline at end of filediff --git a/conf/supplier/template/DeepSeek/embedding.json b/conf/supplier/template/DeepSeek/embedding.jsonnew file mode 100644index 00000000..0637a088--- /dev/null+++ b/conf/supplier/template/DeepSeek/embedding.json@@ -0,0 +1 @@+[]\ No newline at end of filediff --git a/conf/supplier/template/DeepSeek/models.json b/conf/supplier/template/DeepSeek/models.jsonnew file mode 100644index 00000000..f9492c84--- /dev/null+++ b/conf/supplier/template/DeepSeek/models.json@@ -0,0 +1,20 @@+[+ {+ "title": "",+ "supplierName": "DeepSeek",+ "modelName": "deepseek-reasoner",+ "capability": [+ "llm"+ ],+ "status": false+ },+ {+ "title": "",+ "supplierName": "DeepSeek",+ "modelName": "deepseek-chat",+ "capability": [+ "llm"+ ],+ "status": true+ }+]\ No newline at end of filediff --git a/conf/supplier/template/Gemini/config.json b/conf/supplier/template/Gemini/config.jsonnew file mode 100644index 00000000..fd2f7f01--- /dev/null+++ b/conf/supplier/template/Gemini/config.json@@ -0,0 +1,13 @@+{+ "supplierTitle": "Gemini",+ "supplierName": "Gemini",+ "baseUrl": "",+ "baseUrlExample": "https://generativelanguage.googleapis.com/v1beta/openai/",+ "isUseUrlExample": true,+ "apiKey": "",+ "home": "https://ai.google.dev",+ "help": "https://ai.google.dev/gemini-api/docs/openai",+ "status": true,+ "sort": 2,+ "icon":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAMAAABg3Am1AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyFpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDE0IDc5LjE1MTQ4MSwgMjAxMy8wMy8xMy0xMjowOToxNSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChXaW5kb3dzKSIgeG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8Z+X7eExtpbsuKgvc363uz/w5W9os1QpbLvMKa1HbKAk5Cw//TnWqHAytM7/eKdd5LN2JdFhdWUhNuwT6+crqJsvb0+QIj8+b16Vbu74e3/4/fsPr9p4o+iwGmS43ZVw+vdc5u/3vPdc7SA5d/wVZDpcITihJO+kZinxrY897qZ37gpQJfkwOPr+s+/6Lkj8aAjV8WoftiwrLtMpLJctbVL8boeeLrqZ62WYLCR5og+X5Pf7pIsXMF01LcyOY/xYI3m+snHNIf+0+aRN4v4j8NbYL96pXWxtm+czJdV3e62fcxl7/rxkbBvfb5pT6W5511g701U0u3A7llUopCesZCKfsJnecZq+sgyapLX/+3tU7iHSpDvnqlvXrSKRr9x5uBzkInU////CgYMBAAAAQB0Uk5T////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AFP3ByUAAALdSURBVHjaYvhPImDAId5gRKIGDg7SNHzv748nSUNDv50RSRo4Jk3hIEWD9yS7d1rxJGjIsZvSrrWLeA2CIPWyjLOJ1pAzJVVLVmL3YmI1eEPUP31ykEgNHCD1jE+fePwjToMRTH0T01JiNNz78BakXhOo/nD3QsIavD+8bYWr19ONJqTBW06uVcJWBaZeNy4avwag+qQUiPqpQPVxcbxbovFpOC2/B6g+r7BeiWlqtl41UPkWKytW3BqOy+8JCAwGqw+CqLeyslK3UsShwZf7+nWg+k8fVxxZG3T3UHUmULk6i7q6+v3ISiwaVm69eXPOumcKCvpHj6z9BlLPawVWfV9IyFCoYzuaBl+us2fPsq0ztdxkoD9jn8ONQz8zeVnA6oXAwNBQsQ6hIXSNcBQQsIneNrX85RUe4iAgwPwzk4VFQ10Irt7QUCiSdRFYwxphKSC4fPnMidvHLl18BdSwSsCNuUuaxVXjPlw1FESyAjVwfhUHAX7+E3ybL5QXHLha8Sbd7WSX9EOwBkMUkJAPdpI/pzA/P79yGp8ZSMO1ijcubie172BoSAB7A+pp/7/Kaav5zKwfvWb4vZGnRsdPWzXrIdhJUNX3kyXRgjX072oTkyWPPlfNa+QpcrE/qXonC+oJkPrkOiwRN3O+yZKwz50ME+BWwHQkSOJIGg9iPcO+VBWDrZiofQemo0MQZ+J7Hhv2AmzFNB17bVWwDg2NfHzJO8aTvQdoRUlRM8hRIB2ukvgzEFBH5+Mf7jzTmidPBOqQlpYklEVjIFY4NzuCdHRVEi4E3r9ou/XD3TmxxXGy30lWYoqZBW23bERynZcBdVwhriBzqrURycjtXdbiIkichv21fywyxMR6l50itjBe/8dCxkdMbBvRpffLnUANPmLGxFcos8rKIpafI6EGMi5Ti4jYS0qlOFdNTYakWrRUre88SRp29PVNJ63pYG5OYlujdAOJGnACgAADAA2AKFD5t3eSAAAAAElFTkSuQmCC"+}\ No newline at end of filediff --git a/conf/supplier/template/Gemini/embedding.json b/conf/supplier/template/Gemini/embedding.jsonnew file mode 100644index 00000000..0637a088--- /dev/null+++ b/conf/supplier/template/Gemini/embedding.json@@ -0,0 +1 @@+[]\ No newline at end of filediff --git a/conf/supplier/template/Gemini/models.json b/conf/supplier/template/Gemini/models.jsonnew file mode 100644index 00000000..32960f8c--- /dev/null+++ b/conf/supplier/template/Gemini/models.json@@ -0,0 +1,2 @@+[+]\ No newline at end of filediff --git a/conf/supplier/template/Grok/config.json b/conf/supplier/template/Grok/config.jsonnew file mode 100644index 00000000..6cb3ecb7--- /dev/null+++ b/conf/supplier/template/Grok/config.json@@ -0,0 +1,13 @@+{+ "supplierTitle": "Grok",+ "supplierName": "Grok",+ "baseUrl": "",+ "baseUrlExample": "https://api.moonshot.cn/v1",+ "isUseUrlExample": true,+ "apiKey": "",+ "home": "https://www.x.ai",+ "help": "https://docs.x.ai/docs/guides/migration",+ "status": true,+ "sort": 6,+ "icon":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAw9pVFh0WE1MOm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////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AFP3ByUAAAMySURBVHjaXJN3lBRFEMZ7Dm4Z7lYO7+BYb3GO8bxe11vOJSM5GDArJgQFFRU9wZxgRMnBnBMoKIg5AQIGgoIBAyrqqSjmiBFUdKamvqV6Zp9/+L153TNVv6nqrupWBdEH496s2ru+3jyi+nozV5368p+dxacKhU9PA3BhsjaZdEXxqPUnYryohwEebkaf/OR8IApF8Ujhyfm6EPYrAryLbBuxFgGtw6LKyrHaruiuTkFFqGNAiyRTHx0FSaDy1gB91bfIiJPIBHcRi4j8BK4459dhOEKdjjBOGmqg5Yw1Tx1w+EBA/Nc89DoSTmu1XwwEGRvXjuFInW982kL79cuRIW+QujQGUrCPibxDzbAS37/Aa9GTkpcUIwSes0Acjx6yo903XyzZA7tv4OObXPJrW8RAkMdW5icPLC4Szc8xP2NTBFwVAfZf8v8qrKMy7WYx4Xn5ehthz4S3r9oLIZGL/szjMaVJtprBzEazjtsntqGERDBA4HQ4ib9LOzobBCl8/hPftawb/9hckfU73WCA0MV05n/hSjUIVTxgEfAqdxlo5+/bdksEBLiJeSe0JEMpn9gWG7GYeYvE9qIUgcZS5veggwwqP5oNJDTeYV6ILMWLFOAf5k0IQrR8ay5cXxL9wdwbexYB2eVnXfg6uMM231wKXxrn4jA++Bd78n/A1fY9fGw7lG22YMlCCMcx/+BMSZleGEA6cSjziJp0ujYVhOSj5H3mZzGNyBus9pfuyzbuZO5aagNaS1vvHcv8GJrIjwDbHBaM48c7AK1bSCM6nnk387kdnWryU95uao7pieP8fEcS827j+Uf2vbKb1Hn0JFhip20fqq8gPcNRj9go6c9FDTjjAlgp8n2quFytAGln5O+wEyG2j+rR+MBBs147AU6J7FYAp1Jdhur0lyORtoLQkuNa069GJssUwxxdtFKNcL4+G54xEZUlPSedDCOvAVK4XxXeQD/PbSvhqDykcjIn3I+8RAlM7K4KXdvjNyuXq6urm5rLqanyEn2oXK4auN5c3ieGAI6D/8mWqn38YnS7C4WjN7XqffGDLzU0NJzXq9c+Rmc1DDn/7+Hm+u8SYABKi5wgnR135gAAAABJRU5ErkJggg=="+}\ No newline at end of filediff --git a/conf/supplier/template/Grok/embedding.json b/conf/supplier/template/Grok/embedding.jsonnew file mode 100644index 00000000..0637a088--- /dev/null+++ b/conf/supplier/template/Grok/embedding.json@@ -0,0 +1 @@+[]\ No newline at end of filediff --git a/conf/supplier/template/Grok/models.json b/conf/supplier/template/Grok/models.jsonnew file mode 100644index 00000000..0637a088--- /dev/null+++ b/conf/supplier/template/Grok/models.json@@ -0,0 +1 @@+[]\ No newline at end of filediff --git a/conf/supplier/template/Kimi/config.json b/conf/supplier/template/Kimi/config.jsonnew file mode 100644index 00000000..9e8055b4--- /dev/null+++ b/conf/supplier/template/Kimi/config.json@@ -0,0 +1,13 @@+{+ "supplierTitle": "Kimi",+ "supplierName": "Kimi",+ "baseUrl": "",+ "baseUrlExample": "https://api.moonshot.cn/v1",+ "isUseUrlExample": true,+ "apiKey": "",+ "home": "https://platform.moonshot.cn",+ "help": "https://platform.moonshot.cn/docs/guide/start-using-kimi-api",+ "status": true,+ "sort": 5,+ "icon":"data:image/gif;base64,R0lGODlhGAAYAOZvAIuLi3Z2dk1NTU9PT42NjQwMDEtLSxoaGs7OzhgYGLi4uJCQkA4ODhwcHKGhoZ2dndHR0SoqKnNzcwAjSh0dHXl5eXh4eDMzMzAwMKSkpObm5iwsLOrq6r29vYyMjEBAQABTrLm5udfX17CwsAAkTGtra/Ly8oODgwDE/62trWRiX6+vr46Oju7u7igoKFhYWAB71H9/f7y8vMzMzE5OTt/Y0D8/PxMTExISEhcXF11dXS4uLgBgyENDQxEREVtbW7e3t2pqallZWQACAyMjI1xcXNra2uLi4pWVlUJCQi8vLwA2ejs7O3x8fLS0tD06NwB+3FpaWmdnZ/f39z09PT4+PgBx+b6+vl5eXpiYmPv7+xQUFJeXl1ZWVgUDATw8PBYWFtTU1CYmJrq6ug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YjUtMzdlNC1lMjRlLWE5ZDQtNjBkYzYzYzA1ODVjIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjU2OWMwNWI1LTM3ZTQtZTI0ZS1hOWQ0LTYwZGM2M2MwNTg1YyIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PgH//v38+/r5+Pf29fTz8vHw7+7t7Ovq6ejn5uXk4+Lh4N/e3dzb2tnY19bV1NPS0dDPzs3My8rJyMfGxcTDwsHAv769vLu6ubi3trW0s7KxsK+urayrqqmop6alpKOioaCfnp2cm5qZmJeWlZSTkpGQj46NjIuKiYiHhoWEg4KBgH9+fXx7enl4d3Z1dHNycXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1JRUE9OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy4tLCsqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MCwoJCAcGBQQDAgEAACH5BAEAAG8ALAAAAAAYABgAAAf/gG+Cb2ELZlEDBgKLAgYDL1IECIODUz9umJmam240HINnEZyjmwcagjakqpkubwqrsG4PQrGrSReaSjpVmg1FKmRLMCSaYg2aD20QmghtNV5WKDyaCTiaBG0ymTttbU9uIFATmj5smgBtQJllbTOYQ5xsBedtTphbbWk5qmzmmegtrqhZ08aEgiCk+tHrxrCNljZdRin818aIBAtNKmw40caBxHkUU2xC0gbNqAIM6IXYxKINl1EMwGjy0GbMJmxZRt0goslBGxGbMrRZMYoCFU1MAgzY9CXAh1EYAtRSheXIVFIQ3iy4uinAoBhcMZWg9KaDgQP90qpNm6DHiEGBAQAAOw=="+}\ No newline at end of filediff --git a/conf/supplier/template/Kimi/embedding.json b/conf/supplier/template/Kimi/embedding.jsonnew file mode 100644index 00000000..0637a088--- /dev/null+++ b/conf/supplier/template/Kimi/embedding.json@@ -0,0 +1 @@+[]\ No newline at end of filediff --git a/conf/supplier/template/Kimi/models.json b/conf/supplier/template/Kimi/models.jsonnew file mode 100644index 00000000..0637a088--- /dev/null+++ b/conf/supplier/template/Kimi/models.json@@ -0,0 +1 @@+[]\ No newline at end of filediff --git a/conf/supplier/template/OpenAI/config.json b/conf/supplier/template/OpenAI/config.jsonnew file mode 100644index 00000000..0e75aa92--- /dev/null+++ b/conf/supplier/template/OpenAI/config.json@@ -0,0 +1,13 @@+{+ "supplierTitle": "OpenAI",+ "supplierName": "openai",+ "baseUrl": "",+ "baseUrlExample":"https://api.openai.com/v1",+ "isUseUrlExample": true,+ "apiKey": "",+ "home": "https://openai.com",+ "help": "https://platform.openai.com/docs/api-reference/introduction",+ "status": true,+ "sort": 1,+ "icon":"data:image/gif;base64,R0lGODlhGAAYAPecALq6us/PzwcHBzExMVZWVjQ0NDc3NyoqKvf397u7uwwMDPz8/M7OzlFRUUlJSevr6/b29k5OToSEhA8PD01NTTw8PDU1NeTk5BwcHAYGBnt7eykpKV1dXVhYWCMjI+Hh4efn5wsLC6Ojo0VFRbKysqKiom5ubu/v73h4eJmZmcXFxcLCwnNzc66urrGxsXJycre3t/r6+mFhYZiYmOXl5UhISAEBAVRUVHBwcKioqEJCQmVlZaurq1tbW+zs7NXV1d3d3ePj42xsbGlpac3NzWZmZkBAQJ2dnZubm1lZWX5+fj8/P/39/Ts7Oz4+PoGBgYaGhiQkJHR0dBkZGby8vCwsLHd3d4uLiw0NDRgYGBcXF46OjicnJ09PT319ffHx8aSkpK2trbCwsCsrKwkJCczMzMjIyLi4uNzc3FNTUwgICAoKCsnJyZycnKenpwQEBHl5eVVVVWRkZIqKiuDg4FpaWiIiInZ2dkxMTHx8fB4eHjY2NkRERJOTk5GRkcTExKmpqdTU1OLi4gMDAxMTE2hoaEpKSurq6pWVlRYWFvPz8z09PQICAvDw8MPDw7m5ucbGxoeHhyAgINPT05eXl3V1db+/vygoKKamppaWlqCgoAAAAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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oOGtMhIiMpNhAgOBggok3MIpixaBLuDqmECwi0IaAsFsMsAp5wNOMDZl4mRh7sBIGGpsUiLQz6Y2YTZBEYhiU48NOwhKOcBJxKYSBWdzqrAJKScgHjZRwyBYYQynAJtmCLSwiVOJhE5uc/qjYNAPSBLHo08hcIANTs31kBAOAyWR0BVWFHDeJvydsAljQmyCAAIDbBKCGBLY4ABslXCx4BGc3LGJC5wgsQkPAp2hwCYZMMRJEG/ssSAgmGxSg0A+bKKgQI2ssBEnHCSkSVIj6UCQBJvU0VAfCfEh3xObeOCGQ0VssoYJlORxySZRsDFQjpKcxAMWI21SBVACXaDHJpacBBYDJwglQBw4iLaJCG461MIUIznwwUMBAQA7"+}\ No newline at end of filediff --git a/conf/supplier/template/OpenAI/embedding.json b/conf/supplier/template/OpenAI/embedding.jsonnew file mode 100644index 00000000..0637a088--- /dev/null+++ b/conf/supplier/template/OpenAI/embedding.json@@ -0,0 +1 @@+[]\ No newline at end of filediff --git a/conf/supplier/template/OpenAI/models.json b/conf/supplier/template/OpenAI/models.jsonnew file mode 100644index 00000000..0637a088--- /dev/null+++ b/conf/supplier/template/OpenAI/models.json@@ -0,0 +1 @@+[]\ No newline at end of filediff --git a/core/api/askai/askai.go b/core/api/askai/askai.gonew file mode 100644index 00000000..5612a53c--- /dev/null+++ b/core/api/askai/askai.go@@ -0,0 +1,59 @@+package askai++import (+ v1 "billionmail-core/api/askai/v1"+ "billionmail-core/utility/types/api_v1"+)++type IAskAiV1 interface {+ // Supplier related methods+ List(req *v1.ListReq) (res *v1.ListRes, err error)+ Models(req *v1.ModelsReq) (res *v1.ModelsRes, err error)+ AddModel(req *v1.AddModelReq) (res *v1.AddModelRes, err error)+ RemoveModel(req *v1.RemoveModelReq) (res *v1.RemoveModelRes, err error)+ SetSupplierConfig(req *v1.SetSupplierConfigReq) (res *api_v1.StandardRes, err error)+ Testing(req *v1.TestingReq) (res *v1.TestingRes, err error)+ GetSupplierConfig(req *v1.GetSupplierConfigReq) (res *v1.GetSupplierConfigRes, err error)+ SetSupplierStatus(req *v1.SetSupplierStatusReq) (res *api_v1.StandardRes, err error)+ SetModelStatus(req *v1.SetModelStatusReq) (res *api_v1.StandardRes, err error)+ AddSupplier(req *v1.AddSupplierReq) (res *v1.AddSupplierRes, err error)+ RemoveSupplier(req *v1.RemoveSupplierReq) (res *v1.RemoveSupplierRes, err error)+ SetModelTitle(req *v1.SetModelTitleReq) (res *v1.SetModelTitleRes, err error)+ SetModelCapability(req *v1.SetModelCapabilityReq) (res *v1.SetModelCapabilityRes, err error)+ ModifyModel(req *v1.ModifyModelReq) (res *v1.ModifyModelRes, err error)+ Status(req *v1.StatusReq) (res *v1.StatusRes, err error)++ // Project related methods+ Create(req *v1.CreateReq) (res *v1.CreateRes, err error)+ GetBaseInfo(req *v1.GetBaseInfoReq) (res *v1.GetBaseInfoRes, err error)+ ModifyBaseInfo(req *v1.ModifyBaseInfoReq) (res *v1.ModifyBaseInfoRes, err error)+ ModifyKnowledgeBaseFile(req *v1.ModifyKnowledgeBaseFileReq) (res *v1.ModifyKnowledgeBaseFileRes, err error)+ CreateKnowledgeBaseFile(req *v1.CreateKnowledgeBaseFileReq) (res *v1.CreateKnowledgeBaseFileRes, err error)+ RemoveKnowledgeBaseFile(req *v1.RemoveKnowledgeBaseFileReq) (res *v1.RemoveKnowledgeBaseFileRes, err error)+ GetCompanyProfile(req *v1.GetCompanyProfileReq) (res *v1.GetCompanyProfileRes, err error)+ ModifyCompanyProfile(req *v1.ModifyCompanyProfileReq) (res *v1.ModifyCompanyProfileRes, err error)+ GetStyleConfig(req *v1.GetStyleConfigReq) (res *v1.GetStyleConfigRes, err error)+ ModifyStyleConfig(req *v1.ModifyStyleConfigReq) (res *v1.ModifyStyleConfigRes, err error)+ GetSitemap(req *v1.GetSitemapReq) (res *v1.GetSitemapRes, err error)+ RemoveSitemapNode(req *v1.RemoveSitemapNodeReq) (res *v1.RemoveSitemapNodeRes, err error)+ AddSitemapNode(req *v1.AddSitemapNodeReq) (res *v1.AddSitemapNodeRes, err error)+ GetFooter(req *v1.GetFooterReq) (res *v1.GetFooterRes, err error)+ ModifyFooter(req *v1.ModifyFooterReq) (res *v1.ModifyFooterRes, err error)+ GetPrompt(req *v1.GetPromptReq) (res *v1.GetPromptRes, err error)+ ModifyPrompt(req *v1.ModifyPromptReq) (res *v1.ModifyPromptRes, err error)+ UploadImage(req *v1.UploadImageReq) (res *v1.UploadImageRes, err error)+ RemoveImage(req *v1.RemoveImageReq) (res *v1.RemoveImageRes, err error)+ ModifyImage(req *v1.ModifyImageReq) (res *v1.ModifyImageRes, err error)+ GetImages(req *v1.GetImagesReq) (res *v1.GetImagesRes, err error)++ // Chat related methods+ CreateChat(req *v1.CreateChatReq) (res *v1.CreateChatRes, err error)+ GetChatList(req *v1.GetChatListReq) (res *v1.GetChatListRes, err error)+ Info(req *v1.InfoReq) (res *v1.InfoRes, err error)+ Chat(req *v1.ChatReq) (res *v1.ChatRes, err error)+ Stop(req *v1.StopReq) (res *v1.StopRes, err error)+ GetHtml(req *v1.GetHtmlReq) (res *v1.GetHtmlRes, err error)+ ModifyHtml(req *v1.ModifyHtmlReq) (res *v1.ModifyHtmlRes, err error)+ RemoveChat(req *v1.RemoveChatReq) (res *v1.RemoveChatRes, err error)+ CopyChat(req *v1.CopyChatReq) (res *v1.CopyChatRes, err error)+}diff --git a/core/api/askai/v1/chat.go b/core/api/askai/v1/chat.gonew file mode 100644index 00000000..70ec6172--- /dev/null+++ b/core/api/askai/v1/chat.go@@ -0,0 +1,96 @@+package v1++import (+ "billionmail-core/utility/types/api_v1"++ "github.com/gogf/gf/v2/frame/g"+)++type CreateChatReq struct {+ g.Meta `path:"/askai/chat/create_chat" method:"post" tags:"AskAi" summary:"create chat"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ AddType int `json:"add_type" dc:"add type" v:"required#add type is required"` // 1: add chat, 2: add knowledge base file+ TempName string `json:"temp_name" dc:"temporary name" v:"required#temporary name is required"` // Temporary name for the chat or knowledge base file+}++type CreateChatRes struct {+ api_v1.StandardRes+}++type GetChatListReq struct {+ g.Meta `path:"/askai/chat/get_chat_list" method:"post" tags:"AskAi" summary:"get chat list"`+}++type GetChatListRes struct {+ api_v1.StandardRes+}++// InfoReq is the request structure for retrieving chat information in AskAi.+type InfoReq struct {+ g.Meta `path:"/askai/chat/info" method:"post" tags:"AskAi" summary:"get chat info"`+ ChatId string `json:"chatId" dc:"chat id" v:"required#chat id is required"`+}++type InfoRes struct {+ api_v1.StandardRes+}++// ChatReq is the request structure for sending a chat message in AskAi.+type ChatReq struct {+ g.Meta `path:"/askai/chat/chat" method:"post,get" tags:"AskAi" summary:"send chat message"`+ ChatId string `json:"chatId" dc:"chat id" v:"required#chat id is required"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+ ModelId string `json:"model_id" dc:"model id" v:"required#model id is required"`+ Content string `json:"content" dc:"content" v:"required#content is required"`+ IsText bool `json:"is_text" dc:"is text"` // true: text, false: json+}+type ChatRes struct {+ api_v1.StandardRes+}++type RemoveChatReq struct {+ g.Meta `path:"/askai/chat/remove_chat" method:"post" tags:"AskAi" summary:"remove chat"`+ ChatId string `json:"chatId" dc:"chat id" v:"required#chat id is required"`+}+type RemoveChatRes struct {+ api_v1.StandardRes+}++// StopReq is the request structure for stopping a chat in AskAi.+type StopReq struct {+ g.Meta `path:"/askai/chat/stop" method:"post" tags:"AskAi" summary:"stop chat"`+ ChatId string `json:"chatId" dc:"chat id" v:"required#chat id is required"`+}+type StopRes struct {+ api_v1.StandardRes+}++// GetHtmlReq is the request structure for retrieving HTML content in AskAi.+type GetHtmlReq struct {+ g.Meta `path:"/askai/chat/get_html" method:"post" tags:"AskAi" summary:"get html content"`+ ChatId string `json:"chatId" dc:"chat id" v:"required#chat id is required"`+}+type GetHtmlRes struct {+ api_v1.StandardRes+}++// ModifyHtmlReq is the request structure for modifying HTML content in AskAi.+type ModifyHtmlReq struct {+ g.Meta `path:"/askai/chat/modify_html" method:"post" tags:"AskAi" summary:"modify html content"`+ ChatId string `json:"chatId" dc:"chat id" v:"required#chat id is required"`+ Content string `json:"content" dc:"content" v:"required#content is required"`+}+type ModifyHtmlRes struct {+ api_v1.StandardRes+}++// CopyChatReq is the request structure for copying a chat in AskAi.+type CopyChatReq struct {+ g.Meta `path:"/askai/chat/copy_chat" method:"post" tags:"AskAi" summary:"copy chat"`+ ChatId string `json:"chatId" dc:"chat id" v:"required#chat id is required"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+}++type CopyChatRes struct {+ api_v1.StandardRes+}diff --git a/core/api/askai/v1/project.go b/core/api/askai/v1/project.gonew file mode 100644index 00000000..09f58bb4--- /dev/null+++ b/core/api/askai/v1/project.go@@ -0,0 +1,243 @@+package v1++import (+ "billionmail-core/utility/types/api_v1"++ "github.com/gogf/gf/v2/frame/g"+)++// CreateReq is the request structure for creating a new project configuration in AskAi.+type CreateReq struct {+ g.Meta `path:"/askai/project/create" method:"post" tags:"AskAi" summary:"create project config"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ Urls []string `json:"urls" dc:"urls"`+}+type CreateRes struct {+ api_v1.StandardRes+}++// GetBaseInfoReq is the request structure for retrieving the base information of a project in AskAi.+type GetBaseInfoReq struct {+ g.Meta `path:"/askai/project/get_base_info" method:"post" tags:"AskAi" summary:"get project base info"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+}+type GetBaseInfoRes struct {+ api_v1.StandardRes+}++// ModifyBaseInfoReq is the request structure for modifying the base information of a project in AskAi.+type ModifyBaseInfoReq struct {+ g.Meta `path:"/askai/project/modify_base_info" method:"post" tags:"AskAi" summary:"modify project base info"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ ProjectName string `json:"project_name" dc:"project name" v:"required#project name is required"`+ Description string `json:"description" dc:"project description"`+ Industry string `json:"industry" dc:"project industry"`+ PrimaryLogo string `json:"primary_logo" dc:"primary logo"`+ SecondaryLogo string `json:"secondary_logo" dc:"secondary logo"`+ Favicon string `json:"favicon" dc:"favicon"`+}+type ModifyBaseInfoRes struct {+ api_v1.StandardRes+}++// ModifyKnowledgeBaseFileReq is the request structure for modifying a knowledge base file in AskAi.+type ModifyKnowledgeBaseFileReq struct {+ g.Meta `path:"/askai/project/modify_knowledge_base_file" method:"post" tags:"AskAi" summary:"modify knowledge base file"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ Kid string `json:"kid" dc:"knowledge base file id" v:"required#knowledge base file id is required"`+ Title string `json:"title" dc:"title" v:"required#title is required"`+ Content string `json:"content" dc:"content" v:"required#content is required"`+}+type ModifyKnowledgeBaseFileRes struct {+ api_v1.StandardRes+}++// CreateKnowledgeBaseFileReq is the request structure for creating a new knowledge base file in AskAi.+type CreateKnowledgeBaseFileReq struct {+ g.Meta `path:"/askai/project/create_knowledge_base_file" method:"post" tags:"AskAi" summary:"create knowledge base file"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ Title string `json:"title" dc:"title" v:"required#title is required"`+ Content string `json:"content" dc:"content" v:"required#content is required"`+}+type CreateKnowledgeBaseFileRes struct {+ api_v1.StandardRes+}++// RemoveKnowledgeBaseFileReq is the request structure for removing a knowledge base file in AskAi.+type RemoveKnowledgeBaseFileReq struct {+ g.Meta `path:"/askai/project/remove_knowledge_base_file" method:"post" tags:"AskAi" summary:"remove knowledge base file"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ Kid string `json:"kid" dc:"knowledge base file id" v:"required#knowledge base file id is required"`+}+type RemoveKnowledgeBaseFileRes struct {+ api_v1.StandardRes+}++// GetCompanyProfileReq is the request structure for retrieving the company profile in AskAi.+type GetCompanyProfileReq struct {+ g.Meta `path:"/askai/project/get_company_profile" method:"post" tags:"AskAi" summary:"get company profile"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+}+type GetCompanyProfileRes struct {+ api_v1.StandardRes+}++// ModifyCompanyProfileReq is the request structure for modifying the company profile in AskAi.+type ModifyCompanyProfileReq struct {+ g.Meta `path:"/askai/project/modify_company_profile" method:"post" tags:"AskAi" summary:"modify company profile"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ LegalCompanyName string `json:"legal_company_name" dc:"legal company name"`+ Website string `json:"website" dc:"website"`+ CompanyProfile string `json:"company_profile" dc:"company profile"`+ Email string `json:"email" dc:"email"`+ Phone string `json:"phone" dc:"phone"`+ SupportUrl string `json:"support_url" dc:"support url"`+}++type ModifyCompanyProfileRes struct {+ api_v1.StandardRes+}++// GetStyleConfigReq is the request structure for retrieving the style configuration of a project in AskAi.+type GetStyleConfigReq struct {+ g.Meta `path:"/askai/project/get_style_config" method:"post" tags:"AskAi" summary:"get style config"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+}++type GetStyleConfigRes struct {+ api_v1.StandardRes+}++// ModifyStyleConfigReq is the request structure for modifying the style configuration of a project in AskAi.+type ModifyStyleConfigReq struct {+ g.Meta `path:"/askai/project/modify_style_config" method:"post" tags:"AskAi" summary:"modify style config"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ AccentColor string `json:"accent_color" dc:"accent color"`+ TextColor string `json:"text_color" dc:"text color"`+ PageBackground string `json:"page_background" dc:"page background"`+ ContainerBackground string `json:"container_background" dc:"container background"`+ LinkSocialColor string `json:"link_social_color" dc:"link social color"`+ LinkFooterColor string `json:"link_footer_color" dc:"link footer color"`+ HeadingFont string `json:"heading_font" dc:"heading font"`+ BodyFont string `json:"body_font" dc:"body font"`+}+type ModifyStyleConfigRes struct {+ api_v1.StandardRes+}++// GetSitemapReq is the request structure for retrieving the sitemap of a project in AskAi.+type GetSitemapReq struct {+ g.Meta `path:"/askai/project/get_sitemap" method:"post" tags:"AskAi" summary:"get sitemap"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+}+type GetSitemapRes struct {+ api_v1.StandardRes+}++// RemoveSitemapNodeReq is the request structure for removing a node from the sitemap of a project in AskAi.+type RemoveSitemapNodeReq struct {+ g.Meta `path:"/askai/project/remove_sitemap_node" method:"post" tags:"AskAi" summary:"remove sitemap node"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ UriPath string `json:"uri_path" dc:"uri path" v:"required#uri path is required"`+}++type RemoveSitemapNodeRes struct {+ api_v1.StandardRes+}++// AddSitemapNodeReq is the request structure for adding a node to the sitemap of a project in AskAi.+type AddSitemapNodeReq struct {+ g.Meta `path:"/askai/project/add_sitemap_node" method:"post" tags:"AskAi" summary:"add sitemap node"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ Title string `json:"title" dc:"title" v:"required#title is required"`+ UriPath string `json:"uri_path" dc:"uri path" v:"required#uri path is required"`+}+type AddSitemapNodeRes struct {+ api_v1.StandardRes+}++// GetFooterReq is the request structure for retrieving the footer configuration of a project in AskAi.+type GetFooterReq struct {+ g.Meta `path:"/askai/project/get_footer" method:"post" tags:"AskAi" summary:"get footer config"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+}+type GetFooterRes struct {+ api_v1.StandardRes+}++// ModifyFooterReq is the request structure for modifying the footer configuration of a project in AskAi.+type ModifyFooterReq struct {+ g.Meta `path:"/askai/project/modify_footer" method:"post" tags:"AskAi" summary:"modify footer config"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ CopyrightText string `json:"copyright_text" dc:"copyright text" v:"required#copyright text is required"`+ Disclaimer string `json:"disclaimer" dc:"disclaimer" v:"required#disclaimer is required"`+}+type ModifyFooterRes struct {+ api_v1.StandardRes+}++// GetPromptReq is the request structure for retrieving the prompt configuration of a project in AskAi.+type GetPromptReq struct {+ g.Meta `path:"/askai/project/get_prompt" method:"post" tags:"AskAi" summary:"get prompt config"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+}+type GetPromptRes struct {+ api_v1.StandardRes+}++// ModifyPromptReq is the request structure for modifying the prompt configuration of a project in AskAi.+type ModifyPromptReq struct {+ g.Meta `path:"/askai/project/modify_prompt" method:"post" tags:"AskAi" summary:"modify prompt config"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ Prompt string `json:"prompt" dc:"prompt" v:"required#prompt is required"`+}+type ModifyPromptRes struct {+ api_v1.StandardRes+}++// UploadImageReq is the request structure for uploading an image to a project in AskAi.+type UploadImageReq struct {+ g.Meta `path:"/askai/project/upload_image" method:"post" tags:"AskAi" summary:"upload image"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ Image string `json:"image" dc:"image" v:"required#image is required"`+ Filename string `json:"filename" dc:"filename" v:"required#filename is required"`+ AltText string `json:"alt_text" dc:"alt text" v:"required#alt text is required"`+ ImageTag string `json:"image_tag" dc:"image tag" v:"required#image tag is required" d:"Image tag is used to identify the image in the project, e.g., 'logo', 'banner', etc."`+}++type UploadImageRes struct {+ api_v1.StandardRes+}++// ModifyImageReq is the request structure for modifying an existing image in a project in AskAi.+type ModifyImageReq struct {+ g.Meta `path:"/askai/project/modify_image" method:"post" tags:"AskAi" summary:"modify image"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ ImageId string `json:"image_id" dc:"image id" v:"required#image id is required"`+ AltText string `json:"alt_text" dc:"alt text" v:"required#alt text is required"`+ ImageTag string `json:"image_tag" dc:"image tag" v:"required#image tag is required" d:"Image tag is used to identify the image in the project, e.g., 'logo', 'banner', etc."`+}+type ModifyImageRes struct {+ api_v1.StandardRes+}++// RemoveImageReq is the request structure for removing an image from a project in AskAi.+type RemoveImageReq struct {+ g.Meta `path:"/askai/project/remove_image" method:"post" tags:"AskAi" summary:"remove image"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+ ImageId string `json:"image_id" dc:"image id" v:"required#image id is required"`+}++type RemoveImageRes struct {+ api_v1.StandardRes+}++// GetImagesReq is the request structure for retrieving images associated with a project in AskAi.+type GetImagesReq struct {+ g.Meta `path:"/askai/project/get_images" method:"post" tags:"AskAi" summary:"get images"`+ Domain string `json:"domain" dc:"domain" v:"required#domain is required"`+}++type GetImagesRes struct {+ api_v1.StandardRes+}diff --git a/core/api/askai/v1/supplier.go b/core/api/askai/v1/supplier.gonew file mode 100644index 00000000..8fca32f1--- /dev/null+++ b/core/api/askai/v1/supplier.go@@ -0,0 +1,174 @@+package v1++import (+ "billionmail-core/utility/types/api_v1"++ "github.com/gogf/gf/v2/frame/g"+)++// ListReq is the request structure for listing AI model suppliers.+type ListReq struct {+ g.Meta `path:"/askai/supplier/list" method:"get,post" tags:"AskAi" summary:"list ai models supplier"`+}++type ListRes struct {+ api_v1.StandardRes+}++// ModelsReq is the request structure for listing AI models of a specific supplier.+type ModelsReq struct {+ g.Meta `path:"/askai/supplier/models" method:"get,post" tags:"AskAi" summary:"list ai models"`+ SupplierName string `json:"supplier_name" dc:"supplier name"`+}++type ModelsRes struct {+ api_v1.StandardRes+}++// AddModelReq is the request structure for adding a new AI model to a supplier.+type AddModelReq struct {+ g.Meta `path:"/askai/supplier/add_model" method:"post" tags:"AskAi" summary:"add ai model"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+ Title string `json:"title" dc:"model title" v:"required#model title is required"`+ ModelId string `json:"model_id" dc:"model id" v:"required#model id is required"`+ MaxTokens int `json:"max_tokens" dc:"max tokens" v:"required#max tokens is required"`+ Capability []string `json:"capability" dc:"capability" v:"required#capability is required"`+}++type AddModelRes struct {+ api_v1.StandardRes+}++// RemoveModelReq is the request structure for removing an AI model from a supplier.+type RemoveModelReq struct {+ g.Meta `path:"/askai/supplier/remove_model" method:"post" tags:"AskAi" summary:"remove ai model"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+ ModelId string `json:"model_id" dc:"model id" v:"required#model id is required"`+}++type RemoveModelRes struct {+ api_v1.StandardRes+}++// SetSupplierConfigReq is the request structure for setting the configuration of an AI model supplier.+type SetSupplierConfigReq struct {+ g.Meta `path:"/askai/supplier/set_supplier_config" method:"post" tags:"AskAi" summary:"set supplier config"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+ BaseUrl string `json:"base_url" dc:"base url" v:"required#base url is required"`+ ApiKey string `json:"api_key" dc:"api key" v:"required#api key is required"`+}++type SetSupplierConfigRes struct {+ api_v1.StandardRes+}++// TestingReq is the request structure for testing the configuration of an AI model supplier.+type TestingReq struct {+ g.Meta `path:"/askai/supplier/testing" method:"post" tags:"AskAi" summary:"test supplier config"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+ BaseUrl string `json:"base_url" dc:"base url" v:"required#base url is required"`+ ApiKey string `json:"api_key" dc:"api key" v:"required#api key is required"`+}+type TestingRes struct {+ api_v1.StandardRes+}++// GetSupplierConfigReq is the request structure for retrieving the configuration of an AI model supplier.+type GetSupplierConfigReq struct {+ g.Meta `path:"/askai/supplier/get_supplier_config" method:"post" tags:"AskAi" summary:"get supplier config"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+}++type GetSupplierConfigRes struct {+ api_v1.StandardRes+}++// SetSupplierStatusReq is the request structure for setting the status of an AI model supplier.+type SetSupplierStatusReq struct {+ g.Meta `path:"/askai/supplier/set_supplier_status" method:"post" tags:"AskAi" summary:"set supplier status"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+ Status bool `json:"status" dc:"status" v:"required#status is required"`+}++type SetSupplierStatusRes struct {+ api_v1.StandardRes+}++// SetModelStatusReq is the request structure for setting the status of an AI model.+type SetModelStatusReq struct {+ g.Meta `path:"/askai/supplier/set_model_status" method:"post" tags:"AskAi" summary:"set model status"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+ ModelId string `json:"model_id" dc:"model id" v:"required#model id is required"`+ Status bool `json:"status" dc:"status" v:"required#status is required"`+}+type SetModelStatusRes struct {+ api_v1.StandardRes+}++// AddSupplierReq is the request structure for adding a new AI supplier.+type AddSupplierReq struct {+ g.Meta `path:"/askai/supplier/add_supplier" method:"post" tags:"AskAi" summary:"add ai supplier"`+ SupplierTitle string `json:"supplier_title" dc:"supplier title" v:"required#supplier title is required"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+ BaseUrl string `json:"base_url" dc:"base url" v:"required#base url is required"`+ ApiKey string `json:"api_key" dc:"api key" v:"required#api key is required"`+}++type AddSupplierRes struct {+ api_v1.StandardRes+}++// RemoveSupplierReq is the request structure for removing an AI supplier.+type RemoveSupplierReq struct {+ g.Meta `path:"/askai/supplier/remove_supplier" method:"post" tags:"AskAi" summary:"remove ai supplier"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+}++type RemoveSupplierRes struct {+ api_v1.StandardRes+}++// SetModelTitleReq is the request structure for setting the title of an AI model.+type SetModelTitleReq struct {+ g.Meta `path:"/askai/supplier/set_model_title" method:"post" tags:"AskAi" summary:"set model title"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+ ModelId string `json:"model_id" dc:"model id" v:"required#model id is required"`+ Title string `json:"title" dc:"title" v:"required#title is required"`+}++type SetModelTitleRes struct {+ api_v1.StandardRes+}++// SetModelCapabilityReq is the request structure for setting the capabilities of an AI model.+type SetModelCapabilityReq struct {+ g.Meta `path:"/askai/supplier/set_model_capability" method:"post" tags:"AskAi" summary:"set model capability"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+ ModelId string `json:"model_id" dc:"model id" v:"required#model id is required"`+ Capability []string `json:"capability" dc:"capability" v:"required#capability is required" d:"llm,vision,tools,text-to-image"`+}+type SetModelCapabilityRes struct {+ api_v1.StandardRes+}++// ModifyModelReq is the request structure for modifying an AI model's details.+type ModifyModelReq struct {+ g.Meta `path:"/askai/supplier/modify_model" method:"post" tags:"AskAi" summary:"modify model"`+ SupplierName string `json:"supplier_name" dc:"supplier name" v:"required#supplier name is required"`+ ModelId string `json:"model_id" dc:"model id" v:"required#model id is required"`+ MaxTokens int `json:"max_tokens" dc:"max tokens" v:"required#max tokens is required"`+ Capability []string `json:"capability" dc:"capability" v:"required#capability is required" d:"llm,vision,tools,text-to-image"`+ Title string `json:"title" dc:"title" v:"required#title is required"`+}++type ModifyModelRes struct {+ api_v1.StandardRes+}++// StatusReq is the request structure for retrieving the status of an AI model supplier's configuration.+type StatusReq struct {+ g.Meta `path:"/askai/supplier/status" method:"get,post" tags:"AskAi" summary:"get supplier config status"`+}+type StatusRes struct {+ api_v1.StandardRes+}diff --git a/core/internal/cmd/cmd.go b/core/internal/cmd/cmd.goindex dfa829c4..8321fcfa 100644--- a/core/internal/cmd/cmd.go+++ b/core/internal/cmd/cmd.go@@ -3,6 +3,7 @@ package cmdimport ("billionmail-core/internal/consts""billionmail-core/internal/controller/abnormal_recipient"+ "billionmail-core/internal/controller/askai""billionmail-core/internal/controller/batch_mail""billionmail-core/internal/controller/campaign""billionmail-core/internal/controller/contact"@@ -32,10 +33,6 @@ import ("billionmail-core/internal/service/timers""context""fmt"- "github.com/gogf/gf/v2/frame/g"- "github.com/gogf/gf/v2/net/ghttp"- "github.com/gogf/gf/v2/os/gcmd"- "github.com/gogf/gf/v2/util/gconv""net/http""net/http/httputil""net/url"@@ -43,6 +40,11 @@ import ("strings""sync""time"++ "github.com/gogf/gf/v2/frame/g"+ "github.com/gogf/gf/v2/net/ghttp"+ "github.com/gogf/gf/v2/os/gcmd"+ "github.com/gogf/gf/v2/util/gconv")var (@@ -248,6 +250,7 @@ var (settings.NewV1(),subscribe_list.NewV1(),operation_log.NewV1(),+ askai.NewV1(),)})diff --git a/core/internal/controller/askai/askai.go b/core/internal/controller/askai/askai.gonew file mode 100644index 00000000..e6cb0ff7--- /dev/null+++ b/core/internal/controller/askai/askai.go@@ -0,0 +1 @@+package askaidiff --git a/core/internal/controller/askai/askai_new.go b/core/internal/controller/askai/askai_new.gonew file mode 100644index 00000000..79ae9d21--- /dev/null+++ b/core/internal/controller/askai/askai_new.go@@ -0,0 +1,7 @@+package askai++type ControllerV1 struct{}++func NewV1() *ControllerV1 {+ return &ControllerV1{}+}diff --git a/core/internal/controller/askai/askai_v1_chat.go b/core/internal/controller/askai/askai_v1_chat.gonew file mode 100644index 00000000..506e1280--- /dev/null+++ b/core/internal/controller/askai/askai_v1_chat.go@@ -0,0 +1,117 @@+package askai++import (+ v1 "billionmail-core/api/askai/v1"+ "billionmail-core/internal/service/askai"+ "context"+)++// Chat related methods+// Info(req *v1.InfoReq) (res *v1.InfoRes, err error)+// Chat(req *v1.ChatReq) (res *v1.ChatRes, err error)+// Stop(req *v1.StopReq) (res *v1.StopRes, err error)+// GetHtml(req *v1.GetHtmlReq) (res *v1.GetHtmlRes, err error)+// ModifyHtml(req *v1.ModifyHtmlReq) (res *v1.ModifyHtmlRes, err error)++func (c *ControllerV1) CreateChat(ctx context.Context, req *v1.CreateChatReq) (res *v1.CreateChatRes, err error) {+ res = &v1.CreateChatRes{}+ chatId, err := askai.CreateChat(req.Domain, req.AddType, req.TempName)+ if err != nil {+ res.SetError(err)+ } else {+ res.Data = map[string]string{"chatId": chatId}+ res.SetSuccess("Chat created successfully")+ }+ return res, nil+}++func (c *ControllerV1) GetChatList(ctx context.Context, req *v1.GetChatListReq) (res *v1.GetChatListRes, err error) {+ res = &v1.GetChatListRes{}+ res.Data, err = askai.GetChatList()+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Chat list retrieved successfully")+ }+ return res, nil+}++func (c *ControllerV1) Info(ctx context.Context, req *v1.InfoReq) (res *v1.InfoRes, err error) {+ res = &v1.InfoRes{}+ res.Data, err = askai.GetChatInfo(req.ChatId)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Chat info retrieved successfully")+ }+ return res, nil+}++func (c *ControllerV1) Chat(ctx context.Context, req *v1.ChatReq) (res *v1.ChatRes, err error) {+ res = &v1.ChatRes{}+ err = askai.Chat(ctx, req.ChatId, req.SupplierName, req.ModelId, req.Content, req.IsText)+ if err != nil {+ res.SetError(err)+ return res, nil+ }+ return+}++func (c *ControllerV1) Stop(ctx context.Context, req *v1.StopReq) (res *v1.StopRes, err error) {+ res = &v1.StopRes{}+ err = askai.Stop(req.ChatId)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Chat stopped successfully")+ }+ return res, nil+}++func (c *ControllerV1) GetHtml(ctx context.Context, req *v1.GetHtmlReq) (res *v1.GetHtmlRes, err error) {+ res = &v1.GetHtmlRes{}+ res.Data, err = askai.GetHtml(req.ChatId)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("HTML content retrieved successfully")+ }+ return res, nil+}++func (c *ControllerV1) ModifyHtml(ctx context.Context, req *v1.ModifyHtmlReq) (res *v1.ModifyHtmlRes, err error) {+ res = &v1.ModifyHtmlRes{}+ err = askai.ModifyHtml(req.ChatId, req.Content)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("HTML content modified successfully")+ }++ return res, nil+}++func (c *ControllerV1) RemoveChat(ctx context.Context, req *v1.RemoveChatReq) (res *v1.RemoveChatRes, err error) {+ res = &v1.RemoveChatRes{}+ // Logic to remove the chat based on req.ChatId+ // This is a placeholder implementation+ err = askai.RemoveChat(req.ChatId)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Chat removed successfully")+ }+ return res, nil+}++func (c *ControllerV1) CopyChat(ctx context.Context, req *v1.CopyChatReq) (res *v1.CopyChatRes, err error) {+ res = &v1.CopyChatRes{}+ chatId, content, err := askai.CopyChat(req.ChatId, req.Domain)+ if err != nil {+ res.SetError(err)+ } else {+ res.Data = map[string]string{"chatId": chatId, "content": content}+ res.SetSuccess("Chat copied successfully")+ }+ return res, nil+}diff --git a/core/internal/controller/askai/askai_v1_project.go b/core/internal/controller/askai/askai_v1_project.gonew file mode 100644index 00000000..543f7385--- /dev/null+++ b/core/internal/controller/askai/askai_v1_project.go@@ -0,0 +1,241 @@+package askai++import (+ v1 "billionmail-core/api/askai/v1"+ "billionmail-core/internal/service/askai"+ "context"+)++func (c *ControllerV1) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {+ res = &v1.CreateRes{}+ err = askai.Create(req.Domain, req.Urls)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Project created successfully")+ }+ return res, nil+}++func (c *ControllerV1) GetBaseInfo(ctx context.Context, req *v1.GetBaseInfoReq) (res *v1.GetBaseInfoRes, err error) {+ res = &v1.GetBaseInfoRes{}+ res.Data, err = askai.GetBaseInfo(req.Domain)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Base information retrieved successfully")+ }+ return res, nil+}++func (c *ControllerV1) ModifyBaseInfo(ctx context.Context, req *v1.ModifyBaseInfoReq) (res *v1.ModifyBaseInfoRes, err error) {+ res = &v1.ModifyBaseInfoRes{}+ err = askai.ModifyBaseInfo(req.Domain, req.ProjectName, req.Description, req.Industry, req.PrimaryLogo, req.SecondaryLogo, req.Favicon)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Base information modified successfully")+ }+ return res, nil+}++func (c *ControllerV1) ModifyKnowledgeBaseFile(ctx context.Context, req *v1.ModifyKnowledgeBaseFileReq) (res *v1.ModifyKnowledgeBaseFileRes, err error) {+ res = &v1.ModifyKnowledgeBaseFileRes{}+ err = askai.ModifyKnowledgeBaseFile(req.Domain, req.Kid, req.Title, req.Content)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Knowledge base file modified successfully")+ }+ return res, nil+}++func (c *ControllerV1) CreateKnowledgeBaseFile(ctx context.Context, req *v1.CreateKnowledgeBaseFileReq) (res *v1.CreateKnowledgeBaseFileRes, err error) {+ res = &v1.CreateKnowledgeBaseFileRes{}+ err = askai.CreateKnowledgeBaseFile(req.Domain, req.Title, req.Content)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Knowledge base file created successfully")+ }+ return res, nil+}++func (c *ControllerV1) RemoveKnowledgeBaseFile(ctx context.Context, req *v1.RemoveKnowledgeBaseFileReq) (res *v1.RemoveKnowledgeBaseFileRes, err error) {+ res = &v1.RemoveKnowledgeBaseFileRes{}+ err = askai.RemoveKnowledgeBaseFile(req.Domain, req.Kid)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Knowledge base file removed successfully")+ }+ return res, nil+}++func (c *ControllerV1) GetCompanyProfile(ctx context.Context, req *v1.GetCompanyProfileReq) (res *v1.GetCompanyProfileRes, err error) {+ res = &v1.GetCompanyProfileRes{}+ res.Data, err = askai.GetCompanyProfile(req.Domain)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Company profile retrieved successfully")+ }+ return res, nil+}++func (c *ControllerV1) ModifyCompanyProfile(ctx context.Context, req *v1.ModifyCompanyProfileReq) (res *v1.ModifyCompanyProfileRes, err error) {+ res = &v1.ModifyCompanyProfileRes{}+ err = askai.ModifyCompanyProfile(req.Domain, req.LegalCompanyName, req.Website, req.CompanyProfile, req.Email, req.Phone, req.SupportUrl)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Company profile modified successfully")+ }+ return res, nil+}++func (c *ControllerV1) GetStyleConfig(ctx context.Context, req *v1.GetStyleConfigReq) (res *v1.GetStyleConfigRes, err error) {+ res = &v1.GetStyleConfigRes{}+ res.Data, err = askai.GetStyleConfig(req.Domain)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Style configuration retrieved successfully")+ }+ return res, nil+}++func (c *ControllerV1) ModifyStyleConfig(ctx context.Context, req *v1.ModifyStyleConfigReq) (res *v1.ModifyStyleConfigRes, err error) {+ res = &v1.ModifyStyleConfigRes{}+ err = askai.ModifyStyleConfig(req.Domain, req.AccentColor, req.TextColor, req.PageBackground, req.ContainerBackground, req.LinkSocialColor, req.LinkFooterColor, req.HeadingFont, req.BodyFont)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Style configuration modified successfully")+ }+ return res, nil+}++func (c *ControllerV1) GetSitemap(ctx context.Context, req *v1.GetSitemapReq) (res *v1.GetSitemapRes, err error) {+ res = &v1.GetSitemapRes{}+ res.Data, err = askai.GetSiteMap(req.Domain)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Sitemap retrieved successfully")+ }+ return res, nil+}++func (c *ControllerV1) RemoveSitemapNode(ctx context.Context, req *v1.RemoveSitemapNodeReq) (res *v1.RemoveSitemapNodeRes, err error) {+ res = &v1.RemoveSitemapNodeRes{}+ err = askai.RemoveSiteMapNode(req.Domain, req.UriPath)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Sitemap node removed successfully")+ }+ return res, nil+}++func (c *ControllerV1) AddSitemapNode(ctx context.Context, req *v1.AddSitemapNodeReq) (res *v1.AddSitemapNodeRes, err error) {+ res = &v1.AddSitemapNodeRes{}+ err = askai.AddSiteMapNode(req.Domain, req.Title, req.UriPath)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Sitemap node added successfully")+ }+ return res, nil+}++func (c *ControllerV1) GetFooter(ctx context.Context, req *v1.GetFooterReq) (res *v1.GetFooterRes, err error) {+ res = &v1.GetFooterRes{}+ res.Data, err = askai.GetFooter(req.Domain)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Footer retrieved successfully")+ }+ return res, nil+}++func (c *ControllerV1) ModifyFooter(ctx context.Context, req *v1.ModifyFooterReq) (res *v1.ModifyFooterRes, err error) {+ res = &v1.ModifyFooterRes{}+ err = askai.ModifyFooter(req.Domain, req.CopyrightText, req.Disclaimer, "")+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Footer modified successfully")+ }+ return res, nil+}++func (c *ControllerV1) GetPrompt(ctx context.Context, req *v1.GetPromptReq) (res *v1.GetPromptRes, err error) {+ res = &v1.GetPromptRes{}+ res.Data, err = askai.GetPrompt(req.Domain)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Prompt retrieved successfully")+ }+ return res, nil+}++func (c *ControllerV1) ModifyPrompt(ctx context.Context, req *v1.ModifyPromptReq) (res *v1.ModifyPromptRes, err error) {+ res = &v1.ModifyPromptRes{}+ err = askai.ModifyPrompt(req.Domain, req.Prompt)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Prompt modified successfully")+ }+ return res, nil+}++func (c *ControllerV1) UploadImage(ctx context.Context, req *v1.UploadImageReq) (res *v1.UploadImageRes, err error) {+ res = &v1.UploadImageRes{}+ imageUrl, err := askai.UploadImage(req.Domain, req.Image, req.Filename, req.AltText, req.ImageTag)+ if err != nil {+ res.SetError(err)+ } else {+ res.Data = map[string]string{+ "url": imageUrl,+ }+ res.SetSuccess("Image uploaded successfully")+ }+ return res, nil+}++func (c *ControllerV1) RemoveImage(ctx context.Context, req *v1.RemoveImageReq) (res *v1.RemoveImageRes, err error) {+ res = &v1.RemoveImageRes{}+ err = askai.RemoveImage(req.Domain, req.ImageId)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Image removed successfully")+ }+ return res, nil+}++func (c *ControllerV1) ModifyImage(ctx context.Context, req *v1.ModifyImageReq) (res *v1.ModifyImageRes, err error) {+ res = &v1.ModifyImageRes{}+ err = askai.ModifyImage(req.Domain, req.ImageId, req.AltText, req.ImageTag)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Image modified successfully")+ }+ return res, nil+}++func (c *ControllerV1) GetImages(ctx context.Context, req *v1.GetImagesReq) (res *v1.GetImagesRes, err error) {+ res = &v1.GetImagesRes{}+ res.Data, err = askai.GetImages(req.Domain)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess("Images retrieved successfully")+ }+ return res, nil+}diff --git a/core/internal/controller/askai/askai_v1_supplier.go b/core/internal/controller/askai/askai_v1_supplier.gonew file mode 100644index 00000000..3bffe348--- /dev/null+++ b/core/internal/controller/askai/askai_v1_supplier.go@@ -0,0 +1,176 @@+package askai++import (+ v1 "billionmail-core/api/askai/v1"+ "billionmail-core/internal/service/askai"+ "billionmail-core/internal/service/public"+ "billionmail-core/utility/types/api_v1"+ "context"+ "errors"+)++func (c *ControllerV1) List(ctx context.Context, req *v1.ListReq) (res *v1.ListRes, err error) {+ res = &v1.ListRes{}+ res.Data = askai.List()+ if res.Data == nil {+ res.SetError(errors.New(public.LangCtx(ctx, "Not suppliers found")))+ return res, nil+ }+ res.SetSuccess(public.LangCtx(ctx, "List of suppliers retrieved successfully"))+ return res, nil+}++func (c *ControllerV1) Models(ctx context.Context, req *v1.ModelsReq) (res *v1.ModelsRes, err error) {+ res = &v1.ModelsRes{}+ res.Data = askai.Models(req.SupplierName)+ res.SetSuccess(public.LangCtx(ctx, "List of models retrieved successfully"))+ return res, nil+}++func (c *ControllerV1) AddModel(ctx context.Context, req *v1.AddModelReq) (res *v1.AddModelRes, err error) {+ res = &v1.AddModelRes{}+ res.Data = askai.AddModel(req.SupplierName, req.Title, req.ModelId, req.MaxTokens, req.Capability)+ res.SetSuccess(public.LangCtx(ctx, "Model added successfully"))+ return res, nil+}++func (c *ControllerV1) RemoveModel(ctx context.Context, req *v1.RemoveModelReq) (res *v1.RemoveModelRes, err error) {+ res = &v1.RemoveModelRes{}+ res.Data = askai.RemoveModel(req.SupplierName, req.ModelId)+ if res.Data == nil {+ res.SetError(errors.New(public.LangCtx(ctx, "Model not found")))+ return res, nil+ }+ res.SetSuccess(public.LangCtx(ctx, "Model removed successfully"))+ return res, nil+}++func (c *ControllerV1) SetSupplierConfig(ctx context.Context, req *v1.SetSupplierConfigReq) (res *api_v1.StandardRes, err error) {+ res = &api_v1.StandardRes{}+ result := askai.SetSupplierConfig(req.SupplierName, req.BaseUrl, req.ApiKey)+ if result == nil {+ res.Data = result+ res.SetSuccess(public.LangCtx(ctx, "Supplier configuration updated successfully"))+ } else {+ res.SetError(result)+ }++ return res, nil+}++func (c *ControllerV1) Testing(ctx context.Context, req *v1.TestingReq) (res *v1.TestingRes, err error) {+ res = &v1.TestingRes{}+ err = askai.Testing(req.SupplierName, req.BaseUrl, req.ApiKey)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess(public.LangCtx(ctx, "Supplier connection successful"))+ }++ // fmt.Println("Testing supplier connection:%s", req.SupplierName)+ return res, nil+}++func (c *ControllerV1) GetSupplierConfig(ctx context.Context, req *v1.GetSupplierConfigReq) (res *v1.GetSupplierConfigRes, err error) {+ res = &v1.GetSupplierConfigRes{}+ config, err := askai.GetSupplierConfig(req.SupplierName)+ if err == nil {+ res.Data = config+ res.SetSuccess(public.LangCtx(ctx, "Supplier configuration retrieved successfully"))+ } else {+ res.SetError(err)+ }+ return res, nil+}++func (c *ControllerV1) SetSupplierStatus(ctx context.Context, req *v1.SetSupplierStatusReq) (res *api_v1.StandardRes, err error) {+ res = &api_v1.StandardRes{}+ err = askai.SetSupplierStatus(req.SupplierName, req.Status)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess(public.LangCtx(ctx, "Supplier status updated successfully"))+ }++ return res, nil+}++func (c *ControllerV1) SetModelStatus(ctx context.Context, req *v1.SetModelStatusReq) (res *api_v1.StandardRes, err error) {+ res = &api_v1.StandardRes{}+ err = askai.SetModelStatus(req.SupplierName, req.ModelId, req.Status)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess(public.LangCtx(ctx, "Model status updated successfully"))+ }++ return res, nil+}++func (c *ControllerV1) AddSupplier(ctx context.Context, req *v1.AddSupplierReq) (res *v1.AddSupplierRes, err error) {+ res = &v1.AddSupplierRes{}+ err = askai.AddSupplier(req.SupplierTitle, req.SupplierName, req.BaseUrl, req.ApiKey)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess(public.LangCtx(ctx, "Supplier added successfully"))+ }+ return res, nil+}++func (c *ControllerV1) RemoveSupplier(ctx context.Context, req *v1.RemoveSupplierReq) (res *v1.RemoveSupplierRes, err error) {+ res = &v1.RemoveSupplierRes{}+ err = askai.RemoveSupplier(req.SupplierName)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess(public.LangCtx(ctx, "Supplier removed successfully"))+ }+ return res, nil+}+func (c *ControllerV1) SetModelTitle(ctx context.Context, req *v1.SetModelTitleReq) (res *v1.SetModelTitleRes, err error) {+ res = &v1.SetModelTitleRes{}+ err = askai.SetModelTitle(req.SupplierName, req.ModelId, req.Title)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess(public.LangCtx(ctx, "Model title updated successfully"))+ }+ return res, nil+}++func (c *ControllerV1) SetModelCapability(ctx context.Context, req *v1.SetModelCapabilityReq) (res *v1.SetModelCapabilityRes, err error) {+ res = &v1.SetModelCapabilityRes{}+ err = askai.SetModelCapability(req.SupplierName, req.ModelId, req.Capability)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess(public.LangCtx(ctx, "Model capability updated successfully"))+ }+ return res, nil+}++func (c *ControllerV1) ModifyModel(ctx context.Context, req *v1.ModifyModelReq) (res *v1.ModifyModelRes, err error) {+ res = &v1.ModifyModelRes{}+ err = askai.ModifyModel(req.SupplierName, req.ModelId, req.MaxTokens, req.Capability, req.Title)+ if err != nil {+ res.SetError(err)+ } else {+ res.SetSuccess(public.LangCtx(ctx, "Model modified successfully"))+ }+ return res, nil+}++func (c *ControllerV1) Status(ctx context.Context, req *v1.StatusReq) (res *v1.StatusRes, err error) {+ res = &v1.StatusRes{}+ status := askai.Status()+ if err != nil {+ res.SetError(err)+ } else {+ res.Data = map[string]bool{+ "is_configured": status,+ }+ res.SetSuccess(public.LangCtx(ctx, "Supplier status retrieved successfully"))+ }+ return res, nil+}diff --git a/core/internal/service/askai/chat.go b/core/internal/service/askai/chat.gonew file mode 100644index 00000000..329ba3ad--- /dev/null+++ b/core/internal/service/askai/chat.go@@ -0,0 +1,384 @@+package askai++import (+ "billionmail-core/internal/service/public"+ "context"+ "encoding/json"+ "errors"+ "os"++ "github.com/gogf/gf/v2/frame/g"+)++const (+ CHAT_CONFIG_PATH = "../conf/chat"+)++type TempChat struct {+ ChatId string `json:"chatId"` // Unique identifier for the chat+ Domain string `json:"domain"` // Domain associated with the chat+ AddType int `json:"add_type"` // Type of addition (e.g., 0 for new chat, 1 for existing chat)+ TempName string `json:"temp_name"` // Temporary name for the chat or knowledge base file+ HtmlContent string `json:"html_content"` // HTML content of the chat or knowledge base file+ DragData string `json:"drag_data"` // Data for drag-and-drop functionality+ CreateTime int64 `json:"create_time"` // Creation time of the chat+ UpdateTime int64 `json:"update_time"` // Last update time of the chat+}++type ChatUsage struct {+ PromptTokens int `json:"prompt_tokens"` // Number of tokens in the prompt+ CompletionTokens int `json:"completion_tokens"` // Number of tokens in the completion+ TotalTokens int `json:"total_tokens"` // Total number of tokens used+}++type Message struct {+ MessageId string `json:"messageId"` // Unique identifier for the message+ ChatId string `json:"chatId"` // Unique identifier for the chat+ Ppid string `json:"ppid"` // Parent message ID (if applicable)+ Content string `json:"content"` // Content of the message+ HtmlContent string `json:"html_content"` // HTML content of the message+ Role string `json:"role"` // Role of the message sender (e.g., "user", "assistant","system","tool")+ CreateTime int64 `json:"create_time"` // Creation time of the message+ EndTime int64 `json:"end_time"` // End time of the message (if applicable)+ Reasoning string `json:"reasoning"` // Reasoning or explanation for the message+ SupplierName string `json:"supplier_name"` // Name of the AI model supplier+ ModelId string `json:"model_id"` // Identifier for the AI model used in the message+ FinishReason string `json:"finish_reason"` // Reason for finishing the message (e.g., "stop", "length")+ Usage ChatUsage `json:"usage"` // Usage statistics for the message+ TimeConsuming int64 `json:"time_consuming"` // Time taken to process the message in milliseconds+}++type File struct {+ Fid string `json:"fid"` // Unique identifier for the file+ Content string `json:"content"` // Content of the file+ Title string `json:"title"` // Title of the file+ Size int64 `json:"size"` // Size of the file in bytes+ UpdateTime int64 `json:"update_time"` // Last update time of the file+}++type ChatInfo struct {+ ChatId string `json:"chatId"` // Unique identifier for the chat+ Prompt string `json:"prompt"` // Prompt or question for the chat+ Title string `json:"title"` // Title of the chat+ SupplierName string `json:"supplierName"` // Name of the AI model supplier+ ModelId string `json:"modelId"` // Identifier for the AI model used in the chat+ Messages []Message `json:"messages"` // List of messages in the chat+ Files []File `json:"files"` // List of files associated with the chat+ CreateTime int64 `json:"create_time"` // Creation time of the chat+ UpdateTime int64 `json:"update_time"` // Last update time of the chat+}++var ChatStatus = map[string]bool{}++func SaveTempChat(chatId string, chatInfo *TempChat) error {+ // Implementation for saving a temporary chat+ // This function should handle the logic for saving the temporary chat information+ tempChatPath := CHAT_CONFIG_PATH + "/" + chatId+ if !public.FileExists(tempChatPath) {+ os.MkdirAll(tempChatPath, os.ModePerm)+ }+ jsonData, err := json.Marshal(chatInfo)+ if err != nil {+ return err+ }+ tempChatFile := tempChatPath + "/config.json"+ os.WriteFile(tempChatFile, jsonData, 0644)+ return nil+}++func GetTempChat(chatId string) (*TempChat, error) {+ // Implementation for retrieving a temporary chat+ // This function should handle the logic for loading the temporary chat information+ tempChatPath := CHAT_CONFIG_PATH + "/" + chatId + "/config.json"+ if !public.FileExists(tempChatPath) {+ return nil, os.ErrNotExist+ }+ data, err := os.ReadFile(tempChatPath)+ if err != nil {+ return nil, err+ }+ var tempChat TempChat+ err = json.Unmarshal(data, &tempChat)+ if err != nil {+ return nil, err+ }+ return &tempChat, nil+}++func SaveChat(chatId string, chatInfo *ChatInfo) error {+ // Implementation for saving chat information+ // This function should handle the logic for saving the chat information+ chatPath := CHAT_CONFIG_PATH + "/" + chatId+ if !public.FileExists(chatPath) {+ os.MkdirAll(chatPath, os.ModePerm)+ }+ jsonData, err := json.Marshal(chatInfo)+ if err != nil {+ return err+ }+ chatFile := chatPath + "/info.json"+ return os.WriteFile(chatFile, jsonData, 0644)+}++func GetChat(chatId string) (*ChatInfo, error) {+ // Implementation for retrieving chat information+ // This function should handle the logic for loading the chat information+ chatPath := CHAT_CONFIG_PATH + "/" + chatId + "/info.json"+ if !public.FileExists(chatPath) {+ return nil, os.ErrNotExist+ }+ data, err := os.ReadFile(chatPath)+ if err != nil {+ return nil, err+ }+ var chatInfo ChatInfo+ err = json.Unmarshal(data, &chatInfo)+ if err != nil {+ return nil, err+ }+ return &chatInfo, nil+}++func GetMessages(chatId string) []Message {+ messageFile := CHAT_CONFIG_PATH + "/" + chatId + "/message.json"+ if !public.FileExists(messageFile) {+ return []Message{} // Return an empty slice if the file does not exist+ }+ data, err := os.ReadFile(messageFile)+ if err != nil {+ return []Message{} // Return an empty slice if there's an error reading the file+ }+ var messages []Message+ err = json.Unmarshal(data, &messages)+ if err != nil {+ return []Message{} // Return an empty slice if there's an error unmarshalling the data+ }+ return messages+}++func CreateChat(Domain string, AddType int, TempName string) (string, error) {+ // Implementation for creating a chat+ // This function should handle the logic for creating a chat based on the provided parameters+ chatId := GetUUID()+ pData := TempChat{+ ChatId: chatId,+ Domain: Domain,+ AddType: AddType,+ TempName: TempName,+ HtmlContent: "",+ DragData: "",+ CreateTime: public.GetNowTime(),+ UpdateTime: public.GetNowTime(),+ }++ err := SaveTempChat(chatId, &pData)+ if err != nil {+ return "", err+ }++ // Initialize chat information with default values+ // This function should handle the logic for initializing a chat with default values+ chatInfo := ChatInfo{+ ChatId: chatId,+ Prompt: "",+ Title: TempName,+ SupplierName: "",+ ModelId: "",+ Messages: []Message{},+ Files: []File{},+ CreateTime: public.GetNowTime(),+ UpdateTime: public.GetNowTime(),+ }+ err = SaveChat(chatId, &chatInfo)+ if err != nil {+ return "", err+ }++ return chatId, nil+}++func GetChatList() ([]TempChat, error) {+ var chatList []TempChat+ // Implementation for retrieving the chat list+ // This function should return the list of chats and any error encountered+ if !public.FileExists(CHAT_CONFIG_PATH) {+ return chatList, nil+ }+ files, err := os.ReadDir(CHAT_CONFIG_PATH)+ if err != nil {+ return chatList, err+ }++ for _, file := range files {+ if !file.IsDir() {+ continue+ }++ chatId := file.Name()+ tempChat, err := GetTempChat(chatId)+ if err != nil {+ continue // Skip if there's an error retrieving the temporary chat+ }++ chatList = append(chatList, *tempChat)+ }++ return chatList, nil+}++// GetChatInfo retrieves the chat information for a given chat ID+// This function should handle the logic for loading the chat information and return the ChatInfo struct and any error encountered+func GetChatInfo(chatId string) (*ChatInfo, error) {+ chatInfo, err := GetChat(chatId)+ if err != nil {+ return nil, err+ }+ chatInfo.Messages = GetMessages(chatId)+ return chatInfo, nil+}++func Chat(ctx context.Context, chatId string, supplierName string, modelId string, content string, isText bool) error {+ supplierInfo, err := GetSupplierConfig(supplierName)+ if err != nil {+ return errors.New("Supplier not found")+ }+ modelInfo := GetModelInfo(supplierName, modelId)+ if modelInfo == nil {+ return errors.New("Model not found")+ }++ // Check if the chat is already active+ chatInfo, err := GetChat(chatId)+ if err != nil {+ return errors.New("Chat not found")+ }+ // set the chat information+ chatInfo.SupplierName = supplierName+ chatInfo.ModelId = modelId+ err = SaveChat(chatId, chatInfo)+ if err != nil {+ return errors.New("Failed to save chat")+ }++ ChatStatus[chatId] = true // Set chat status to active+ defer func() {+ delete(ChatStatus, chatId) // Ensure chat status is removed after processing+ }()++ aiObj := NewOpenAI(ctx, supplierInfo.ApiKey, supplierInfo.BaseUrl, modelId, chatId, supplierName, modelInfo.MaxTokens)+ aiObj.GetClient()+ return aiObj.Chat(content, isText)+}++// RemoveChat removes a chat by its ID+// This function should handle the logic for removing a chat based on the provided chat ID+func RemoveChat(chatId string) error {+ chatPath := CHAT_CONFIG_PATH + "/" + chatId+ if !public.FileExists(chatPath) {+ return os.ErrNotExist+ }+ err := os.RemoveAll(chatPath)+ if err != nil {+ return err+ }+ return nil+}++func Stop(chatId string) error {+ // Implementation for stopping a chat+ // This function should handle the logic for stopping a chat based on the provided parameters+ if _, exists := ChatStatus[chatId]; !exists {+ return errors.New("Chat not found or already stopped")+ }+ ChatStatus[chatId] = false // Set chat status to inactive+ return nil+}++// GetHtml retrieves the HTML content of a chat by its ID+// This function should handle the logic for loading the HTML content of a chat based on the provided chat ID+func GetHtml(chatId string) (string, error) {+ var htmlContent string+ filename := CHAT_CONFIG_PATH + "/" + chatId + "/code.html"+ if !public.FileExists(filename) {+ return "", nil+ }+ data, err := os.ReadFile(filename)+ if err != nil {+ return "", err+ }+ htmlContent = string(data)+ return htmlContent, nil+}++// ModifyHtml modifies the HTML content of a chat by its ID+// This function should handle the logic for modifying the HTML content of a chat based on the provided chat ID and content+func ModifyHtml(chatId string, content string) error {+ filename := CHAT_CONFIG_PATH + "/" + chatId + "/code.html"+ if !public.FileExists(filename) {+ return errors.New("HTML file not found")+ }+ g.DB().Model("email_templates").Where("chat_id", chatId).Update(g.Map{+ "content": content, // Update the HTML content in the database+ })++ return os.WriteFile(filename, []byte(content), os.ModePerm)+}++func CopyChat(chatId string, domain string) (string, string, error) {+ // Implementation for copying a chat+ // This function should handle the logic for copying a chat based on the provided chat ID and domain++ chatInfo, err := GetChat(chatId)+ if err != nil {+ return "", "", err+ }++ newChatId := GetUUID()+ newTempChat := TempChat{+ ChatId: newChatId,+ Domain: domain,+ AddType: 99,+ CreateTime: public.GetNowTime(),+ UpdateTime: public.GetNowTime(),+ }+ err = SaveTempChat(newChatId, &newTempChat)++ if err != nil {+ return "", "", err+ }++ newChatInfo := ChatInfo{+ ChatId: newChatId,+ Prompt: chatInfo.Prompt,+ Title: chatInfo.Title,+ SupplierName: chatInfo.SupplierName,+ ModelId: chatInfo.ModelId,+ Messages: []Message{},+ Files: []File{},+ CreateTime: public.GetNowTime(),+ UpdateTime: public.GetNowTime(),+ }++ err = SaveChat(newChatId, &newChatInfo)+ if err != nil {+ return "", "", err+ }++ oldChatId := chatInfo.ChatId+ oldCodeFile := CHAT_CONFIG_PATH + "/" + oldChatId + "/code.html"+ newCodeFile := CHAT_CONFIG_PATH + "/" + newChatId + "/code.html"+ oldCode := ""+ if public.FileExists(oldCodeFile) {+ oldCodeBytes, err := os.ReadFile(oldCodeFile)+ oldCode = string(oldCodeBytes)+ if err != nil {+ return "", oldCode, err+ }+ err = os.WriteFile(newCodeFile, oldCodeBytes, os.ModePerm)+ if err != nil {+ return "", oldCode, err+ }+ }++ return newChatId, oldCode, nil+}diff --git a/core/internal/service/askai/openai.go b/core/internal/service/askai/openai.gonew file mode 100644index 00000000..b21a541b--- /dev/null+++ b/core/internal/service/askai/openai.go@@ -0,0 +1,912 @@+package askai++import (+ "billionmail-core/internal/service/public"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "strconv"+ "strings"++ "github.com/gogf/gf/v2/frame/g"+ "github.com/gogf/gf/v2/net/ghttp"+ tiktoken "github.com/pkoukk/tiktoken-go"+ openai "github.com/sashabaranov/go-openai"+)++const (+ TOKENS_CACHE_DIR = "../conf/tokens_cache" // Directory for token cache files+)++type ResultJson struct {+ ThinkStart bool `json:"think_start"` // Indicates if the chat is in thinking state+ ThinkEnd bool `json:"think_end"` // Indicates if the chat has ended thinking state+ IsThink bool `json:"is_think"` // Indicates if the chat is in thinking state+ Content string `json:"content"` // Content of the chat message+ Reasoning string `json:"reasoning"` // Reasoning or explanation for the chat message+ IsHtmlContent bool `json:"is_html"` // HTML content of the chat message+ Role string `json:"role"` // Role of the message sender (e.g., "user", "assistant")+ IsEnd bool `json:"is_end"` // Indicates if this is the end of the chat message+ UpdateTime int64 `json:"update_time"` // Last update time of the chat message+}++type OpenAI struct {+ ApiKey string // API key for OpenAI+ BaseUrl string // Base URL for OpenAI API+ ModelId string // Model ID for OpenAI API+ ChatId string // Chat ID for OpenAI API+ SupplierName string // Supplier name for OpenAI+ MaxTokens int // Maximum tokens for OpenAI API+ Client *openai.Client // OpenAI client instance+ Ctx context.Context+ Reasoning string // Reasoning for the chat message+ ThinkStart bool // Indicates if the chat is in thinking state+ ThinkEnd bool // Indicates if the chat has ended thinking state+ IsThinking bool // Indicates if the chat is in thinking state+ IsThinkContent bool // Indicates if the chat content is being thought about+ HtmlContent string // HTML content of the chat message+ IsHtml bool // Indicates if the content is HTML+ LastContent string // Last content sent in the chat+ MessageId string // Unique identifier for the message+ CreateTime int64 // Creation time of the chat+ RequestTime int64 // Time when the request was made+ Usage ChatUsage // Usage statistics for the chat+ IsRecordHtml bool // Indicates if HTML content should be recorded+ Content string // Content of the chat message+ AddedSystemPrompt string // Initial system prompt for the chat+ AddedSystemPromptTokens int // Tokens for the initial system prompt+ TempInfo *TempChat // Chat information for the OpenAI chat+ UserContent string // User content for the chat+ IsModify bool // Indicates if the chat is being modified++}++func NewOpenAI(ctx context.Context, apiKey, baseUrl, modelId, chatId, supplierName string, maxTokens int) *OpenAI {+ tempInfo, err := GetTempChat(chatId)+ if err != nil {+ fmt.Println("Error getting template chat:", err)+ return nil // Return nil if there is an error getting template chat info+ }+ return &OpenAI{+ ApiKey: apiKey,+ BaseUrl: baseUrl,+ ModelId: modelId,+ ChatId: chatId,+ SupplierName: supplierName,+ MaxTokens: maxTokens,+ Client: nil, // Client will be initialized later+ Ctx: ctx,+ Reasoning: "", // Default reasoning is empty+ IsThinking: false, // Default thinking state is false+ HtmlContent: "", // Default HTML content is empty+ IsHtml: false, // Default content type is not HTML+ MessageId: "",+ CreateTime: public.GetNowTime(), // Set creation time to the current time+ RequestTime: 0, // Request time will be set when the chat is initiated+ Usage: ChatUsage{+ PromptTokens: 0, // Default prompt tokens is 0+ CompletionTokens: 0, // Default completion tokens is 0+ TotalTokens: 0, // Default total tokens is 0+ },+ IsRecordHtml: false, // Default is not to record HTML content+ LastContent: "", // Default last content is empty+ Content: "", // Default content is empty+ AddedSystemPrompt: "", // Set the initial system prompt+ AddedSystemPromptTokens: 0, // Set initial system prompt tokens+ TempInfo: tempInfo, // Get chat information based on the chat ID+ UserContent: "", // Default user content is empty+ IsModify: false, // Default is not to modify the chat+ }+}++type ModelConfig struct {+ Encoding string+ MaxTokens int+ Description string+}++var SYSTEM_PROMPT_TOKENS = 0++// GetClient returns the OpenAI client+func (o *OpenAI) GetClient() *openai.Client {+ if o.SupplierName == "openai" {+ o.Client = openai.NewClient(o.ApiKey)+ } else {+ config := openai.DefaultConfig(o.ApiKey)+ config.BaseURL = o.BaseUrl++ o.Client = openai.NewClientWithConfig(config)+ }+ return o.Client+}++// GetCacheTokens retrieves the cached tokens for a specific key+// It checks if the cache directory exists, creates it if not, and reads the tokens from a file named after the cache key.+func (o *OpenAI) GetCacheTokens(cacheKey string) int {+ // cache filename+ if !public.FileExists(TOKENS_CACHE_DIR) {+ os.MkdirAll(TOKENS_CACHE_DIR, 0755) // Create the cache directory if it does not exist+ }+ cacheFile := TOKENS_CACHE_DIR + "/" + cacheKey+ if !public.FileExists(cacheFile) {+ return 0+ }++ // read cache file+ data, err := os.ReadFile(cacheFile)+ if err != nil {+ fmt.Println("Error reading cache file:", err)+ return 0 // Return 0 if there is an error reading the cache file+ }++ // string to int+ tokens, err := strconv.Atoi(string(data)) // Convert the string data to an integer+ if err != nil {+ return 0 // Return 0 if there is an error converting the string to an integer+ }+ return tokens+}++// SetCacheTokens sets the cached tokens for a specific key+// It creates a cache directory if it does not exist and writes the tokens to a file named after the cache key.+func (o *OpenAI) SetCacheTokens(cacheKey string, tokens int) error {+ // cache filename+ if !public.FileExists(TOKENS_CACHE_DIR) {+ os.MkdirAll(TOKENS_CACHE_DIR, 0755) // Create the cache directory if it does not exist+ }+ cacheFile := TOKENS_CACHE_DIR + "/" + cacheKey++ // write cache file+ err := os.WriteFile(cacheFile, []byte(strconv.Itoa(tokens)), 0644)+ if err != nil {+ fmt.Println("Error writing cache file:", err)+ return err+ }+ return nil+}++// 计算tokens+func (o *OpenAI) CalculateTokens(content string, isCache bool) (int, error) {+ // Implementation for calculating tokens based on the content+ // This function should handle the logic for calculating tokens and return the count or any error encountered++ // 尝试从缓存获取tokens+ cacheKey := public.Md5(content)+ if isCache {+ cachedTokens := o.GetCacheTokens(cacheKey)+ if cachedTokens > 0 {+ return cachedTokens, nil // Return cached tokens if available+ }+ }++ encoding := "cl100k_base"+ tke, err := tiktoken.GetEncoding(encoding)+ if err != nil {+ return 0, err // Return error if encoding is not found+ }+ tokens := tke.Encode(content, nil, nil)+ tokenCount := len(tokens)++ // 将计算的tokens存入缓存+ if isCache {+ o.SetCacheTokens(cacheKey, tokenCount)+ }++ return tokenCount, nil // Placeholder implementation, replace with actual token calculation logic+}++// CalculatePromptTokens calculates the number of prompt tokens based on the content length+// It also adds the system prompt tokens to the total prompt tokens+func (o *OpenAI) CalculatePromptTokens(content string) {+ o.Usage.PromptTokens, _ = o.CalculateTokens(content, false) // Update prompt tokens based on the content length+ if SYSTEM_PROMPT_TOKENS == 0 {+ SYSTEM_PROMPT_TOKENS, _ = o.CalculateTokens(INITIAL_SYSTEM_PROMPT, true)+ }+ o.Usage.PromptTokens += SYSTEM_PROMPT_TOKENS + o.AddedSystemPromptTokens // Add system prompt tokens to the total prompt tokens+}++func (o *OpenAI) WriteMessage(content string, finishReason string) {++ userMessage := Message{+ MessageId: o.MessageId,+ Ppid: "", // Parent message ID is empty for the initial message+ ChatId: o.ChatId,+ Role: openai.ChatMessageRoleUser,+ Content: content,+ HtmlContent: "",+ CreateTime: o.CreateTime, // Use the creation time set in the OpenAI struct+ EndTime: public.GetNowTime(), // End time is 0 for the initial message+ Reasoning: "",+ SupplierName: o.SupplierName,+ ModelId: o.ModelId,+ TimeConsuming: 0, // Time consuming is 0 for the initial message+ FinishReason: "",+ Usage: ChatUsage{+ PromptTokens: 0,+ CompletionTokens: 0,+ TotalTokens: 0,+ },+ }+ userMessage.TimeConsuming = userMessage.EndTime - userMessage.CreateTime // Calculate time consuming++ assistantMessage := Message{+ MessageId: GetUUID(),+ Ppid: o.MessageId, // Use the MessageId as the parent message ID+ ChatId: o.ChatId,+ Role: openai.ChatMessageRoleAssistant,+ Content: o.Content,+ HtmlContent: o.HtmlContent,+ CreateTime: o.RequestTime,+ EndTime: public.GetNowTime(), // End time is set to the current time+ Reasoning: o.Reasoning,+ SupplierName: o.SupplierName,+ ModelId: o.ModelId,+ TimeConsuming: 0, // Time consuming is 0 for the initial message+ FinishReason: finishReason,+ Usage: ChatUsage{+ PromptTokens: o.Usage.PromptTokens,+ CompletionTokens: o.Usage.CompletionTokens,+ TotalTokens: o.Usage.PromptTokens + o.Usage.CompletionTokens,+ },+ }+ assistantMessage.TimeConsuming = assistantMessage.EndTime - assistantMessage.CreateTime // Calculate time consuming++ o.AppendMessage(userMessage, assistantMessage) // Append the messages to the chat+}++func (o *OpenAI) GetCompanyProfilePrompt() (string, int) {+ companyProFile, err := GetCompanyProfile(o.TempInfo.Domain) // Get the company profile for the chat+ if err != nil {+ fmt.Println("Error getting company profile:", err)+ return "", 0+ }+ companyProFileJson, err := json.Marshal(companyProFile) // Marshal the company profile to JSON+ if err != nil {+ fmt.Println("Error marshalling company profile:", err)+ return "", 0+ }++ prompt := "Company Profile: " + string(companyProFileJson) + "\n\n" // Return the company profile as a string+ tokens, _ := o.CalculateTokens(prompt, true) // Calculate the tokens for the company profile prompt++ return prompt, tokens+}++func (o *OpenAI) GetProjectConfigPrompt() (string, int) {+ projectConfig, err := ReadProjectConfig(o.TempInfo.Domain) // Get the project configuration for the chat+ if err != nil {+ fmt.Println("Error reading project config:", err)+ return "", 0+ }+ projectConfigJson, err := json.Marshal(projectConfig) // Marshal the project configuration to JSON+ if err != nil {+ fmt.Println("Error marshalling project config:", err)+ return "", 0+ }+ prompt := "Project Config: " + string(projectConfigJson) + "\n\n" // Return the project configuration as a string+ tokens, _ := o.CalculateTokens(prompt, true) // Calculate the tokens for the project configuration prompt+ return prompt, tokens+}++func (o *OpenAI) GetSitemapPrompt() (string, int) {+ sitemap, err := GetSiteMap(o.TempInfo.Domain) // Get the sitemap for the chat+ if err != nil {+ fmt.Println("Error getting sitemap:", err)+ return "", 0+ }++ sitemapJson, err := json.Marshal(sitemap) // Marshal the sitemap to JSON+ if err != nil {+ fmt.Println("Error marshalling sitemap:", err)+ return "", 0+ }+ prompt := "Sitemap: " + string(sitemapJson) + "\n\n" // Return the sitemap as a string+ tokens, _ := o.CalculateTokens(prompt, true) // Calculate the tokens for the sitemap prompt+ return prompt, tokens+}++func (o *OpenAI) GetStylePrompt() (string, int) {+ styleConfig, err := GetStyleConfig(o.TempInfo.Domain) // Get the style configuration for the chat+ if err != nil {+ fmt.Println("Error getting style config:", err)+ return "", 0+ }+ styleConfigJson, err := json.Marshal(styleConfig) // Marshal the style configuration to JSON+ if err != nil {+ fmt.Println("Error marshalling style config:", err)+ return "", 0+ }+ prompt := "Style Config: " + string(styleConfigJson) + "\n\n" // Return the style configuration as a string+ tokens, _ := o.CalculateTokens(prompt, true) // Calculate the tokens for the style configuration prompt+ return prompt, tokens+}++func (o *OpenAI) GetFooterPrompt() (string, int) {+ footer, err := GetFooter(o.TempInfo.Domain) // Get the footer for the chat+ if err != nil {+ fmt.Println("Error getting footer:", err)+ return "", 0+ }+ footerJson, err := json.Marshal(footer) // Marshal the footer to JSON+ if err != nil {+ fmt.Println("Error marshalling footer:", err)+ return "", 0+ }+ prompt := "Footer: " + string(footerJson) + "\n\n" // Return the footer as a string+ tokens, _ := o.CalculateTokens(prompt, true) // Calculate the tokens for the footer prompt+ return prompt, tokens+}++func (o *OpenAI) GetKnowledgeBasePrompt() (string, int) {+ knowledgeBase, err := GetKnowledgeBaseList(o.TempInfo.Domain) // Get the knowledge base for the chat+ if err != nil {+ fmt.Println("Error getting knowledge base:", err)+ return "", 0+ }++ // 取内容长度小于1024的文档+ var filteredKnowledgeBase []string+ for i := len(knowledgeBase) - 1; i >= 0; i-- {+ if len(knowledgeBase[i].Content) < 1024 {+ filteredKnowledgeBase = append(filteredKnowledgeBase, knowledgeBase[i].Content)+ }+ }++ knowledgeBaseJson, err := json.Marshal(filteredKnowledgeBase) // Marshal the knowledge base to JSON+ if err != nil {+ fmt.Println("Error marshalling knowledge base:", err)+ return "", 0+ }+ prompt := "Knowledge Base Doc List: " + string(knowledgeBaseJson) + "\n\n" // Return the knowledge base as a string+ tokens, _ := o.CalculateTokens(prompt, true) // Calculate the tokens for the knowledge base prompt+ return prompt, tokens+}++func (o *OpenAI) GetImagesPrompt() (string, int) {+ images, err := ReadImagesConfig(o.TempInfo.Domain) // Get the images configuration for the chat+ if err != nil {+ fmt.Println("Error reading images list:", err)+ return "", 0+ }+ if err != nil {+ fmt.Println("Error reading images list:", err)+ return "", 0+ }+ imagesJson, err := json.Marshal(images) // Marshal the images configuration to JSON+ if err != nil {+ fmt.Println("Error marshalling images list:", err)+ return "", 0+ }+ prompt := "Images: " + string(imagesJson) + "\n\n" // Return the images configuration as a string+ tokens, _ := o.CalculateTokens(prompt, true) // Calculate the tokens for the images prompt+ return prompt, tokens+}++func (o *OpenAI) GetLastPrompt() (string, int) {+ prompt := "The following are reference materials, all in JSON format, which you can use as needed:\n\n"+ tokens, _ := o.CalculateTokens(prompt, true) // Calculate the tokens for the last prompt+ return prompt, tokens+}++func (o *OpenAI) GetSystemPrompt() string {+ if o.AddedSystemPrompt == "" {++ o.AddedSystemPrompt = ""+ prompt := ""+ tokens := 0+ prompt, tokens = o.GetLastPrompt() // Get the last prompt+ o.AddedSystemPrompt += prompt // Add the last prompt to the system prompt+ o.AddedSystemPromptTokens = tokens // Set the tokens for the last prompt+ // Get the additional system prompts+ prompt, tokens = o.GetCompanyProfilePrompt() // Get the company profile prompt+ o.AddedSystemPrompt += prompt // Add the company profile prompt to the system prompt+ o.AddedSystemPromptTokens += tokens // Add the tokens for the company profile prompt+ prompt, tokens = o.GetProjectConfigPrompt() // Get the project configuration prompt+ o.AddedSystemPrompt += prompt // Add the project configuration prompt to the system prompt+ o.AddedSystemPromptTokens += tokens // Add the tokens for the project configuration prompt+ prompt, tokens = o.GetSitemapPrompt() // Get the sitemap prompt+ o.AddedSystemPrompt += prompt // Add the sitemap prompt to the system prompt+ o.AddedSystemPromptTokens += tokens // Add the tokens for the sitemap prompt+ prompt, tokens = o.GetStylePrompt() // Get the style prompt+ o.AddedSystemPrompt += prompt // Add the style prompt to the system prompt+ o.AddedSystemPromptTokens += tokens // Add the tokens for the style prompt+ prompt, tokens = o.GetFooterPrompt() // Get the footer prompt+ o.AddedSystemPrompt += prompt // Add the footer prompt to the system prompt+ o.AddedSystemPromptTokens += tokens // Add the tokens for the footer prompt+ prompt, tokens = o.GetKnowledgeBasePrompt() // Get the knowledge base prompt+ o.AddedSystemPrompt += prompt // Add the knowledge base prompt to the system prompt+ o.AddedSystemPromptTokens += tokens // Add the tokens for the knowledge base prompt+ prompt, tokens = o.GetImagesPrompt() // Get the images prompt+ o.AddedSystemPrompt += prompt // Add the images prompt to the system prompt+ o.AddedSystemPromptTokens += tokens // Add the tokens for the images prompt++ o.AddedSystemPrompt += fmt.Sprintf("Current time: %s\n\n", public.GetNowDate())+ }+ systemPrompt := INITIAL_SYSTEM_PROMPT+ if o.IsModify {+ systemPrompt = FOLLOW_UP_SYSTEM_PROMPT+ }++ return systemPrompt + "\n\n" + o.AddedSystemPrompt // Return the initial system prompt concatenated with any additional system prompt++}++// GetMessages retrieves the messages for the chat+// It reads the chat history, adds the system prompt, and appends the user content to the messages.+// It also handles the last assistant message and ensures the format complies with OpenAI requirements.+func (o *OpenAI) GetMessages() []openai.ChatCompletionMessage {+ historyMessages := o.ReadMessages() // Read messages from the chat history+ lastContent, _ := GetHtml(o.ChatId)+ o.IsModify = false+ if len(historyMessages) > 0 && lastContent != "" {+ o.IsModify = true // If there are history messages and last content is not empty, set IsModify to true+ }++ messages := []openai.ChatCompletionMessage{+ {Role: openai.ChatMessageRoleSystem, Content: o.GetSystemPrompt()},+ }++ // Process history messages and ensure proper alternating pattern+ for _, message := range historyMessages {+ // Truncate long assistant messages+ content := message.Content+ if message.Role == openai.ChatMessageRoleAssistant && len(content) > 512 {+ content = "..."+ }++ messages = append(messages, openai.ChatCompletionMessage{+ Role: message.Role,+ Content: content,+ })+ }++ // Ensure the conversation ends with a user message for proper OpenAI format+ messagesLen := len(messages)+ if messagesLen > 1 && messages[messagesLen-1].Role == openai.ChatMessageRoleAssistant {+ // If last message is from assistant, update its content with HTML if available+ if lastContent != "" {+ messages[messagesLen-1].Content = lastContent+ }+ }++ // Add the current user content to the messages+ if strings.TrimSpace(o.UserContent) != "" {+ messages = append(messages, openai.ChatCompletionMessage{+ Role: openai.ChatMessageRoleUser,+ Content: o.UserContent,+ })+ }++ return messages+}++func (o *OpenAI) Chat(content string, isText bool) error {+ // Implementation for sending a chat message to OpenAI+ // This function should handle the logic for sending a chat message and return the response or any error encountered++ request := ghttp.RequestFromCtx(o.Ctx)+ if request == nil {+ return errors.New("request context is nil")+ }++ if o.Client == nil {+ o.GetClient()+ }++ o.UserContent = content // Set the user content to the provided content++ req := openai.ChatCompletionRequest{+ Model: o.ModelId,+ MaxCompletionTokens: o.MaxTokens,+ Messages: o.GetMessages(), // Get the messages for the chat+ Temperature: 0.6, // Set temperature for the chat completion+ Stream: true,+ }+ o.MessageId = GetUUID()++ o.RequestTime = public.GetNowTime() // Set request time to the current time+ o.CalculatePromptTokens(content) // Calculate prompt tokens based on the content++ stream, err := o.Client.CreateChatCompletionStream(o.Ctx, req)+ if err != nil {+ return err+ }++ defer stream.Close()++ // set request.Response.Header().Set("Content-Type", "text/event-stream")+ request.Response.Header().Set("Content-Type", "text/event-stream; charset=utf-8") // Set content type for SSE (Server-Sent Events)+ request.Response.Header().Set("Cache-Control", "no-cache")+ request.Response.Header().Set("Connection", "keep-alive")+ request.Response.WriteHeader(200) // OK status+ finishReason := ""+ for {+ if ChatStatus[o.ChatId] == false {+ finishReason = "stop"+ break+ }++ response, err := stream.Recv()+ if errors.Is(err, io.EOF) {+ break+ }+ if err != nil {+ return err+ }++ // Set Usage.PromptTokens, CompletionTokens, and TotalTokens+ o.Usage.CompletionTokens += len(response.Choices[0].Delta.Content)+ o.Usage.TotalTokens += o.Usage.PromptTokens + o.Usage.CompletionTokens+ finishReason = string(response.Choices[0].FinishReason)++ messageBody := response.Choices[0].Delta.Content+ if messageBody == "" {+ if response.Choices[0].Delta.ReasoningContent != "" {+ if !o.IsThinkContent {+ o.ThinkStart = true+ } else {+ o.ThinkStart = false+ }+ o.IsThinking = true+ o.IsThinkContent = true // Set thinking content state to true+ messageBody = response.Choices[0].Delta.ReasoningContent // Use reasoning content+ } else {+ continue // Skip empty messages+ }+ } else {+ if o.IsThinkContent {+ o.ThinkEnd = true // Set thinking end state to true if content is not empty+ o.WriteEvent(request, "\n", isText, false) // Write event to the response+ o.ThinkEnd = false+ o.IsThinkContent = false // Reset thinking content state after processing+ if o.IsThinking {+ o.IsThinking = false // Reset thinking state after processing+ }+ }+ }++ // 获取HTML内容,格式:```html+ // if messageBody++ o.WriteEvent(request, messageBody, isText, false) // Write event to the response+ }+ // Ensure the response is properly closed+ o.WriteHtml() // Write HTML content if the chat has ended+ o.WriteMessage(content, finishReason) // Write the final message to the chat+ o.WriteEvent(request, "", isText, true) // Write final event to indicate completion+ return nil+}++type ReplaceHtml struct {+ SearchContent string // Content to search for in the HTML+ ReplaceContent string // Content to replace the searched content with+}++func (o *OpenAI) ReplaceHtml() {+ // SEARCH_START = "<<<<<<< SEARCH"+ // DIVIDER = "======="+ // REPLACE_END = ">>>>>>> REPLACE"+ // FOLLOW_UP_SYSTEM_PROMPT = `You are an expert email writer crafting or modifying professional emails. The user wants to refine an existing email based on their request. You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT rewrite the entire email unless explicitly requested.++ // Explain the changes briefly *before* the blocks if necessary, but the content changes THEMSELVES MUST be within the blocks.++ // Format Rules:+ // 1. Start with ` + SEARCH_START + `+ // 2. Provide the exact lines from the current email that need to be replaced.+ // 3. Use ` + DIVIDER + ` to separate the search block from the replacement.+ // 4. Provide the new lines that should replace the original lines.+ // 5. End with ` + REPLACE_END + `+ // 6. You can use multiple SEARCH/REPLACE blocks if changes are needed in different parts of the email.+ // 7. To insert content, use an empty SEARCH block (only ` + SEARCH_START + ` and ` + DIVIDER + ` on their lines) if inserting at the very beginning, otherwise provide the line *before* the insertion point in the SEARCH block and include that line plus the new content in the REPLACE block.+ // 8. To delete content, provide the lines to delete in the SEARCH block and leave the REPLACE block empty (only ` + DIVIDER + ` and ` + REPLACE_END + ` on their lines).+ // 9. IMPORTANT: The SEARCH block must *exactly* match the current email content, including punctuation and formatting.++ // Example Modifying Email:+ // ` + "```" + `+ // Updated the greeting to be more personal:+ // ` + SEARCH_START + `+ // Dear Sir/Madam,+ // ` + DIVIDER + `+ // Dear Ms. Johnson,+ // ` + REPLACE_END + `++ // Shortened the introduction for clarity:+ // ` + SEARCH_START + `+ // I hope this email finds you well. I am writing to follow up on our recent conversation regarding the upcoming project. As we discussed, I wanted to provide you with some additional information that I believe will be helpful as we move forward.+ // ` + DIVIDER + `+ // Following up on our call, here's the information you requested:+ // ` + REPLACE_END + `+ // ` + "```" + `++ // Example Deleting Content:+ // ` + "```" + `+ // Removed redundant information:+ // ` + SEARCH_START + `+ // Please let me know if you have any questions. I look forward to hearing from you soon.+ // ` + DIVIDER + `+ // ` + REPLACE_END + `+ // ` + "```"++ if !o.IsModify {+ return // If not modifying, return early+ }++ // If modifying, replace the HTML content with the formatted content+ if o.Content == "" {+ return+ }++ // Here are the changes to make the footer more email-appropriate:++ // 1. Simplified the footer content and structure:+ // <<<<<<< SEARCH+ // <!-- 页脚 -->+ // <tr>+ // <td class="section" style="background-color: #f1f4f8; padding: 30px 50px; color: #666666; font-size: 13px;">+ // <table width="100%">+ // <tr>+ // <td>+ // <p style="margin: 0 0 15px; line-height: 1.8;">+ // <a href="http://www.bt.cn/new/agreement_open.html" style="color: #666666; text-decoration: underline; margin-right: 15px;">开源许可协议</a>+ // <a href="http://www.bt.cn/new/agreement_user.html" style="color: #666666; text-decoration: underline; margin-right: 15px;">用户协议</a>+ // <a href="http://www.bt.cn/new/agreement_privacy.html" style="color: #666666; text-decoration: underline;">隐私声明</a>+ // </p>++ // <p style="margin: 8px 0;">高新技术企业编号 GR201944000059 | 粤B2-20201398</p>+ // <p style="margin: 8px 0;">粤ICP备17030143号 | 粤公网安备 44190002003211号</p>++ // <p style="margin: 20px 0 15px;">Copyright © 2023 宝塔面板 (www.bt.cn) 广东堡塔安全技术有限公司 版权所有</p>++ // <p style="margin: 0 0 15px;">+ // <a href="http://www.bt.cn/report/" style="color: #666666; text-decoration: underline; margin-right: 15px;">违规信息举报入口</a>+ // <a href="http://www.bt.cn/new/about.html" style="color: #666666; text-decoration: underline;">公司简介</a>+ // </p>+ // =======+ // <!-- 邮件页脚 -->+ // <tr>+ // <td class="section" style="background-color: #f1f4f8; padding: 25px 50px; color: #666666; font-size: 12px; text-align: center;">+ // <p style="margin: 0 0 10px;">宝塔面板 - 让运维简单高效</p>+ // <p style="margin: 0 0 15px;">+ // <a href="http://www.bt.cn" style="color: #666666; text-decoration: none; margin: 0 10px;">官网</a> |+ // <a href="http://www.bt.cn/bbs" style="color: #666666; text-decoration: none; margin: 0 10px;">社区</a> |+ // <a href="http://www.bt.cn/new/download.html" style="color: #666666; text-decoration: none; margin: 0 10px;">下载</a>+ // </p>+ // <p style="margin: 0 0 10px; color: #999999;">© 2023 宝塔面板 广东堡塔安全技术有限公司</p>+ // <p style="margin: 0; font-size: 11px; color: #999999;">+ // 本邮件为系统自动发送,请勿直接回复+ // </p>+ // >>>>>>> REPLACE++ // 2. Added a small adjustment to the section above the footer to better transition:+ // <<<<<<< SEARCH+ // <!-- 客服支持 -->+ // <tr>+ // <td class="section" style="padding-top: 10px; padding-bottom: 30px;">+ // =======+ // <!-- 客服支持 -->+ // <tr>+ // <td class="section" style="padding-top: 10px; padding-bottom: 20px;">+ // >>>>>>> REPLACE++ // These changes:+ // 1. Simplified the footer content to be more email-appropriate+ // 2. Centered the content and made it more compact+ // 3. Added common email footer elements like "do not reply" notice+ // 4. Reduced the legal/compliance information to just essentials+ // 5. Made the links more prominent but still subtle+ // 6. Adjusted spacing between sections for better flow+ // fmt.Println(o.Content)+ replaceHtml := []ReplaceHtml{}+ if strings.Contains(o.Content, SEARCH_START) && strings.Contains(o.Content, REPLACE_END) && strings.Contains(o.Content, DIVIDER) {++ // Split the content into parts based on the SEARCH_START and REPLACE_END markers+ parts := strings.Split(o.Content, SEARCH_START)+ for _, part := range parts {+ if strings.Contains(part, REPLACE_END) {+ // Further split each part to get the search and replace content+ subParts := strings.Split(part, REPLACE_END)+ if len(subParts) == 2 && strings.Contains(subParts[0], DIVIDER) {+ searchReplace := strings.Split(subParts[0], DIVIDER)+ if len(searchReplace) == 2 {+ fmt.Println("Search Content:", searchReplace[0])+ fmt.Println("Replace Content:", searchReplace[1])+ replaceHtml = append(replaceHtml, ReplaceHtml{+ SearchContent: searchReplace[0],+ ReplaceContent: searchReplace[1],+ })+ }+ }+ }+ }+ }++ htmlContent, err := GetHtml(o.ChatId) // Get the HTML content for the chat+ if err != nil {+ fmt.Println("Error getting HTML content:", err)+ return // Return if there is an error getting the HTML content+ }++ // Replace the HTML content based on the search and replace rules+ for _, replace := range replaceHtml {+ if replace.SearchContent != "" && replace.ReplaceContent != "" {+ htmlContent = strings.ReplaceAll(htmlContent, replace.SearchContent, replace.ReplaceContent)+ }+ }++ err = ModifyHtml(o.ChatId, htmlContent) // Modify the HTML content for the chat+ if err != nil {+ fmt.Println("Error modifying HTML content:", err)+ }++ return++}++// WriteHtml writes the HTML content to a file if it exists+func (o *OpenAI) WriteHtml() {+ if o.IsModify {+ o.ReplaceHtml() // Replace HTML content if modifying+ return+ }+ if o.HtmlContent != "" {+ filename := CHAT_CONFIG_PATH + "/" + o.ChatId + "/code.html"+ o.HtmlContent = strings.Trim(o.HtmlContent, "`")+ if strings.HasPrefix(o.HtmlContent, "html") {+ o.HtmlContent = o.HtmlContent[4:] // Remove the "html" prefix if present+ }+ o.HtmlContent = strings.TrimSpace(o.HtmlContent) // Trim leading and trailing whitespace+ o.HtmlContent = strings.Trim(o.HtmlContent, "`")+ os.WriteFile(filename, []byte(o.HtmlContent), os.ModePerm)+ g.DB().Model("email_templates").Where("chat_id", o.ChatId).Update(g.Map{+ "content": o.HtmlContent, // Update the HTML content in the database+ })+ }+}++func (o *OpenAI) ReadMessages() []Message {+ messageFile := CHAT_CONFIG_PATH + "/" + o.ChatId + "/message.json"+ var messages []Message+ if !public.FileExists(messageFile) {+ return messages // Return nil if the message file does not exist+ }++ // Read existing messages from the file+ fileContent, err := os.ReadFile(messageFile)+ if err != nil {+ fmt.Println("Failed to read message file: ", err)+ return messages+ }++ err = json.Unmarshal(fileContent, &messages)+ if err != nil {+ fmt.Println("Failed to unmarshal messages: ", err)+ return messages+ }++ return messages+}++// SaveMessages saves the messages to a file+// It creates a directory for the chat if it does not exist and writes the messages to a JSON file+func (o *OpenAI) SaveMessages(messages []Message) error {+ messageFile := CHAT_CONFIG_PATH + "/" + o.ChatId + "/message.json"+ updatedContent, err := json.Marshal(messages)+ if err != nil {+ return err+ }+ return os.WriteFile(messageFile, updatedContent, os.ModePerm)+}++func (o *OpenAI) AppendMessage(message ...Message) {+ messages := o.ReadMessages() // Read existing messages from the file++ // Append the new message to the existing messages+ messages = append(messages, message...)++ // Save the updated messages back to the file+ err := o.SaveMessages(messages)+ if err != nil {+ fmt.Println("Failed to save messages: ", err) // Log error if saving messages fails+ return+ }+}++// SetHtmlContent sets the HTML content and reasoning for the OpenAI chat+func (o *OpenAI) SetHtmlContent(content string, isText bool) (reasoning string, IsHtmlContent bool) {+ reasoning = ""+ IsHtmlContent = false+ trimSpaceContent := strings.TrimSpace(content)++ // Check for special tags and update the state accordingly+ if trimSpaceContent == "<think>" {+ o.IsThinking = true+ } else if trimSpaceContent == "</think>" {+ o.IsThinking = false+ if o.Reasoning != "" {+ // If reasoning is not empty, append the content to reasoning+ reasoning = content[:]+ if !isText {+ content = ""+ }+ }+ o.Reasoning += content+ }++ // Check for HTML code blocks and toggle the HTML state+ if trimSpaceContent == "```" || (trimSpaceContent == "`" && o.LastContent == "``") {+ o.IsHtml = !o.IsHtml // Toggle HTML state+ if !o.IsHtml {+ IsHtmlContent = true+ if !o.IsRecordHtml {+ o.HtmlContent += content+ o.IsRecordHtml = true+ }+ }+ }++ // isModify is true, it means the user is modifying the chat+ // if o.IsModify {++ // }++ // If the content is a thinking block, append it to the Reasoning+ if o.IsThinking {+ o.Reasoning += content+ reasoning = content[:]+ if !isText {+ content = ""+ }+ }++ // If the content is HTML, append it to the HtmlContent+ if o.IsHtml {+ if !o.IsRecordHtml {+ o.HtmlContent += content+ }+ IsHtmlContent = true+ }++ o.LastContent = content // Store the last content sent in the chat++ return reasoning, IsHtmlContent+}++func (o *OpenAI) WriteEvent(request *ghttp.Request, content string, isText bool, isEnd bool) error {+ // Implementation for writing an event to the OpenAI response+ // This function should handle the logic for writing an event and return any error encountered+ Write := request.Response.Write+ if isEnd {+ Write = request.Response.WriteExit+ } else {+ o.Usage.CompletionTokens += 1 // Increment completion tokens for the final message+ }++ reasoning, IsHtmlContent := o.SetHtmlContent(content, isText) // Set HTML content and reasoning+ o.Content += content // Update the content in the OpenAI struct+ if isText {+ Write(content)+ } else {+ resultJson := ResultJson{+ Content: content,+ Reasoning: reasoning,+ IsHtmlContent: IsHtmlContent,+ Role: openai.ChatMessageRoleAssistant,+ IsEnd: isEnd,+ ThinkStart: o.ThinkStart,+ ThinkEnd: o.ThinkEnd,+ IsThink: o.IsThinking,+ UpdateTime: public.GetNowTime(),+ }+ strJson, err := json.Marshal(resultJson)+ if err != nil {+ return err // Handle JSON marshaling error+ }+ Write("id: " + o.ChatId + "\ndata: " + string(strJson) + "\n\n")+ }++ request.Response.Flush()+ return nil+}diff --git a/core/internal/service/askai/project.go b/core/internal/service/askai/project.gonew file mode 100644index 00000000..d0381415--- /dev/null+++ b/core/internal/service/askai/project.go@@ -0,0 +1,1143 @@+package askai++import (+ "billionmail-core/internal/service/public"+ "encoding/json"+ "fmt"+ "net/url"+ "os"+ "strings"++ "github.com/google/uuid"+)++const (+ PRODUCT_CONFIG_PATH = "../conf/askai"+ FILE_CDN_API = "https://cdn.billionmail.cn" // CDN API for file access+)++type KnowledgeInfo struct {+ Kid string `json:"kid"` // 知识库ID+ Title string `json:"title"` // 知识库标题+ Content string `json:"content"` // 知识库内容+ UpdateTime int64 `json:"update_time"` // 更新时间+}++type ProjectConfig struct {+ Domain string `json:"domain"` // 域名+ Urls []string `json:"urls"` // 相关URL列表+ ProjectName string `json:"project_name"` // 项目名称+ Description string `json:"description"` // 项目描述+ Industry string `json:"industry"` // 行业+ PrimaryLogo string `json:"primary_logo"` // 主Logo+ SecondaryLogo string `json:"secondary_logo"` // 副Logo+ Favicon string `json:"favicon"` // 网站图标+ KnowledgeBase []KnowledgeInfo `json:"knowledge_base"` // 知识库+ UpdateTime int64 `json:"update_time"` // 更新时间++}++// CompanyProfile represents the company profile information.+type CompanyProfile struct {+ LegalCompanyName string `json:"legal_company_name"` // 法定公司名称+ WebSite string `json:"web_site"` // 公司网站+ CompanyProfile string `json:"company_profile"` // 公司简介+ Email string `json:"email"` // 公司邮箱+ Phone string `json:"phone"` // 公司电话+ SupportUrl string `json:"support_url"` // 支持链接+ UpdateTime int64 `json:"update_time"` // 更新时间+}++// StyleConfig represents the style configuration for a project.+type StyleConfig struct {+ AccentColor string `json:"accent_color"` // 强调色+ TextColor string `json:"text_color"` // 文字颜色+ PageBackground string `json:"page_background"` // 页面背景色+ ContainerBackground string `json:"container_background"` // 容器背景色+ LinkSocialColor string `json:"link_social_color"` // 社交链接颜色+ LinkFooterColor string `json:"link_footer_color"` // 页脚链接颜色+ HeadingFont string `json:"heading_font"` // 标题字体+ BodyFont string `json:"body_font"` // 正文字体+ UpdateTime int64 `json:"update_time"` // 更新时间+}++// SiteMap represents a single entry in the site map of a project.+// It contains the title and URI path of the entry.+type SiteMap struct {+ Title string `json:"title"` // 网站标题+ // PageTitle string `json:"page_title"` // 页面标题+ // PageMarkdown string `json:"page_markdown"` // 页面Markdown内容+ UriPath string `json:"uri_path"` // URI路径+ UpdateTime int64 `json:"update_time"` // 更新时间+}++// FooterConfig represents the footer configuration for a project.+type FooterConfig struct {+ CopyrightText string `json:"copyright_text"` // 页脚版权文本+ Disclaimer string `json:"disclaimer"` // 免责声明+ Text string `json:"text"` // 页脚文本内容+ UpdateTime int64 `json:"update_time"` // 更新时间+}++type PromptConfig struct {+ Prompt string `json:"prompt"` // 提示内容+ UpdateTime int64 `json:"update_time"` // 更新时间+}++type ImageInfo struct {+ ImageId string `json:"image_id"` // 图片ID+ ImageUrl string `json:"image_url"` // 图片URL+ Filename string `json:"filename"` // 图片文件名+ AltText string `json:"alt_text"` // 图片替代文本+ ImageTag string `json:"image_tag"` // 图片标签+ UpdateTime int64 `json:"update_time"` // 更新时间+ Size string `json:"size"` // 图片大小 80x80+}++// ReadProjectConfig reads the project configuration from a JSON file based on the provided domain.+// It returns a ProjectConfig struct or an error if the file does not exist or cannot be read.+func ReadProjectConfig(Domain string) (ProjectConfig, error) {++ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/project.json", Domain)+ // Here you would implement the logic to read the project configuration from the file.+ // For now, we will just return a placeholder string.+ if !public.FileExists(filename) {+ return ProjectConfig{}, fmt.Errorf("project configuration file does not exist: %s", filename)+ }+ data, err := os.ReadFile(filename)+ if err != nil {+ return ProjectConfig{}, fmt.Errorf("error reading project configuration file: %v", err)+ }++ var config ProjectConfig+ err = json.Unmarshal(data, &config)+ if err != nil {+ return ProjectConfig{}, fmt.Errorf("error unmarshalling project configuration: %v", err)+ }+ return config, nil+}++// SaveProjectConfig saves the provided ProjectConfig to a JSON file based on the domain.+// It creates the directory if it does not exist and writes the configuration to project.json.+// If the file cannot be written, it returns an error.+// If the directory does not exist, it creates it with appropriate permissions.+func SaveProjectConfig(Domain string, config ProjectConfig) error {+ projectConfigPath := fmt.Sprintf("%s/%s", PRODUCT_CONFIG_PATH, Domain)+ if !public.FileExists(projectConfigPath) {+ os.MkdirAll(projectConfigPath, os.ModePerm)+ }+ filename := fmt.Sprintf("%s/project.json", projectConfigPath)++ configStr, err := json.MarshalIndent(config, "", " ")+ if err != nil {+ return fmt.Errorf("error marshalling project configuration: %v", err)+ }+ config.UpdateTime = public.GetNowTime() // Update the time before saving+ err = os.WriteFile(filename, configStr, os.ModePerm)+ if err != nil {+ return fmt.Errorf("error writing project configuration file: %v", err)+ }+ return nil+}++// Create initializes a new project configuration with the provided domain and URLs.+// It sets default values for other fields and saves the configuration to a file.+func Create(Domain string, urls []string) error {+ if urls == nil || len(urls) == 0 {+ urls = append(urls, "http://"+Domain) // Default URL if none provided+ }+ var config ProjectConfig = ProjectConfig{+ Domain: Domain,+ Urls: urls,+ ProjectName: "",+ Description: "",+ Industry: "",+ PrimaryLogo: "",+ SecondaryLogo: "",+ Favicon: "",+ KnowledgeBase: []KnowledgeInfo{},+ }++ err := SaveProjectConfig(Domain, config)+ if err != nil {+ return fmt.Errorf("error creating project configuration: %v", err)+ }++ return nil+}++// GetBaseInfo retrieves the base information of a project configuration based on the provided domain.+// It reads the project configuration and returns a ProjectConfig struct containing only the base information.+func GetBaseInfo(Domain string) (ProjectConfig, error) {+ config, err := ReadProjectConfig(Domain)+ if err != nil {+ return ProjectConfig{}, fmt.Errorf("error reading project configuration: %v", err)+ }++ // Return only the base information+ baseInfo := ProjectConfig{+ Domain: config.Domain,+ Urls: config.Urls,+ ProjectName: config.ProjectName,+ Description: config.Description,+ Industry: config.Industry,+ PrimaryLogo: config.PrimaryLogo,+ SecondaryLogo: config.SecondaryLogo,+ Favicon: config.Favicon,+ }++ // Get the knowledge base list+ // This will populate the KnowledgeBase field in the baseInfo struct.+ baseInfo.KnowledgeBase, err = GetKnowledgeBaseList(Domain)+ if err != nil {+ return ProjectConfig{}, fmt.Errorf("error getting knowledge base list: %v", err)+ }++ return baseInfo, nil+}++// ModifyBaseInfo updates the base information of a project configuration based on the provided domain.+// It reads the existing configuration, modifies the specified fields, and saves the updated configuration back to the file.+// If any field is empty, it will not be updated.+func ModifyBaseInfo(Domain string, projectName, description, industry, primaryLogo, secondaryLogo, favicon string) error {+ config, err := ReadProjectConfig(Domain)+ if err != nil {+ return fmt.Errorf("error reading project configuration: %v", err)+ }++ // Update the base information+ if projectName != "" {+ config.ProjectName = projectName+ }+ if description != "" {+ config.Description = description+ }+ if industry != "" {+ config.Industry = industry+ }+ if primaryLogo != "" {+ config.PrimaryLogo = primaryLogo+ }+ if secondaryLogo != "" {+ config.SecondaryLogo = secondaryLogo+ }+ if favicon != "" {+ config.Favicon = favicon+ }++ err = SaveProjectConfig(Domain, config)+ if err != nil {+ return fmt.Errorf("error saving project configuration: %v", err)+ }+ return nil+}++// ReadKnowledgeBase reads a specific knowledge base from a JSON file based on the provided domain and knowledge ID.+// It returns a KnowledgeInfo struct or an error if the file does not exist or cannot be+func ReadKnowledgeBase(Domain string, Kid string) (KnowledgeInfo, error) {+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/knowledge/%s.json", Domain, Kid)+ if !public.FileExists(filename) {+ return KnowledgeInfo{}, fmt.Errorf("knowledge base file does not exist: %s", filename)+ }+ data, err := os.ReadFile(filename)+ if err != nil {+ return KnowledgeInfo{}, fmt.Errorf("error reading knowledge base file: %v", err)+ }++ var knowledge KnowledgeInfo+ err = json.Unmarshal(data, &knowledge)+ if err != nil {+ return KnowledgeInfo{}, fmt.Errorf("error unmarshalling knowledge base: %v", err)+ }+ return knowledge, nil+}++// SaveKnowledgeBase saves the provided KnowledgeInfo to a JSON file based on the domain and knowledge ID.+// It creates the directory if it does not exist and writes the knowledge information to a JSON file+func SaveKnowledgeBase(Domain string, knowledge KnowledgeInfo) error {+ knowledgePath := fmt.Sprintf("%s/%s/knowledge", PRODUCT_CONFIG_PATH, Domain)+ if !public.FileExists(knowledgePath) {+ os.MkdirAll(knowledgePath, os.ModePerm)+ }+ filename := fmt.Sprintf("%s/%s.json", knowledgePath, knowledge.Kid)++ configStr, err := json.MarshalIndent(knowledge, "", " ")+ if err != nil {+ return fmt.Errorf("error marshalling knowledge base: %v", err)+ }++ err = os.WriteFile(filename, configStr, os.ModePerm)+ if err != nil {+ return fmt.Errorf("error writing knowledge base file: %v", err)+ }+ return nil+}++// GetKnowledgeBaseList retrieves a list of all knowledge bases for a given domain.+// It reads the knowledge base directory, iterates through the files, and returns a slice of KnowledgeInfo structs.+// If the directory does not exist or cannot be read, it returns an error.+func GetKnowledgeBaseList(Domain string) ([]KnowledgeInfo, error) {+ knowledgePath := fmt.Sprintf("%s/%s/knowledge", PRODUCT_CONFIG_PATH, Domain)+ if !public.FileExists(knowledgePath) {+ os.MkdirAll(knowledgePath, os.ModePerm)+ // If the knowledge base directory does not exist, create it+ }++ files, err := os.ReadDir(knowledgePath)+ if err != nil {+ return nil, fmt.Errorf("error reading knowledge base directory: %v", err)+ }++ var knowledgeList []KnowledgeInfo = []KnowledgeInfo{}+ for _, file := range files {+ if !file.IsDir() {+ knowledge, err := ReadKnowledgeBase(Domain, strings.Split(file.Name(), ".")[0])+ if err == nil {+ knowledgeList = append(knowledgeList, knowledge)+ }+ }+ }+ return knowledgeList, nil+}++// GetUUID generates a new UUID using the UUID version 7 and returns it as a string.+// UUID version 7 is a time-based UUID that is suitable for generating unique identifiers.+func GetUUID() string {+ return uuid.Must(uuid.NewV7()).String()++}++// CreateKnowledgeBaseFile creates a new knowledge base file with the provided domain, title, and content.+// It generates a unique ID for the knowledge base, constructs a KnowledgeInfo struct, and saves it using the SaveKnowledgeBase function.+func CreateKnowledgeBaseFile(Domain string, Title string, Content string) error {+ Tid := GetUUID()+ knowledge := KnowledgeInfo{+ Kid: Tid,+ Title: Title,+ Content: Content,+ UpdateTime: public.GetNowTime(),+ }+ return SaveKnowledgeBase(Domain, knowledge)+}++// ModifyKnowledgeBaseFile updates the title and content of an existing knowledge base file.+// It reads the existing knowledge base, modifies the specified fields, and saves the updated knowledge base.+// If the knowledge base does not exist or cannot be read, it returns an error.+func ModifyKnowledgeBaseFile(Domain string, Kid string, Title string, Content string) error {+ knowledge, err := ReadKnowledgeBase(Domain, Kid)+ if err != nil {+ return fmt.Errorf("error reading knowledge base: %v", err)+ }++ // Update the knowledge base information+ if Title != "" {+ knowledge.Title = Title+ }+ if Content != "" {+ knowledge.Content = Content+ }++ knowledge.UpdateTime = public.GetNowTime()+ err = SaveKnowledgeBase(Domain, knowledge)+ if err != nil {+ return fmt.Errorf("error saving knowledge base: %v", err)+ }+ return nil+}++// RemoveKnowledgeBaseFile removes a knowledge base file based on the provided domain and knowledge ID.+// It constructs the file path, checks if the file exists, and removes it.+func RemoveKnowledgeBaseFile(Domain string, Kid string) error {+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/knowledge/%s.json", Domain, Kid)+ if !public.FileExists(filename) {+ return fmt.Errorf("knowledge base file does not exist: %s", filename)+ }+ err := os.Remove(filename)+ if err != nil {+ return fmt.Errorf("error removing knowledge base file: %v", err)+ }+ return nil+}++// ReadCompanyProfile reads the company profile from a JSON file based on the provided domain.+// It returns a CompanyProfile struct or an error if the file does not exist or cannot be read.+func ReadCompanyProfile(Domain string) (CompanyProfile, error) {+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/company_profile.json", Domain)+ if !public.FileExists(filename) {+ companyProfileDefault := CompanyProfile{+ LegalCompanyName: "",+ WebSite: "",+ CompanyProfile: "",+ Email: "",+ Phone: "",+ SupportUrl: "",+ }+ // If the company profile file does not exist, return a default profile+ // This allows the system to handle cases where the profile has not been set up yet+ // and avoids errors when trying to read a non-existent file.+ // It also allows the user to create a new profile without needing to handle file not+ // found errors.+ companyProfileDefault.UpdateTime = public.GetNowTime()+ companyProfileJson, err := json.MarshalIndent(companyProfileDefault, "", " ")+ if err != nil {+ return CompanyProfile{}, fmt.Errorf("error marshalling company profile: %v", err)+ }+ err = os.WriteFile(filename, companyProfileJson, 0644)+ if err != nil {+ return CompanyProfile{}, fmt.Errorf("error creating company profile file: %v", err)+ }+ return companyProfileDefault, nil+ }+ data, err := os.ReadFile(filename)+ if err != nil {+ return CompanyProfile{}, fmt.Errorf("error reading company profile file: %v", err)+ }+ var profile CompanyProfile+ err = json.Unmarshal(data, &profile)+ if err != nil {+ return CompanyProfile{}, fmt.Errorf("error unmarshalling company profile: %v", err)+ }+ return profile, nil+}++// SaveCompanyProfile saves the provided CompanyProfile to a JSON file based on the domain.+// It creates the directory if it does not exist and writes the profile information to company_profile.json+func SaveCompanyProfile(Domain string, profile CompanyProfile) error {+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/company_profile.json", Domain)+ data, err := json.Marshal(profile)+ if err != nil {+ return fmt.Errorf("error marshalling company profile: %v", err)+ }+ err = os.WriteFile(filename, data, 0644)+ if err != nil {+ return fmt.Errorf("error saving company profile file: %v", err)+ }+ return nil+}++// GetCompanyProfile retrieves the company profile for a given domain.+// It reads the company profile from the file and returns a CompanyProfile struct.+// If the profile does not exist or cannot be read, it returns an error.+func GetCompanyProfile(Domain string) (CompanyProfile, error) {+ companyProfile, err := ReadCompanyProfile(Domain)+ if err != nil {+ return CompanyProfile{}, fmt.Errorf("error reading company profile: %v", err)+ }+ return companyProfile, nil+}++// ModifyCompanyProfile updates the company profile information based on the provided parameters.+// It reads the existing profile, modifies the specified fields, and saves the updated profile back to the file.+// If any field is empty, it will not be updated.+func ModifyCompanyProfile(Domain string, legalCompanyName, webSite, companyProfile, email, phone, supportUrl string) error {+ profile, err := ReadCompanyProfile(Domain)+ if err != nil {+ return fmt.Errorf("error reading company profile: %v", err)+ }++ // Update the company profile information+ if legalCompanyName != "" {+ profile.LegalCompanyName = legalCompanyName+ }+ if webSite != "" {+ profile.WebSite = webSite+ }+ if companyProfile != "" {+ profile.CompanyProfile = companyProfile+ }+ if email != "" {+ profile.Email = email+ }+ if phone != "" {+ profile.Phone = phone+ }+ if supportUrl != "" {+ profile.SupportUrl = supportUrl+ }++ profile.UpdateTime = public.GetNowTime()+ err = SaveCompanyProfile(Domain, profile)+ if err != nil {+ return fmt.Errorf("error saving company profile: %v", err)+ }+ return nil+}++// GetStyleConfig retrieves the style configuration for a given domain from a JSON file.+func GetStyleConfig(Domain string) (StyleConfig, error) {+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/style_config.json", Domain)+ if !public.FileExists(filename) {+ styleConfigDefault := StyleConfig{+ AccentColor: "#007bff", // Default accent color+ TextColor: "#000000", // Default text color+ PageBackground: "#ffffff", // Default page background color+ ContainerBackground: "#f8f9fa", // Default container background color+ LinkSocialColor: "#007bff", // Default social link color+ LinkFooterColor: "#6c757d", // Default footer link color+ HeadingFont: "Arial, sans-serif", // Default heading font+ BodyFont: "Arial, sans-serif", // Default body font+ UpdateTime: public.GetNowTime(), // Current time as update time+ }+ // If the style config file does not exist, return a default style config+ // This allows the system to handle cases where the style configuration has not been set up yet+ // and avoids errors when trying to read a non-existent file.+ styleConfigJson, err := json.MarshalIndent(styleConfigDefault, "", " ")+ if err != nil {+ return StyleConfig{}, fmt.Errorf("error marshalling style config: %v", err)+ }+ err = os.WriteFile(filename, styleConfigJson, 0644)+ if err != nil {+ return StyleConfig{}, fmt.Errorf("error saving style config file: %v", err)+ }+ return styleConfigDefault, nil+ }+ data, err := os.ReadFile(filename)+ if err != nil {+ return StyleConfig{}, fmt.Errorf("error reading style config file: %v", err)+ }++ var config StyleConfig+ err = json.Unmarshal(data, &config)+ if err != nil {+ return StyleConfig{}, fmt.Errorf("error unmarshalling style config: %v", err)+ }+ return config, nil+}++func SaveStyleConfig(Domain string, config StyleConfig) error {+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/style_config.json", Domain)+ data, err := json.MarshalIndent(config, "", " ")+ if err != nil {+ return fmt.Errorf("error marshalling style config: %v", err)+ }+ err = os.WriteFile(filename, data, 0644)+ if err != nil {+ return fmt.Errorf("error saving style config file: %v", err)+ }+ return nil+}++// ModifyStyleConfig saves the provided StyleConfig to a JSON file based on the domain.+// It creates the directory if it does not exist and writes the style configuration to style_config.json+func ModifyStyleConfig(Domain string, AccentColor string, TextColor string, PageBackground, ContainerBackground, LinkSocialColor, LinkFooterColor, HeadingFont, BodyFont string) error {+ config := StyleConfig{+ AccentColor: AccentColor,+ TextColor: TextColor,+ PageBackground: PageBackground,+ ContainerBackground: ContainerBackground,+ LinkSocialColor: LinkSocialColor,+ LinkFooterColor: LinkFooterColor,+ HeadingFont: HeadingFont,+ BodyFont: BodyFont,+ UpdateTime: public.GetNowTime(),+ }++ err := SaveStyleConfig(Domain, config)+ if err != nil {+ return fmt.Errorf("error saving style config file: %v", err)+ }+ return nil+}++// GetSiteMap retrieves the site map for a given domain from a JSON file.+// It reads the site map file and returns a slice of SiteMap structs.+// If the file does not exist or cannot be read, it returns an error.+func GetSiteMap(Domain string) ([]SiteMap, error) {+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/sitemap.json", Domain)+ if !public.FileExists(filename) {+ // If the site map file does not exist, return an empty slice+ // This allows the system to handle cases where the site map has not been set up+ // and avoids errors when trying to read a non-existent file.+ // It also allows the user to create a new site map without needing to handle file not found errors.+ emptySiteMap := []SiteMap{}+ emptySiteMapJson, err := json.MarshalIndent(emptySiteMap, "", " ")+ if err != nil {+ return nil, fmt.Errorf("error marshalling empty site map: %v", err)+ }+ err = os.WriteFile(filename, emptySiteMapJson, 0644)+ if err != nil {+ return nil, fmt.Errorf("error saving empty site map file: %v", err)+ }+ return emptySiteMap, nil+ }+ data, err := os.ReadFile(filename)+ if err != nil {+ return nil, fmt.Errorf("error reading site map file: %v", err)+ }++ var siteMap []SiteMap+ err = json.Unmarshal(data, &siteMap)+ if err != nil {+ return nil, fmt.Errorf("error unmarshalling site map: %v", err)+ }+ return siteMap, nil+}++func SaveSiteMap(Domain string, siteMap []SiteMap) error {+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/sitemap.json", Domain)+ data, err := json.MarshalIndent(siteMap, "", " ")+ if err != nil {+ return fmt.Errorf("error marshalling site map: %v", err)+ }+ err = os.WriteFile(filename, data, 0644)+ if err != nil {+ return fmt.Errorf("error saving site map file: %v", err)+ }+ return nil+}++// AddSiteMapNode adds a new site map node with the provided title and URI path to the site map of the specified domain.+// It reads the existing site map, appends the new node, and saves the updated site map back to the file.+// If the site map file does not exist or cannot be read, it returns an error.+func AddSiteMapNode(Domain string, Title string, UriPath string) error {+ siteMap, err := GetSiteMap(Domain)+ if err != nil {+ return fmt.Errorf("error getting site map: %v", err)+ }++ newNode := SiteMap{+ Title: Title,+ UriPath: UriPath,+ UpdateTime: public.GetNowTime(),+ }+ siteMap = append(siteMap, newNode)++ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/sitemap.json", Domain)+ data, err := json.MarshalIndent(siteMap, "", " ")+ if err != nil {+ return fmt.Errorf("error marshalling site map: %v", err)+ }+ err = os.WriteFile(filename, data, 0644)+ if err != nil {+ return fmt.Errorf("error saving site map file: %v", err)+ }+ return nil+}++// RemoveSiteMapNode removes a site map node based on the provided domain and URI path.+// It reads the existing site map, filters out the node with the specified URI path, and saves the updated site map back to the file.+// If the site map file does not exist or cannot be read, it returns an error.+func RemoveSiteMapNode(Domain string, UriPath string) error {+ siteMap, err := GetSiteMap(Domain)+ if err != nil {+ return fmt.Errorf("error getting site map: %v", err)+ }++ var updatedSiteMap []SiteMap+ for _, node := range siteMap {+ if node.UriPath != UriPath {+ updatedSiteMap = append(updatedSiteMap, node)+ }+ }++ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/sitemap.json", Domain)+ data, err := json.MarshalIndent(updatedSiteMap, "", " ")+ if err != nil {+ return fmt.Errorf("error marshalling site map: %v", err)+ }+ err = os.WriteFile(filename, data, 0644)+ if err != nil {+ return fmt.Errorf("error saving site map file: %v", err)+ }+ return nil+}++// GetFooter retrieves the footer configuration for a given domain from a JSON file.+// It reads the footer configuration file and returns a FooterConfig struct.+// If the file does not exist or cannot be read, it returns an error.+func GetFooter(Domain string) (FooterConfig, error) {+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/footer_config.json", Domain)+ if !public.FileExists(filename) {+ // If the footer config file does not exist, return a default footer config+ // This allows the system to handle cases where the footer configuration has not been set up+ // and avoids errors when trying to read a non-existent file.+ // It also allows the user to create a new footer configuration without needing to handle file+ // not found errors.+ defaultFooterConfig := FooterConfig{+ CopyrightText: "© 2023 Your Company. All rights reserved.",+ Disclaimer: "This is a sample disclaimer.",+ }+ defaultFooterConfig.UpdateTime = public.GetNowTime()+ defaultFooterJson, err := json.MarshalIndent(defaultFooterConfig, "", " ")+ if err != nil {+ return FooterConfig{}, fmt.Errorf("error marshalling default footer config: %v", err)+ }+ err = os.WriteFile(filename, defaultFooterJson, 0644)+ if err != nil {+ return FooterConfig{}, fmt.Errorf("error saving default footer config file: %v", err)+ }+ // Return the default footer config if the file does not exist+ return defaultFooterConfig, nil+ }+ data, err := os.ReadFile(filename)+ if err != nil {+ return FooterConfig{}, fmt.Errorf("error reading footer config file: %v", err)+ }++ var config FooterConfig+ err = json.Unmarshal(data, &config)+ if err != nil {+ return FooterConfig{}, fmt.Errorf("error unmarshalling footer config: %v", err)+ }+ return config, nil+}++// ModifyFooter updates the footer configuration for a given domain.+// It reads the existing footer configuration, modifies the specified fields, and saves the updated configuration back to the file.+// If any field is empty, it will not be updated.+func ModifyFooter(Domain string, CopyrightText, Disclaimer string, Text string) error {+ config, err := GetFooter(Domain)+ if err != nil {+ return fmt.Errorf("error getting footer config: %v", err)+ }++ // Update the footer configuration+ if CopyrightText != "" {+ config.CopyrightText = CopyrightText+ }+ if Disclaimer != "" {+ config.Disclaimer = Disclaimer+ }+ if Text != "" {+ config.Text = Text+ }++ config.UpdateTime = public.GetNowTime()+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/footer_config.json", Domain)+ data, err := json.Marshal(config)+ if err != nil {+ return fmt.Errorf("error marshalling footer config: %v", err)+ }+ err = os.WriteFile(filename, data, 0644)+ if err != nil {+ return fmt.Errorf("error saving footer config file: %v", err)+ }+ return nil+}++// GetPrompt retrieves the prompt configuration for a given domain from a JSON file.+// It reads the prompt configuration file and returns a PromptConfig struct.+// If the file does not exist or cannot be read, it returns an error.+func GetPrompt(Domain string) (PromptConfig, error) {+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/prompt_config.json", Domain)+ if !public.FileExists(filename) {+ // If the prompt config file does not exist, return a default prompt config+ // This allows the system to handle cases where the prompt configuration has not been set up+ // and avoids errors when trying to read a non-existent file.+ // It also allows the user to create a new prompt configuration without needing to handle file+ // not found errors.+ defaultPromptConfig := PromptConfig{+ Prompt: "This is a default prompt. Please customize it.",+ }+ defaultPromptConfig.UpdateTime = public.GetNowTime()+ defaultPromptJson, err := json.MarshalIndent(defaultPromptConfig, "", " ")++ if err != nil {+ return PromptConfig{}, fmt.Errorf("error marshalling default prompt config: %v", err)+ }+ err = os.WriteFile(filename, defaultPromptJson, 0644)+ if err != nil {+ return PromptConfig{}, fmt.Errorf("error saving default prompt config file: %v", err)+ }+ return defaultPromptConfig, nil+ }+ data, err := os.ReadFile(filename)+ if err != nil {+ return PromptConfig{}, fmt.Errorf("error reading prompt config file: %v", err)+ }++ var config PromptConfig+ err = json.Unmarshal(data, &config)+ if err != nil {+ return PromptConfig{}, fmt.Errorf("error unmarshalling prompt config: %v", err)+ }+ return config, nil+}++// ModifyPrompt updates the prompt configuration for a given domain.+// It reads the existing prompt configuration, modifies the specified fields, and saves the updated configuration back to the file.+// If the prompt is empty, it will not be updated.+func ModifyPrompt(Domain string, Prompt string) error {+ config, err := GetPrompt(Domain)+ if err != nil {+ return fmt.Errorf("error getting prompt config: %v", err)+ }++ // Update the prompt configuration+ if Prompt != "" {+ config.Prompt = Prompt+ }++ config.UpdateTime = public.GetNowTime()+ filename := fmt.Sprintf(PRODUCT_CONFIG_PATH+"/%s/prompt_config.json", Domain)+ data, err := json.Marshal(config)+ if err != nil {+ return fmt.Errorf("error marshalling prompt config: %v", err)+ }+ err = os.WriteFile(filename, data, 0644)+ if err != nil {+ return fmt.Errorf("error saving prompt config file: %v", err)+ }+ return nil+}++type BotResponse struct {+ Data BotData `json:"data"`+ Msg string `json:"msg"`+ Status bool `json:"status"`+}++type BotData struct {+ Description string `json:"description"`+ Domain string `json:"domain"`+ Markdown string `json:"markdown"`+ Footer BotFooter `json:"footer"`+ Icon string `json:"icon"`+ Images []ImageInfo `json:"images"`+ Keywords string `json:"keywords"`+ PrimaryLogo string `json:"primary_logo"`+ SecondaryLogo string `json:"secondary_logo"`+ Sitemap []BotSitemap `json:"sitemap"`+ Source string `json:"source"`+ Style BotStyle `json:"style"`+ Title string `json:"title"`+ URL string `json:"url"`+}++type BotFooter struct {+ Copyright string `json:"copyright"`+ Disclaimer string `json:"disclaimer"`+ Text string `json:"text"`+}++type BotSitemap struct {+ PageMarkdown string `json:"page_markdown"`+ PageTitle string `json:"page_title"`+ Title string `json:"title"`+ URIPath string `json:"uri_path"`+}++type BotStyle struct {+ AccentColor string `json:"accent_color"`+ BodyFont string `json:"body_font"`+ ContainerBackground string `json:"container_background"`+ HeadingFont string `json:"heading_font"`+ LinkFooterColor string `json:"link_footer_color"`+ LinkSocialColor string `json:"link_social_color"`+ PageBackground string `json:"page_background"`+ TextColor string `json:"text_color"`+}++func SaveImagesConfig(Domain string, images []ImageInfo) error {+ imagesPath := fmt.Sprintf("%s/%s/images.json", PRODUCT_CONFIG_PATH, Domain)+ if !public.FileExists(PRODUCT_CONFIG_PATH + "/" + Domain) {+ os.MkdirAll(PRODUCT_CONFIG_PATH+"/"+Domain, os.ModePerm)+ }+ data, err := json.MarshalIndent(images, "", " ")+ if err != nil {+ return fmt.Errorf("error marshalling images: %v", err)+ }+ err = os.WriteFile(imagesPath, data, 0644)+ if err != nil {+ return fmt.Errorf("error saving images file: %v", err)+ }+ return nil+}++func ReadImagesConfig(Domain string) ([]ImageInfo, error) {+ imagesPath := fmt.Sprintf("%s/%s/images.json", PRODUCT_CONFIG_PATH, Domain)+ if !public.FileExists(imagesPath) {+ os.WriteFile(imagesPath, []byte("[]"), 0644)+ }+ data, err := os.ReadFile(imagesPath)+ if err != nil {+ return []ImageInfo{}, fmt.Errorf("error reading images configuration file: %v", err)+ }++ var images []ImageInfo+ err = json.Unmarshal(data, &images)+ if err != nil {+ return []ImageInfo{}, fmt.Errorf("error unmarshalling images configuration: %v", err)+ }+ return images, nil+}++type UploadImageResponse struct {+ Status bool `json:"status"`+ Msg string `json:"msg"`+ Data struct {+ URL string `json:"url"`+ } `json:"data"`+}++// UploadImage(req.Domain, req.Image, req.Filename, req.AltText, req.ImageTag)+func UploadImage(Domain string, Image string, Filename string, AltText string, ImageTag string) (string, error) {+ imageInfo := ImageInfo{+ ImageId: GetUUID(),+ ImageUrl: "",+ Filename: Filename,+ AltText: AltText,+ ImageTag: ImageTag,+ UpdateTime: public.GetNowTime(),+ }+ apiUrl := fmt.Sprintf("%s/upload-image", FILE_CDN_API)+ params := url.Values{}+ params.Set("imageId", imageInfo.ImageId)+ params.Set("imageBase64", Image)+ params.Set("imageFilename", Filename)++ result, err := public.HttpPostSrc(apiUrl, params, 60)+ if err != nil {+ return "", err+ }+ var resultData UploadImageResponse+ err = json.Unmarshal([]byte(result), &resultData)+ if err != nil {+ return "", err+ }++ if resultData.Status == false {+ return "", fmt.Errorf("upload image failed: %s", resultData.Msg)+ }++ imageInfo.ImageUrl = resultData.Data.URL++ // Save the image information to the images.json file+ images, err := ReadImagesConfig(Domain)+ if err != nil {+ return "", fmt.Errorf("error reading images configuration: %v", err)+ }+ images = append(images, imageInfo)+ err = SaveImagesConfig(Domain, images)+ if err != nil {+ return "", fmt.Errorf("error saving images configuration: %v", err)+ }++ return imageInfo.ImageUrl, nil+}++// ModifyImage updates the alt text and image tag of an existing image in the images configuration.+// It reads the existing images configuration, modifies the specified fields for the image with the given ID and saves the updated configuration back to the file.+// If the images configuration file does not exist or cannot be read, it returns an error.+func ModifyImage(Domain string, ImageId string, AltText string, ImageTag string) error {+ images, err := ReadImagesConfig(Domain)+ if err != nil {+ return fmt.Errorf("error reading images configuration: %v", err)+ }+ for i, image := range images {+ if image.ImageId == ImageId {+ // Update the AltText and ImageTag if they are not empty+ if AltText != "" {+ images[i].AltText = AltText+ }+ if ImageTag != "" {+ images[i].ImageTag = ImageTag+ }+ images[i].UpdateTime = public.GetNowTime()+ break+ }+ }+ err = SaveImagesConfig(Domain, images)+ if err != nil {+ return fmt.Errorf("error saving images configuration: %v", err)+ }+ return nil+}++// RemoveImage removes an image from the images configuration based on the provided domain and image ID.+// It reads the existing images configuration, filters out the image with the specified ID, and saves the updated configuration back to the file.+// If the images configuration file does not exist or cannot be read, it returns an error.+func RemoveImage(Domain string, ImageId string) error {+ images, err := ReadImagesConfig(Domain)+ if err != nil {+ return fmt.Errorf("error reading images configuration: %v", err)+ }++ for i, image := range images {+ if image.ImageId == ImageId {+ images = append(images[:i], images[i+1:]...)+ break+ }+ }+ err = SaveImagesConfig(Domain, images)+ if err != nil {+ return fmt.Errorf("error saving images configuration: %v", err)+ }+ // Optionally, you can also delete the image file from the CDN if needed+ apiUrl := fmt.Sprintf("%s/remove-image", FILE_CDN_API)+ params := url.Values{}+ params.Set("imageId", ImageId)+ go public.HttpPostSrc(apiUrl, params, 60)+ return nil+}++// GetImages retrieves the images configuration for a given domain.+// It reads the images.json file and returns a slice of ImageInfo structs.+// If the file does not exist or cannot be read, it returns an error.+func GetImages(Domain string) ([]ImageInfo, error) {+ images, err := ReadImagesConfig(Domain)+ if err != nil {+ return []ImageInfo{}, fmt.Errorf("error reading images configuration: %v", err)+ }+ return images, nil+}++func AutoGetProjectInfo() {++ dirs, err := os.ReadDir(PRODUCT_CONFIG_PATH)+ if err != nil {+ fmt.Println("Error reading project config directory:", err)+ return+ }++ for _, dir := range dirs {+ if !dir.IsDir() {+ continue // Skip files, only process directories+ }++ domain := dir.Name()+ projectConfigFile := fmt.Sprintf("%s/%s/project.json", PRODUCT_CONFIG_PATH, domain)+ if !public.FileExists(projectConfigFile) {+ continue // Skip if project.json does not exist for this domain+ }++ // Read the project configuration+ config, err := ReadProjectConfig(domain)+ if err != nil {+ fmt.Printf("Error reading project configuration for %s: %v\n", domain, err)+ continue+ }++ if config.UpdateTime > 0 {+ continue // Skip if the project configuration has already been updated+ }++ if len(config.Urls) == 0 {+ continue // Skip if there are no URLs to process+ }++ url := "http://cdn.billionmail.com/bot?url=" + config.Urls[0]+ resultBody, err := public.HttpGetSrc(url, 1800)+ if err != nil {+ fmt.Printf("Error fetching project data for %s: %v\n", domain, err)+ continue+ }++ // Parse the JSON response+ var result BotResponse+ err = json.Unmarshal([]byte(resultBody), &result)+ if err != nil {+ fmt.Printf("Error parsing project data for %s: %v\n", domain, err)+ continue+ }++ config.Description = result.Data.Description+ config.Favicon = result.Data.Icon+ config.PrimaryLogo = result.Data.PrimaryLogo+ config.SecondaryLogo = result.Data.SecondaryLogo+ config.UpdateTime = public.GetNowTime()+ SaveProjectConfig(domain, config)++ companyConfig, _ := GetCompanyProfile(domain)+ if companyConfig.LegalCompanyName == "" {+ companyConfig.LegalCompanyName = result.Data.Title+ }+ if companyConfig.WebSite == "" {+ companyConfig.WebSite = result.Data.URL+ }++ if companyConfig.CompanyProfile == "" {+ companyConfig.CompanyProfile = result.Data.Description+ }+ companyConfig.UpdateTime = public.GetNowTime()++ SaveCompanyProfile(domain, companyConfig)++ styleConfig, _ := GetStyleConfig(domain)+ if styleConfig.AccentColor == "" {+ styleConfig.AccentColor = result.Data.Style.AccentColor+ }+ if styleConfig.TextColor == "" {+ styleConfig.TextColor = result.Data.Style.TextColor+ }+ if styleConfig.PageBackground == "" {+ styleConfig.PageBackground = result.Data.Style.PageBackground+ }+ if styleConfig.ContainerBackground == "" {+ styleConfig.ContainerBackground = result.Data.Style.ContainerBackground+ }+ if styleConfig.LinkSocialColor == "" {+ styleConfig.LinkSocialColor = result.Data.Style.LinkSocialColor+ }+ if styleConfig.LinkFooterColor == "" {+ styleConfig.LinkFooterColor = result.Data.Style.LinkFooterColor+ }+ if styleConfig.HeadingFont == "" {+ styleConfig.HeadingFont = result.Data.Style.HeadingFont+ }+ if styleConfig.BodyFont == "" {+ styleConfig.BodyFont = result.Data.Style.BodyFont+ }+ styleConfig.UpdateTime = public.GetNowTime()++ SaveStyleConfig(domain, styleConfig)++ siteMap, _ := GetSiteMap(domain)++ for _, sitemapNode := range result.Data.Sitemap {+ // check if the node already exists in the site map+ exists := false+ for _, existingNode := range siteMap {+ if existingNode.UriPath == sitemapNode.URIPath {+ exists = true+ break+ }+ }+ if exists {+ continue+ }+ newNode := SiteMap{+ Title: sitemapNode.Title,+ // PageTitle: sitemapNode.PageTitle,+ // PageMarkdown: sitemapNode.PageMarkdown,+ UriPath: sitemapNode.URIPath,+ UpdateTime: public.GetNowTime(),+ }+ siteMap = append(siteMap, newNode)+ }+ SaveSiteMap(domain, siteMap)++ CreateKnowledgeBaseFile(domain, result.Data.Title, result.Data.Markdown)++ images, err := ReadImagesConfig(domain)+ if err != nil {+ fmt.Printf("Error reading images configuration for %s: %v\n", domain, err)+ continue+ }++ for _, image := range result.Data.Images {+ exists := false+ for _, img := range images {+ if img.ImageUrl == image.ImageUrl {+ exists = true+ break+ }+ }+ if !exists && image.ImageUrl != "" {+ image.ImageId = GetUUID()+ image.UpdateTime = public.GetNowTime()+ images = append(images, image)+ }+ }+ err = SaveImagesConfig(domain, images)+ if err != nil {+ fmt.Printf("Error saving images configuration for %s: %v\n", domain, err)+ continue+ }++ if result.Data.Footer.Copyright != "" {+ ModifyFooter(domain, result.Data.Footer.Copyright, result.Data.Footer.Disclaimer, result.Data.Footer.Text)+ }++ }+}diff --git a/core/internal/service/askai/prompts.go b/core/internal/service/askai/prompts.gonew file mode 100644index 00000000..c4ec63c5--- /dev/null+++ b/core/internal/service/askai/prompts.go@@ -0,0 +1,65 @@+package askai++// 定义提示词模板+const (+ SEARCH_START = "<<<<<<< SEARCH"+ DIVIDER = "======="+ REPLACE_END = ">>>>>>> REPLACE"+ MAX_REQUESTS_PER_IP = 2+ INITIAL_SYSTEM_PROMPT = `Role:+You are a senior marketing email expert with over 10 years of experience in planning and producing marketing emails. You are particularly adept at creating visually appealing and highly attractive email interfaces, well-versed in the characteristics of marketing emails in different industries and user psychology. You can accurately grasp the visual presentation, content rhythm, and conversion guidance logic of emails. You have created high-quality marketing emails with an open rate exceeding 30% and a conversion rate exceeding 5% for clients in various fields such as e-commerce, education, and finance. The emails you designed have been included as excellent cases by industry media many times.+Functions:++ 1. When users request to generate an email, you must strictly follow the above requirements to ensure the email content is complete, the design is exquisite, and the code is standardized.+ 2. When users consult questions related to email design, provide professional and detailed answers to help users understand the principles and skills of email design.+ 3. When users consult other questions, maintain a professional attitude and try to provide relevant information or suggestions.++Requirements for Email Generation (only used when generating emails):++ 1. Please use HTML to generate an exquisite marketing promotion email. On the premise of focusing on the beautiful and delicate design of the email interface, meet the following requirements: The email content must include an eye-catching subject, a clear brand logo, an attractive product/activity introduction (including core selling points, preferential information, etc.), clear call-to-action buttons (such as "Buy Now", "Learn More", etc.), necessary contact information and unsubscribe options. In terms of visual design, the color matching should pay attention to layering and harmony. The matching mode of main color + auxiliary color + accent color can be adopted, with the main color accounting for 60%, the auxiliary color 30%, and the accent color 10%. The color saturation and lightness are moderate to avoid being too dazzling or dark. In terms of layout, the art of white space should be used to have reasonable spacing between elements to create a sense of breath. At the same time, strengthen the layering through alignment, grouping and other methods. The combination of pictures and texts should be natural and appropriate. The pictures should be high-definition and highly relevant to the content. You can appropriately add design elements such as shadows and rounded corners to enhance the three-dimensional sense. The font selection should match the overall style. The title font can be more designed, and the text font should be clear and easy to read. The font size and spacing should be reasonably distinguished according to the importance of the content to improve reading comfort. The overall style should be simple, professional and vibrant according to the characteristics of the target audience (urban white-collar workers aged 25-40), and at the same time incorporate exquisite detail designs, such as the hover effect of buttons, subtle gradients of borders, creative design of dividing lines, etc.+ 2. The generated HTML email must have good compatibility, be compatible with mainstream email clients (such as Gmail, Outlook, NetEase Mail, QQ Mail, etc.), and display normally on different devices (computers, mobile phones, tablets) to avoid problems such as layout disorder, inability to load pictures, and text overlap. The code should be concise and standardized, and avoid using JavaScript scripts.+ 3. Regarding the use of pictures: only use pictures from reliable sources, and it is forbidden to fabricate false pictures.+ 4. The email subject should be concise and clear, able to accurately convey the email theme and attract users' attention, and put the subject into the HTML <title> tag. The main body of the email must contain a clear brand logo (such as a logo), and provide contact information (such as customer service phone number, email address, etc.) at the beginning or end of the email, so that users can easily contact you if they have any questions or need further information.+ 5. Note: If there is a QR code for contact information, use it as much as possible, but note that the size of the QR code should not be less than 80x80px. When you need to use icons in the main text, you can use emojis or Unicode characters instead of icons to avoid using pictures with uncertain purposes.+ 6. Output: A complete email (subject, HTML body, signature). Only prepare HTML (no explanation); all tags are closed.+ 7. The HTML code must be included in the code block, and the language mark of the code block is ` + "```html\n\n ... \n\n```" + `。+ 8. Example Email Content:` + "```" + `html<!DOCTYPE html><html lang="XX">...</html>` + "```"++ FOLLOW_UP_SYSTEM_PROMPT = `You are an expert web developer modifying an existing HTML file.+The user wants to apply changes based on their request.+You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT output the entire file.+Explain the changes briefly *before* the blocks if necessary, but the code changes THEMSELVES MUST be within the blocks.+Format Rules:+ 1. Start with ` + SEARCH_START + `+ 2. Provide the exact lines from the current email that need to be replaced.+ 3. Use ` + DIVIDER + ` to separate the search block from the replacement.+ 4. Provide the new lines that should replace the original lines.+ 5. End with ` + REPLACE_END + `+ 6. You can use multiple SEARCH/REPLACE blocks if changes are needed in different parts of the email.+ 7. To insert content, use an empty SEARCH block (only ` + SEARCH_START + ` and ` + DIVIDER + ` on their lines) if inserting at the very beginning, otherwise provide the line *before* the insertion point in the SEARCH block and include that line plus the new content in the REPLACE block.+ 8. To delete content, provide the lines to delete in the SEARCH block and leave the REPLACE block empty (only ` + DIVIDER + ` and ` + REPLACE_END + ` on their lines).+ 9. IMPORTANT: The SEARCH block must *exactly* match the current email content, including punctuation and formatting.++ Example Modifying Code:+ Some explanation...+ ` + "```" + SEARCH_START + `+ <h1>Old Title</h1>+ ` + DIVIDER + `+ <h1>New Title</h1>+ ` + REPLACE_END + `+ ` + SEARCH_START + `+ </body>+ ` + DIVIDER + `+ <script>console.log("Added script");</script>+ </body>+ ` + REPLACE_END + `+ ` + "```" + `++ Example Deleting Code:+ Removing the paragraph...+ ` + "```" + SEARCH_START + `+ <p>This paragraph will be deleted.</p>+ ` + DIVIDER + `+ ` + REPLACE_END + `+ ` + "```"+)diff --git a/core/internal/service/askai/supplier.go b/core/internal/service/askai/supplier.gonew file mode 100644index 00000000..ca45fbd3--- /dev/null+++ b/core/internal/service/askai/supplier.go@@ -0,0 +1,560 @@+package askai++import (+ "billionmail-core/internal/service/public"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "sort"++ "github.com/gogf/gf/v2/frame/g"+)++const (+ SUPPLIER_CONFIG_PATH = "../conf/supplier"+ SUPPLIER_TEMPLATE_PATH = SUPPLIER_CONFIG_PATH + "/template"+)++type Supplier struct {+ SupplierTitle string `json:"supplierTitle"`+ SupplierName string `json:"supplierName"`+ BaseUrl string `json:"baseUrl"`+ BaseUrlExample string `json:"baseUrlExample"`+ IsUseUrlExample bool `json:"isUseUrlExample"`+ ApiKey string `json:"apiKey"`+ Home string `json:"home"`+ Help string `json:"help"`+ Status bool `json:"status"`+ Sort int `json:"sort"`+ Icon string `json:"icon"`+}++type ModelInfo struct {+ Title string `json:"title"`+ SupplierName string `json:"supplierName"`+ ModelId string `json:"modelId"`+ MaxTokens int `json:"max_tokens"`+ Capability []string `json:"capability"`+ Status bool `json:"status"`+}++var IsSyncTemplateToConfig = false++// SyncTemplateToConfig copies the template files from the SUPPLIER_TEMPLATE_PATH to the SUPPLIER_CONFIG_PATH.+func SyncTemplateToConfig() {+ if IsSyncTemplateToConfig {+ return+ }+ if !public.FileExists(SUPPLIER_TEMPLATE_PATH) {+ g.Log().Error(context.Background(), "Supplier template path does not exist: "+SUPPLIER_TEMPLATE_PATH, public.GetCwdPath())+ return+ }++ supplierTemplates, err := os.ReadDir(SUPPLIER_TEMPLATE_PATH)++ if err != nil {+ return+ }++ for _, supplier := range supplierTemplates {+ supplierName := supplier.Name()+ if supplierName == "" {+ continue+ }++ dstSupplierPath := SUPPLIER_CONFIG_PATH + "/" + supplierName+ if !public.FileExists(dstSupplierPath) {+ os.MkdirAll(dstSupplierPath, os.ModePerm)+ }++ srcConfigFile := SUPPLIER_TEMPLATE_PATH + "/" + supplierName + "/config.json"+ dstConfigFile := dstSupplierPath + "/config.json"+ if !public.FileExists(dstConfigFile) {+ fBody, err := os.ReadFile(srcConfigFile)+ if err != nil {+ continue+ }+ os.WriteFile(dstConfigFile, fBody, os.ModePerm)+ }++ srcModelsFile := SUPPLIER_TEMPLATE_PATH + "/" + supplierName + "/models.json"+ dstModelsFile := dstSupplierPath + "/models.json"+ if !public.FileExists(dstModelsFile) {+ fBody, err := os.ReadFile(srcModelsFile)+ if err != nil {+ continue+ }+ os.WriteFile(dstModelsFile, fBody, os.ModePerm)+ }++ srcEmbeddingFile := SUPPLIER_TEMPLATE_PATH + "/" + supplierName + "/embedding.json"+ dstEmbeddingFile := dstSupplierPath + "/embedding.json"+ if !public.FileExists(dstEmbeddingFile) {+ fBody, err := os.ReadFile(srcEmbeddingFile)+ if err != nil {+ continue+ }+ os.WriteFile(dstEmbeddingFile, fBody, os.ModePerm)+ }+ }++ IsSyncTemplateToConfig = true++}++func Status() bool {+ return len(Models("")) > 0 // Ensure models are loaded to check their status+}++// List retrieves a list of suppliers from the configuration directory.+// It reads the supplier configuration files and returns a slice of Supplier structs.+func List() []Supplier {+ SyncTemplateToConfig() // Ensure templates are synced before listing suppliers++ if !public.FileExists(SUPPLIER_CONFIG_PATH) {+ return nil+ }++ supplierList := make([]Supplier, 0)+ supplierNameList, err := os.ReadDir(SUPPLIER_CONFIG_PATH) // This is just a placeholder for the actual implementation+ if err != nil {+ return supplierList+ }+ for _, supplier := range supplierNameList {+ if !supplier.IsDir() {+ continue+ }++ if supplier.Name() == "template" {+ continue+ }++ supplierPath := SUPPLIER_CONFIG_PATH + "/" + supplier.Name()+ configFile := supplierPath + "/config.json"+ if !public.FileExists(configFile) {+ continue+ }++ fBody, err := os.ReadFile(configFile)+ if err != nil {+ continue+ }+ var supplierConfig Supplier+ err = json.Unmarshal(fBody, &supplierConfig)+ if err != nil {+ continue+ }++ supplierList = append(supplierList, supplierConfig)+ }++ // Sort suppliers by their sort order ASC+ if len(supplierList) > 0 {+ sort.Slice(supplierList, func(i, j int) bool {+ return supplierList[i].Sort < supplierList[j].Sort+ })+ }++ return supplierList+}++// Models retrieves the list of models for a given supplier from the models.json file.+// It reads the file, unmarshals the JSON content into a slice of ModelInfo structs, and returns it.+// If the file does not exist or an error occurs, it returns an empty slice.+func GetModelList(supplierName string) []ModelInfo {+ modelsFile := SUPPLIER_CONFIG_PATH + "/" + supplierName + "/models.json"++ Models := make([]ModelInfo, 0)+ if !public.FileExists(modelsFile) {+ return Models+ }++ supplierConfig, err := ReadSupplierConfig(supplierName)+ if err != nil {+ return Models+ }+ if supplierConfig.Status == false || supplierConfig.ApiKey == "" || supplierConfig.BaseUrl == "" {+ return Models // If the supplier is not active or missing API key/base URL, return empty models+ }++ fBody, err := os.ReadFile(modelsFile)+ if err != nil {+ return Models+ }++ err = json.Unmarshal(fBody, &Models)+ if err != nil {+ return Models+ }++ for i := 0; i < len(Models); i++ {+ if Models[i].Title == "" {+ Models[i].Title = fmt.Sprintf("%s/%s", supplierName, Models[i].ModelId)+ }+ if Models[i].MaxTokens == 0 {+ Models[i].MaxTokens = 4096 // Default max tokens if not specified+ }+ }++ return Models+}++// GetModelInfo retrieves a specific model's information by its ID from the supplier's model list.+// It iterates through the models and returns the one that matches the provided modelId.+func GetModelInfo(supplierName string, modelId string) *ModelInfo {+ models := GetModelList(supplierName)+ for _, model := range models {+ if model.ModelId == modelId {+ return &model+ }+ }+ return nil+}++// saveModelsToFile saves the provided models to the specified file in JSON format.+// It marshals the models slice into JSON with indentation for readability.+func saveModelsToFile(modelsFile string, models []ModelInfo) error {+ fBody, err := json.MarshalIndent(models, "", " ")+ if err != nil {+ return err+ }++ err = os.WriteFile(modelsFile, fBody, os.ModePerm)+ if err != nil {+ return err+ }++ return nil+}++// SaveModelInfo saves or updates a model's information in the supplier's models.json file.+// If the model already exists, it updates the existing entry; otherwise, it appends the new model.+// It reads the existing models, modifies or adds the new model, and writes the updated list.+func SaveModelInfo(supplierName string, modelId string, modelInfo ModelInfo) error {+ modelsFile := SUPPLIER_CONFIG_PATH + "/" + supplierName + "/models.json"++ // Read existing models+ existingModels := GetModelList(supplierName)++ // Update or add the model+ for i, model := range existingModels {+ if model.ModelId == modelId {+ existingModels[i] = modelInfo+ return saveModelsToFile(modelsFile, existingModels)+ }+ }++ // If not found, append the new model+ existingModels = append(existingModels, modelInfo)+ return saveModelsToFile(modelsFile, existingModels)+}++// Models retrieves a list of models for a specific supplier or all suppliers if no name is provided.+// It checks the status of each model and returns only those that are active if no supplier name is specified.+func Models(supplierName string) []ModelInfo {+ supplierList := make([]string, 0)+ if supplierName != "" {+ supplierList = append(supplierList, supplierName)+ } else {+ // If no supplier name is provided, list all suppliers+ supplierDirList, err := os.ReadDir(SUPPLIER_CONFIG_PATH)+ if err != nil {+ return nil+ }+ for _, supplier := range supplierDirList {+ if !supplier.IsDir() || supplier.Name() == "template" {+ continue+ }+ supplierList = append(supplierList, supplier.Name())+ }+ }++ models := make([]ModelInfo, 0)+ for _, supplier := range supplierList {+ models = append(models, GetModelList(supplier)...)+ }++ // Filter models by status+ isCheckStatus := false+ if supplierName == "" {+ isCheckStatus = true+ }+ if isCheckStatus {+ modelList := make([]ModelInfo, 0)+ for i := 0; i < len(models); i++ {+ if models[i].Status {+ modelList = append(modelList, models[i])+ }+ }+ return modelList+ }++ return models+}++// AddModel adds a new model to the specified supplier's models.json file.+// It creates a ModelInfo struct with the provided details and saves it using SaveModelInfo.+// If the model already exists, it updates the existing entry with the new information.+func AddModel(supplierName string, title string, modelId string, max_tokens int, capability []string) error {+ modelInfo := ModelInfo{+ Title: title,+ SupplierName: supplierName,+ ModelId: modelId,+ MaxTokens: max_tokens,+ Capability: capability,+ Status: true,+ }++ return SaveModelInfo(supplierName, modelId, modelInfo)+}++// RemoveModel removes a model from the specified supplier's models.json file.+// It reads the existing models, finds the model with the specified modelId, and removes it.+// If the model is found and removed, it saves the updated list back to the file.+func RemoveModel(supplierName string, modelId string) error {+ modelsFile := SUPPLIER_CONFIG_PATH + "/" + supplierName + "/models.json"++ // Read existing models+ existingModels := GetModelList(supplierName)++ // Remove the model+ for i, model := range existingModels {+ if model.ModelId == modelId {+ existingModels = append(existingModels[:i], existingModels[i+1:]...)+ return saveModelsToFile(modelsFile, existingModels)+ }+ }++ return nil // Model not found, nothing to remove+}++// SaveSupplierConfig saves the supplier configuration to a JSON file.+// It creates the necessary directory structure if it doesn't exist and writes the configuration to config.json.+func SaveSupplierConfig(supplierName string, supplierConfig Supplier) error {+ configDir := SUPPLIER_CONFIG_PATH + "/" + supplierName+ if !public.FileExists(configDir) {+ err := os.MkdirAll(configDir, os.ModePerm)+ if err != nil {+ return err+ }+ }+ configFile := configDir + "/config.json"++ fBody, err := json.MarshalIndent(supplierConfig, "", " ")+ if err != nil {+ return err+ }++ err = os.WriteFile(configFile, fBody, os.ModePerm)+ if err != nil {+ return err+ }++ return nil+}++// ReadSupplierConfig reads the supplier configuration from a JSON file.+// It checks if the configuration file exists, reads its content, and unmarshals it into a Supplier struct.+func ReadSupplierConfig(supplierName string) (*Supplier, error) {+ configFile := SUPPLIER_CONFIG_PATH + "/" + supplierName + "/config.json"+ if !public.FileExists(configFile) {+ return nil, os.ErrNotExist+ }+ fBody, err := os.ReadFile(configFile)+ if err != nil {+ return nil, err+ }+ var supplierConfig Supplier+ err = json.Unmarshal(fBody, &supplierConfig)+ if err != nil {+ return nil, err+ }+ return &supplierConfig, nil+}++// SetSupplierConfig updates the supplier configuration with the provided base URL and API key.+// It reads the existing configuration, modifies it, and saves it back to the file.+// If the configuration file does not exist, it returns an error indicating that the supplier configuration was not found.+// This function is useful for updating the supplier's API settings without needing to recreate the entire configuration.+func SetSupplierConfig(supplierName string, baseUrl string, apiKey string) error {+ supplierConfig, err := ReadSupplierConfig(supplierName)+ if err != nil {+ return errors.New("supplier configuration not found")+ }++ supplierConfig.BaseUrl = baseUrl+ supplierConfig.ApiKey = apiKey++ return SaveSupplierConfig(supplierName, *supplierConfig)+}++// Test whether the model supplier baseURL and apiKey are available+// Test whether the baseURL can be accessed normally+// Test whether the apiKey is correct+func Testing(applierName string, baseUrl string, apiKey string) error {+ if applierName == "" || baseUrl == "" || apiKey == "" {+ return errors.New("applier name, base URL, and API key are required")+ }++ // fmt.Printf("Testing supplier: %s\n", applierName)+ // fmt.Printf("Base URL: %s\n", baseUrl)+ // fmt.Printf("API Key: %s\n", apiKey)+ // Here you would implement the actual testing logic, such as making a request to the supplier+ return nil+}++// GetSupplierConfig retrieves the configuration for a specific supplier by its name.+// It reads the configuration file and returns a Supplier struct containing the supplier's details.+// If the configuration file does not exist or an error occurs, it returns an error.+func GetSupplierConfig(supplierName string) (*Supplier, error) {+ return ReadSupplierConfig(supplierName)+}++// SetSupplierStatus updates the status of a supplier in its configuration file.+// It reads the existing configuration, modifies the status, and saves it back to the file.+func SetSupplierStatus(supplierName string, status bool) error {+ supplierConfig, err := ReadSupplierConfig(supplierName)+ if err != nil {+ return errors.New("supplier configuration not found")+ }++ supplierConfig.Status = status++ return SaveSupplierConfig(supplierName, *supplierConfig)+}++// SetModelStatus updates the status of a specific model in the supplier's models.json file.+// It reads the existing models, modifies the status of the specified model, and saves the updated list back to the file.+// If the model is not found, it returns an error indicating that the model does not exist+func SetModelStatus(supplierName string, modelId string, status bool) error {+ modelsFile := SUPPLIER_CONFIG_PATH + "/" + supplierName + "/models.json"++ // Read existing models+ existingModels := GetModelList(supplierName)++ // Update the model status+ for i, model := range existingModels {+ if model.ModelId == modelId {+ existingModels[i].Status = status+ return saveModelsToFile(modelsFile, existingModels)+ }+ }++ return errors.New("model not found")+}++// AddSupplier creates a new supplier configuration file with the provided details.+// It checks if a supplier with the same name already exists, and if not, it creates a new Supplier struct+func AddSupplier(supplierTitle string, supplierName string, baseUrl string, apiKey string) error {+ supplierPath := SUPPLIER_CONFIG_PATH + "/" + supplierName+ if public.FileExists(supplierPath) {+ return errors.New("supplier already exists")+ }++ supplier := Supplier{+ SupplierTitle: supplierTitle,+ SupplierName: supplierName,+ BaseUrl: baseUrl,+ BaseUrlExample: baseUrl,+ IsUseUrlExample: false,+ ApiKey: apiKey,+ Home: "",+ Help: "",+ Status: true,+ Sort: 100, // Default sort order, can be changed later+ Icon: "", // Default icon, can be set later+ }++ return SaveSupplierConfig(supplierName, supplier)+}++// RemoveSupplier deletes a supplier's configuration directory and all its contents.+// It checks if the supplier exists, and if so, it removes the directory and its files+// If the supplier does not exist, it returns an error indicating that the supplier cannot be found.+// This function is useful for cleaning up unused suppliers from the configuration.+func RemoveSupplier(supplierName string) error {+ supplierPath := SUPPLIER_CONFIG_PATH + "/" + supplierName+ if !public.FileExists(supplierPath) {+ return errors.New("supplier does not exist")+ }++ err := os.RemoveAll(supplierPath)+ if err != nil {+ return err+ }++ return nil+}++// SetModelTitle updates the title of a model in the supplier's models.json file.+// It reads the existing models, modifies the title of the specified model, and saves the updated list back to the file.+// If the model is not found, it returns an error indicating that the model does not exist.+func SetModelTitle(supplierName string, modelId string, title string) error {+ modelsFile := SUPPLIER_CONFIG_PATH + "/" + supplierName + "/models.json"+ if !public.FileExists(modelsFile) {+ return errors.New("models file does not exist for supplier: " + supplierName)+ }++ // Read existing models+ existingModels := GetModelList(supplierName)++ // Update the model title+ for i, model := range existingModels {+ if model.ModelId == modelId {+ existingModels[i].Title = title+ return saveModelsToFile(modelsFile, existingModels)+ }+ }++ return errors.New("model not found")+}++// SetModelCapability updates the capability of a specific model in the supplier's models.json file.+// It reads the existing models, modifies the capability of the specified model, and saves the updated list back to the file.+// If the model is not found, it returns an error indicating that the model does not exist.+func SetModelCapability(supplierName string, modelId string, capability []string) error {+ modelsFile := SUPPLIER_CONFIG_PATH + "/" + supplierName + "/models.json"+ if !public.FileExists(modelsFile) {+ return errors.New("models file does not exist for supplier: " + supplierName)+ }++ // Read existing models+ existingModels := GetModelList(supplierName)++ // Update the model capability+ for i, model := range existingModels {+ if model.ModelId == modelId {+ existingModels[i].Capability = capability+ return saveModelsToFile(modelsFile, existingModels)+ }+ }++ return errors.New("model not found")+}++// ModifyModel updates the title, maxTokens, and capability of a specific model in the supplier's models.json file.+// It reads the existing models, modifies the specified model's details, and saves the updated list back to the file.+// If the model is not found, it returns an error indicating that the model does not exist.+// This function is useful for updating model configurations without needing to remove and re-add the model.+func ModifyModel(supplierName string, modelId string, maxTokens int, capability []string, title string) error {+ modelsFile := SUPPLIER_CONFIG_PATH + "/" + supplierName + "/models.json"+ if !public.FileExists(modelsFile) {+ return errors.New("models file does not exist for supplier: " + supplierName)+ }+ // Read existing models+ existingModels := GetModelList(supplierName)++ // Update or add the model+ for i, model := range existingModels {+ if model.ModelId == modelId {+ existingModels[i].Title = title+ existingModels[i].MaxTokens = maxTokens+ existingModels[i].Capability = capability+ return saveModelsToFile(modelsFile, existingModels)+ }+ }++ return errors.New("model not found")+}diff --git a/core/internal/service/timers/timers.go b/core/internal/service/timers/timers.goindex dad2138f..43c7066b 100644--- a/core/internal/service/timers/timers.go+++ b/core/internal/service/timers/timers.go@@ -1,6 +1,7 @@package timersimport (+ "billionmail-core/internal/service/askai""billionmail-core/internal/service/batch_mail""billionmail-core/internal/service/collect""billionmail-core/internal/service/domains"@@ -9,12 +10,12 @@ import ("billionmail-core/internal/service/mail_service""billionmail-core/internal/service/maillog_stat""billionmail-core/internal/service/relay"- "billionmail-core/internal/service/settings""billionmail-core/internal/service/warmup""context"+ "time"+"github.com/gogf/gf/os/gtimer""github.com/gogf/gf/v2/frame/g"- "time")// Start Start initializes and starts all the necessary timers for the service.@@ -83,26 +84,10 @@ func Start(ctx context.Context) (err error) {})// Fix Postfix main configuration and Rspamd DKIM signing config- gtimer.AddOnce(800*time.Millisecond, func() {- g.Log().Debug(ctx, "Fixing Postfix main configuration and Rspamd DKIM signing config")-- defer func() {- g.Log().Debug(ctx, "Fixing Postfix main configuration and Rspamd DKIM signing config done")- }()-+ gtimer.AddOnce(5*time.Second, func() {mail_service.FixPostfixMainConfig(ctx)mail_service.FixRspamdDKIMSigningConfig(ctx)mail_service.FixDovecotSSLConfig(ctx)- err := relay.SyncRelayConfigsToPostfix(ctx)- if err != nil {- g.Log().Warning(ctx, "SyncRelayConfigsToPostfix failed: ", err)- err = nil- }- err = mail_service.SyncBccToPostfix(ctx)- if err != nil {- g.Log().Warning(ctx, "SyncBccToPostfix failed: ", err)- err = nil- }})// ========== Mail task processing: one executor per task ==========@@ -130,6 +115,7 @@ func Start(ctx context.Context) (err error) {})gtimer.Add(1*time.Minute, func() {+ //gtimer.Add(5*time.Second, func() {batch_mail.ProcessApiMailQueueWithLock(ctx)})@@ -142,12 +128,8 @@ func Start(ctx context.Context) (err error) {// fail2ban access logs detectiongtimer.AddOnce(800*time.Millisecond, fail2ban.NewAccessLogDetection().Start)- gtimer.AddOnce(500*time.Millisecond, func() {- settings.CheckHostname()- })- gtimer.Add(24*time.Hour, func() {- settings.CheckHostname()- })+ // askai timers+ gtimer.Add(5*time.Second, askai.AutoGetProjectInfo)g.Log().Debug(ctx, "All timers started successfully")return nil