This commit is contained in:
shaoyongjun 2024-05-20 10:19:46 +08:00
parent bef22298b7
commit 47d60ce740
5 changed files with 142 additions and 38 deletions

View File

@ -57,6 +57,8 @@ func main() {
//登录界面 //登录界面
e.GET("/", static.Login) e.GET("/", static.Login)
e.GET("/chat", static.Chat) e.GET("/chat", static.Chat)
e.GET("/chat1", static.Chat1)
e.GET("/chat2", static.Chat2)
//user //user
apps.InitUserGroup(e.Group("/v1/user/")) apps.InitUserGroup(e.Group("/v1/user/"))

View File

@ -50,14 +50,15 @@
background-color: #d6eaff; background-color: #d6eaff;
color: #000000; color: #000000;
} }
.gpt{
.gpt {
margin-bottom: 10px; margin-bottom: 10px;
justify-content: flex-start; justify-content: flex-start;
background-color: #e5ece7; background-color: #e5ece7;
color: #000; color: #000;
} }
.gpt span{ .gpt span {
white-space: pre-line; white-space: pre-line;
} }
@ -65,7 +66,7 @@
font-weight: bold; font-weight: bold;
} }
</style> </style>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script> <!-- <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>-->
</head> </head>
@ -79,7 +80,8 @@
</div> </div>
</body> </body>
<script> <script type="module">
import {marked} from "https://cdn.jsdelivr.net/npm/marked/lib/marked.esm.js";
// --------------------init-------------------------------------- // --------------------init--------------------------------------
const API_KEY = "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"; const API_KEY = "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";
const ENDPOINT = "https://openrouter.ai/api/v1/chat/completions"; const ENDPOINT = "https://openrouter.ai/api/v1/chat/completions";
@ -101,7 +103,7 @@
// 等待 // 等待
let waiting = false; let waiting = false;
// ------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------
let reg=/\\n/ig; //o为要替换的关键字不能加引号否则替换不生效i忽略大小写g表示全局查找。 let reg = /\\n/ig; //o为要替换的关键字不能加引号否则替换不生效i忽略大小写g表示全局查找。
/** /**
* 发送消息 * 发送消息
*/ */
@ -127,12 +129,13 @@
const htmlSpanElement = displayChatGPTMessageAndGetContainer(); const htmlSpanElement = displayChatGPTMessageAndGetContainer();
// 发送消息到ChatGPT // 发送消息到ChatGPT
addMessage("user", message); addMessage("user", message);
const body = JSON.stringify({model: "google/gemma-7b-it:free", messages: messages, stream: true}); const body = JSON.stringify({model: "google/gemma-7b-it:free", messages: messages, stream: false});
alert(body)
ssePost( ssePost(
// 请求地址 // 请求地址
ENDPOINT, ENDPOINT,
// 请求头 // 请求头
{"Content-Type": "application/json", Authorization: "Bearer " + API_KEY }, {"Content-Type": "application/json", Authorization: "Bearer " + API_KEY},
// params这里没有参数 // params这里没有参数
{}, {},
// body // body
@ -140,20 +143,25 @@
// 收到事件时的回调。这里将事件的data显示在htmlSpanElement中 // 收到事件时的回调。这里将事件的data显示在htmlSpanElement中
(event) => { (event) => {
const content = getContent(event.data); const content = getContent(event.data);
console.log(event.data) // console.log(event.data)
let ccc=content.toString().replace(reg,"<br/>")
console.log(ccc); if (content) {
// content.replace("world", "js"); let ccc = content.toString().replace(reg, "<br/>")
if (content) htmlSpanElement.innerHTML += ccc; console.log(ccc);
htmlSpanElement.innerHTML += ccc;
}
}, },
// 结束时的回调。1.将消息添加到历史消息中 2.将等待状态设置为false // 结束时的回调。1.将消息添加到历史消息中 2.将等待状态设置为false
() => { () => {
addMessage("assistant", htmlSpanElement.innerHTML); addMessage("assistant", htmlSpanElement.innerHTML);
htmlSpanElement.innerHTML=marked.parse(htmlSpanElement.innerHTML); htmlSpanElement.innerHTML = marked.parse(htmlSpanElement.innerHTML);
waiting = false; waiting = false;
}, },
// 发生错误时的回调 // 发生错误时的回调
(error) => {console.log(error); waiting = false} (error) => {
console.log(error);
waiting = false
}
); );
} }
@ -231,12 +239,6 @@
} }
function objectToQueryString(obj) { function objectToQueryString(obj) {
return Object.keys(obj) return Object.keys(obj)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)

View File

@ -183,28 +183,37 @@
chatlog.scrollTop = chatlog.scrollHeight; chatlog.scrollTop = chatlog.scrollHeight;
} }
// 历史消息
const messagesList = [];
// 调用api // 调用api
function chatApi(message) { function chatApi(msg) {
slideBottom(); slideBottom();
data = {
questions: message, messagesList.push({role: "user", content: msg});
history: messageHistory const body = JSON.stringify({model: "google/gemma-7b-it:free", messages: messagesList});
}; // alert(body)
$.ajax({ $.ajax({
url: "http://127.0.0.1:11434/api/chat", method: 'POST',
type: "POST", url: 'https://openrouter.ai/api/v1/chat/completions',
contentType: "application/json", headers: {
dataType: "json", 'Content-Type': 'application/json',
data: JSON.stringify(data), 'Authorization': 'Bearer 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'
},
data: body,
success: function (res) { success: function (res) {
if (res.code === 200) { let res1=res?.choices[0]?.message?.content;
let answer = res.answer; res1 = marked.parse(res1);
answer = marked.parse(answer); addAIMessage(res1);
addAIMessage(answer);
messageHistory = res.history; // if (res.code === 200) {
} else { // let answer = res.answer;
addAIMessage("服务接口调用错误。"); // answer = marked.parse(answer);
} // addAIMessage(answer);
// messageHistory = res.history;
// } else {
// addAIMessage("服务接口调用错误。");
// }
}, },
error: function (e) { error: function (e) {
addAIMessage("服务接口调用异常。"); addAIMessage("服务接口调用异常。");

77
static/ai-chat2.html Normal file
View File

@ -0,0 +1,77 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="renderer" content="webkit"/>
<meta name="force-rendering" content="webkit"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta charset="UTF-8"/>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0, viewport-fit=cover"/>
<title>智能助理</title>
<link rel="stylesheet" href="https://g.alicdn.com/chatui/sdk-v2/0.3.8/sdk.css">
</head>
<body>
<div id="root"></div>
<script src="https://g.alicdn.com/chatui/sdk-v2/0.3.8/sdk.js"></script>
<script src="https://g.alicdn.com/chatui/extensions/5.18.0/isv-parser.js"></script>
<script>
const messages = [];
var bot = new ChatSDK({
config: {
navbar: {
title: '智能助理'
},
robot: {
avatar: 'https://gw.alicdn.com/tfs/TB1U7FBiAT2gK0jSZPcXXcKkpXa-108-108.jpg'
},
// 用户头像
user: {
avatar: 'https://gw.alicdn.com/tfs/TB1DYHLwMHqK1RjSZFEXXcGMXXa-56-62.svg',
},
messages: [
{
type: 'text',
content: {
text: '智能助理为您服务,请问有什么可以帮您?'
}
}
]
},
requests: {
send: function (msg) {
// alert(msg.content.text)
messages.push({role: "user", content: msg.content.text});
const body = JSON.stringify({model: "google/gemma-7b-it:free", messages: messages});
// alert(body)
if (msg.type === 'text') {
return {
method: 'POST',
url: 'https://openrouter.ai/api/v1/chat/completions',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer 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'
},
body: body
};
}
}
},
handlers: {
parseResponse: function (res, requestType) {
// alert(requestType);
console.log(res);
if (requestType === 'send' && res?.choices?.length > 0) {
let res1=res?.choices[0]?.message?.content;
return {type: 'text', content: {text: res1}};
}
return res;
}
}
});
bot.run();
</script>
<script src="https://g.alicdn.com/chatui/icons/2.0.2/index.js" async></script>
</body>
</html>

View File

@ -19,6 +19,20 @@ func Chat(c echo.Context) error {
return c.Blob(http.StatusOK, "text/html; charset=utf-8", pageMap["ai-chat.html"]) return c.Blob(http.StatusOK, "text/html; charset=utf-8", pageMap["ai-chat.html"])
} }
func Chat1(c echo.Context) error {
c.Response().Header().Set("Content-Type", "text/html; charset=utf-8")
c.Response().Header().Set("Cache-Control", "max-age=3600")
return c.Blob(http.StatusOK, "text/html; charset=utf-8", pageMap["ai-chat1.html"])
}
func Chat2(c echo.Context) error {
c.Response().Header().Set("Content-Type", "text/html; charset=utf-8")
c.Response().Header().Set("Cache-Control", "max-age=3600")
return c.Blob(http.StatusOK, "text/html; charset=utf-8", pageMap["ai-chat2.html"])
}
func InitStaticGroup(g *echo.Group) { func InitStaticGroup(g *echo.Group) {
g.GET("login.html", func(c echo.Context) error { g.GET("login.html", func(c echo.Context) error {