Compare commits

...

2 Commits

3 changed files with 180 additions and 20 deletions

View File

@@ -5,7 +5,10 @@ const CONFIG = {
apiUrl: 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
apiKey: '2259e33a1357460abe17919aaf81e73d.K44a8LPQTmFM5PKm',
model: 'glm-4.5-air',
maxTokens: 2048
maxTokens: 2048,
// Tavily Search API
tavilyApiUrl: 'https://api.tavily.com/search',
tavilyApiKey: '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'
};
// 数据结构
@@ -584,11 +587,6 @@ function openConversation(id) {
thinkingBtn.addEventListener('click', () => {
enableThinking = !enableThinking;
thinkingBtn.classList.toggle('active', enableThinking);
// 如果开启深度思考,关闭联网搜索(智谱思考模型不支持联网)
if (enableThinking && enableSearch) {
enableSearch = false;
searchBtn.classList.remove('active');
}
});
}
@@ -596,11 +594,6 @@ function openConversation(id) {
searchBtn.addEventListener('click', () => {
enableSearch = !enableSearch;
searchBtn.classList.toggle('active', enableSearch);
// 如果开启联网搜索,关闭深度思考
if (enableSearch && enableThinking) {
enableThinking = false;
thinkingBtn.classList.remove('active');
}
});
}
@@ -760,12 +753,20 @@ async function streamGenerate(userMsgIndex) {
sendBtn.disabled = true;
const aiMessageIndex = currentConversation.messages.length;
const userMessage = currentConversation.messages[userMsgIndex];
// 只有开启深度思考时才添加 thinking 字段
// 如果开启联网搜索,先执行搜索
let searchResults = null;
if (enableSearch && userMessage.role === 'user') {
searchResults = await performSearch(userMessage.content);
}
// 只有开启深度思考时才添加 thinking 字段,开启搜索时添加 search_results 字段
currentConversation.messages.push({
role: 'assistant',
content: '',
...(enableThinking ? { thinking: '' } : {})
...(enableThinking ? { thinking: '' } : {}),
...(searchResults ? { search_results: searchResults } : {})
});
renderMessages();
@@ -786,13 +787,25 @@ async function streamGenerate(userMsgIndex) {
showStopGenerateBtn();
try {
// 构建消息数组
let messagesToSend = currentConversation.messages.slice(0, aiMessageIndex).map(m => ({
role: m.role,
content: m.content
}));
// 如果有搜索结果,将搜索内容添加到消息中
if (searchResults) {
const searchContext = formatSearchResultsForLLM(searchResults);
messagesToSend.push({
role: 'system',
content: `以下是搜索结果,请根据这些信息回答用户问题:\n\n${searchContext}`
});
}
// 构建请求体 - 统一使用 glm-4.5-air通过 thinking 参数控制
const requestBody = {
model: CONFIG.model,
messages: currentConversation.messages.slice(0, aiMessageIndex).map(m => ({
role: m.role,
content: m.content
})),
messages: messagesToSend,
max_tokens: CONFIG.maxTokens,
stream: true,
thinking: {
@@ -915,6 +928,44 @@ async function streamGenerate(userMsgIndex) {
}
}
// 执行 Tavily 搜索
async function performSearch(query) {
try {
const response = await fetch(CONFIG.tavilyApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${CONFIG.tavilyApiKey}`
},
body: JSON.stringify({
query: query,
max_results: 10,
include_raw_content: false
})
});
if (!response.ok) {
console.error('搜索失败:', response.status);
return null;
}
const data = await response.json();
return data.results || [];
} catch (error) {
console.error('搜索错误:', error);
return null;
}
}
// 格式化搜索结果给 LLM
function formatSearchResultsForLLM(results) {
if (!results || results.length === 0) return '无搜索结果';
return results.map((r, i) =>
`${i + 1}. 【${r.title}\n来源: ${r.url}\n摘要: ${r.content || '无摘要'}\n`
).join('\n');
}
// 显示停止生成按钮
function showStopGenerateBtn() {
// 检查是否已存在
@@ -1121,6 +1172,27 @@ function renderMessages() {
</div>`;
}
// 搜索结果块仅AI消息放在思考块前面
let searchHtml = '';
if (!isUser && msg.search_results && msg.search_results.length > 0) {
searchHtml = `
<div class="search-results-block" onclick="toggleSearchResults(this)">
<div class="search-results-header">
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 7 9.5 7 14 9.01 14 9.5 11.99 14 9.5 14z"/></svg>
<span>搜索结果 (${msg.search_results.length})</span>
<svg class="search-results-arrow" viewBox="0 0 24 24" width="14" height="14"><path fill="currentColor" d="M7 10l5 5 5-5z"/></svg>
</div>
<div class="search-results-content">
${msg.search_results.map((r, i) => `
<div class="search-result-link">
<span class="search-result-num">${i + 1}</span>
<a href="${r.url}" target="_blank" rel="noopener">${escapeHtml(r.title)}</a>
</div>
`).join('')}
</div>
</div>`;
}
const copyIcon = `<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>`;
const actions = isUser
@@ -1144,6 +1216,7 @@ function renderMessages() {
<div class="message ${msg.role}" data-index="${index}">
<div class="message-avatar">${avatar}</div>
<div class="message-body">
${searchHtml}
${thinkingHtml}
<div class="message-content">${contentHtml}</div>
${actions}
@@ -1171,6 +1244,11 @@ function toggleThinking(block) {
block.classList.toggle('expanded');
}
// 折叠/展开搜索结果
function toggleSearchResults(block) {
block.classList.toggle('expanded');
}
// ==================== 工具函数 ====================
// 渲染 Markdown

View File

@@ -8,12 +8,12 @@
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<title>AI助手</title>
<link rel="stylesheet" href="style.css?v=2.6.0">
<link rel="stylesheet" href="style.css?v=2.7.1">
<link rel="manifest" href="manifest.json">
</head>
<body>
<div id="app"></div>
<script src="marked.min.js?v=2.6.0"></script>
<script src="app.js?v=2.6.0"></script>
<script src="marked.min.js?v=2.7.1"></script>
<script src="app.js?v=2.7.1"></script>
</body>
</html>

View File

@@ -897,6 +897,88 @@ body {
margin: 8px 0;
}
/* 搜索结果块 */
.search-results-block {
margin-bottom: 12px;
background: rgba(102, 126, 234, 0.05);
border: 1px solid rgba(102, 126, 234, 0.15);
border-radius: 10px;
overflow: hidden;
cursor: pointer;
transition: all 0.2s;
}
.search-results-block:hover {
border-color: rgba(102, 126, 234, 0.3);
}
.search-results-header {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 12px;
background: rgba(102, 126, 234, 0.1);
font-size: 13px;
color: var(--primary);
font-weight: 500;
}
.search-results-header svg:first-child {
color: var(--primary);
}
.search-results-arrow {
margin-left: auto;
transition: transform 0.2s;
}
.search-results-block.expanded .search-results-arrow {
transform: rotate(180deg);
}
.search-results-content {
padding: 0 12px;
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease, padding 0.3s ease;
}
.search-results-block.expanded .search-results-content {
padding: 8px 12px;
max-height: 300px;
}
.search-result-link {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 0;
}
.search-result-num {
display: flex;
align-items: center;
justify-content: center;
min-width: 20px;
height: 20px;
background: var(--primary);
color: white;
border-radius: 50%;
font-size: 12px;
font-weight: 500;
}
.search-result-link a {
color: var(--text-color);
font-size: 14px;
text-decoration: none;
transition: color 0.2s;
}
.search-result-link a:hover {
color: var(--primary);
}
/* 输入区域 */
.input-area {
display: flex;