DN 流程,在笔记内让 ai 根据当前笔记内容进行回复,内部 ai 回复框

注意注意,别把这个语句放在有隐私的笔记里面!!!

原有功能与实现教程:
思源笔记页面内实现 ai 聊天与 ai 读取笔记内容进行回复(自动)! - 链滴

让 ai 根据当前笔记内容进行回复

代码功能:
在创建日记的时候进行回复

在每天写完日记以后,让 ai 根据日记内容进行回复

image.png

//!js // Function to get context from recently updated documents (Keep as is) async function getDocumentContext() { try { let currentDocId = Query.root_id(protyle); const sqlQuery = ` select * from blocks where root_id = '${currentDocId}' order by sort ASC limit 9999 `; let blocks = await Query.sql(sqlQuery); if (blocks && blocks.length > 0) { let contextEntries = blocks.map(block => { const content = block.markdown || block.content || '[No Content]'; return `Document Path: ${block.hpath || 'N/A'}\nContent:\n---\n${content}\n---`; }); return "以下是当前文档的内容,请参考:\n==========\n" + contextEntries.join('\n\n') + "\n==========\n"; } else { return "当前文档没有内容可供参考。\n"; } } catch (error) { console.error("查询文档时出错:", error); return "查询参考文档时出现错误。\n"; } } // Function to create the UI elements (Keep as is) const ui = () => { const textarea = document.createElement('textarea'); textarea.className = "fn__block b3-text-field"; textarea.rows = 3; textarea.placeholder = "继续提问..."; const buttonContainer = document.createElement('div'); buttonContainer.style.display = 'flex'; buttonContainer.style.justifyContent = 'flex-end'; buttonContainer.style.gap = '8px'; buttonContainer.style.marginTop = '8px'; const removeLastButton = document.createElement('button'); removeLastButton.className = "b3-button"; removeLastButton.textContent = "我不会和别人说的🌹"; buttonContainer.appendChild(removeLastButton); const sendButton = document.createElement('button'); sendButton.className = "b3-button"; sendButton.textContent = "是这样的😄"; buttonContainer.appendChild(sendButton); return { textarea, buttonContainer, sendButton, removeLastButton }; } // Main chat function (Modified to fix null querySelector error) const chat = async () => { let dv = Query.DataView(protyle, item, top); const messages = dv.useState('messages', []); const msgIds = dv.useState('msgIds', []); // --- Initial Rendering Structure --- dv.addmd(`#### 向我分享你的一天吧!`); // 1. Render existing messages from state const initialMsgIds = []; messages().forEach(msg => { try { let el = dv.addmd(`**${msg.role === 'user' ? 'You' : 'GPT'}**: ${msg.content}`); if (el && el.dataset && el.dataset.id) { initialMsgIds.push(el.dataset.id); } } catch (e) { console.error("Error rendering message:", e); } }); if (msgIds().length === 0 && initialMsgIds.length > 0) { msgIds(initialMsgIds); } // 2. Add Separator dv.addmd('---'); // 3. Create UI Elements but don't store unnecessary references const { textarea, buttonContainer, sendButton, removeLastButton } = ui(); // Just add them directly without storing the references dv.addele(textarea); dv.addele(buttonContainer); // --- Function to perform AI query (Modified with better error handling) --- const performAIQuery = async (prompt, isInitialQuery = false) => { try { sendButton.disabled = true; removeLastButton.disabled = true; // Add placeholder with better error handling let respondPlaceholder; let gptMsgId = null; try { respondPlaceholder = dv.addmd(`**GPT**: 正在检索参考资料并思考... 🤔`); if (respondPlaceholder && respondPlaceholder.dataset) { gptMsgId = respondPlaceholder.dataset.id; // Add placeholder ID to state only if it's valid if (gptMsgId) { msgIds([...msgIds(), gptMsgId]); } } } catch (e) { console.error("Error adding placeholder:", e); // If we can't add a placeholder, we'll just add a new message later } // Safe function to replace or add content const updateContent = (id, content) => { try { if (id) { dv.replaceView(id, dv.md(`**GPT**: ${content}`)); } else { // If no ID, add as new message let newEl = dv.addmd(`**GPT**: ${content}`); if (newEl && newEl.dataset && newEl.dataset.id) { msgIds([...msgIds(), newEl.dataset.id]); } } } catch (e) { console.error("Error updating content:", e); // Last resort fallback - just add a new message try { dv.addmd(`**GPT**: ${content}`); } catch (e) { console.error("Failed to add fallback message:", e); } } }; const docReference = await getDocumentContext(); const prefixText = `${docReference}\n这是我的提问背景信息:`; const suffixText = "\n请基于以上参考信息,回复我的问题。注意:多用表情,尽量简短且切中要点。"; const fullPrompt = `${prefixText}\n${prompt}\n${suffixText}`; const response = await Query.gpt(fullPrompt, { stream: true, streamInterval: 3, streamMsg: (content) => { // Safely update with streaming content updateContent(gptMsgId, content); } }); // Update state with final response const gptMessage = { role: 'assistant', content: response }; const currentMessages = messages(); if (isInitialQuery) { messages([gptMessage]); } else { messages([...currentMessages, gptMessage]); } // Final update with safe function updateContent(gptMsgId, response); } catch (error) { console.error("GPT 调用或处理失败:", error); const errorMessageContent = `抱歉,处理时遇到问题: ${error.message}`; try { if (gptMsgId) { dv.replaceView(gptMsgId, dv.md(`**GPT**: ${errorMessageContent}`)); } else { dv.addmd(`**GPT**: ${errorMessageContent}`); } const errorMessage = { role: 'assistant', content: errorMessageContent }; const currentMessages = messages(); if (isInitialQuery) { messages([errorMessage]); } else { messages([...currentMessages, errorMessage]); } } catch (e) { console.error("Error handling GPT failure:", e); // Try one more time with a simple message try { dv.addmd(`**Error**: ${error.message}`); } catch (finalError) { console.error("Failed all error handling attempts:", finalError); } } } finally { // Re-enable buttons regardless of outcome try { sendButton.disabled = false; removeLastButton.disabled = false; // Safely repaint dv.repaint(); } catch (e) { console.error("Error in finally block:", e); } } }; // --- Initial Query Logic --- if (messages().length === 0) { const predefinedPrompt = "今天真是美好的一天,请你基于参考内容,激励我度过美好的一天吧!请你用满满的正能量激励我,并且要加入很多的表情,让我的心情愉快!"; try { await performAIQuery(predefinedPrompt, true); } catch (e) { console.error("Initial query failed:", e); // Try to add a fallback message dv.addmd("**System**: 初始查询失败,但你仍然可以开始对话。"); } } // --- Button Handlers --- sendButton.onclick = async () => { const userInput = textarea.value.trim(); if (!userInput) return; // 1. Add user message to state and UI with better error handling const userMessage = { role: 'user', content: userInput }; messages([...messages(), userMessage]); let userEl; let userMsgId = null; try { userEl = dv.addmd(`**You**: ${userInput}`); if (userEl && userEl.dataset) { userMsgId = userEl.dataset.id; if (userMsgId) { msgIds([...msgIds(), userMsgId]); } } } catch (e) { console.error("Error adding user message:", e); } textarea.value = ''; // 2. Perform AI query with error handling try { await performAIQuery(userInput, false); } catch (e) { console.error("Query failed:", e); dv.addmd(`**System**: 查询失败,请重试。错误: ${e.message}`); } }; // Remove last button click handler (with better error handling) removeLastButton.onclick = () => { try { const currentMessages = messages(); let currentMsgIds = [...msgIds()]; if (currentMessages.length < 2 || currentMsgIds.length < 2) return; // Update messages state first (in case view operations fail) messages(currentMessages.slice(0, -2)); // Then try to remove the views try { const lastGptId = currentMsgIds.pop(); const lastUserId = currentMsgIds.pop(); if (lastGptId) dv.removeView(lastGptId); if (lastUserId) dv.removeView(lastUserId); // Update msgIds state only after successful removal msgIds(currentMsgIds); } catch (e) { console.error("Error removing views:", e); } // Always try to repaint dv.repaint(); } catch (e) { console.error("Error in removeLastButton handler:", e); } }; // --- Final Render --- try { dv.render(); } catch (e) { console.error("Error rendering DataView:", e); } } // Execute the chat function with error handling try { return chat(); } catch (e) { console.error("Fatal error in chat function:", e); return "Error initializing chat. Please check console for details."; }
  • 思源笔记

    思源笔记是一款隐私优先的个人知识管理系统,支持完全离线使用,同时也支持端到端加密同步。

    融合块、大纲和双向链接,重构你的思维。

    26197 引用 • 108848 回帖 • 2 关注
1 操作
TangQi 在 2025-04-20 21:14:41 更新了该帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...

推荐标签 标签

  • Latke

    Latke 是一款以 JSON 为主的 Java Web 框架。

    71 引用 • 535 回帖 • 827 关注
  • Windows

    Microsoft Windows 是美国微软公司研发的一套操作系统,它问世于 1985 年,起初仅仅是 Microsoft-DOS 模拟环境,后续的系统版本由于微软不断的更新升级,不但易用,也慢慢的成为家家户户人们最喜爱的操作系统。

    229 引用 • 476 回帖 • 1 关注
  • Postman

    Postman 是一款简单好用的 HTTP API 调试工具。

    4 引用 • 3 回帖 • 2 关注
  • Logseq

    Logseq 是一个隐私优先、开源的知识库工具。

    Logseq is a joyful, open-source outliner that works on top of local plain-text Markdown and Org-mode files. Use it to write, organize and share your thoughts, keep your to-do list, and build your own digital garden.

    7 引用 • 69 回帖 • 8 关注
  • Sublime

    Sublime Text 是一款可以用来写代码、写文章的文本编辑器。支持代码高亮、自动完成,还支持通过插件进行扩展。

    10 引用 • 5 回帖 • 2 关注
  • 链滴

    链滴是一个记录生活的地方。

    记录生活,连接点滴

    181 引用 • 3880 回帖
  • 区块链

    区块链是分布式数据存储、点对点传输、共识机制、加密算法等计算机技术的新型应用模式。所谓共识机制是区块链系统中实现不同节点之间建立信任、获取权益的数学算法 。

    92 引用 • 752 回帖 • 3 关注
  • RESTful

    一种软件架构设计风格而不是标准,提供了一组设计原则和约束条件,主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

    30 引用 • 114 回帖 • 3 关注
  • jsDelivr

    jsDelivr 是一个开源的 CDN 服务,可为 npm 包、GitHub 仓库提供免费、快速并且可靠的全球 CDN 加速服务。

    5 引用 • 31 回帖 • 109 关注
  • 微信

    腾讯公司 2011 年 1 月 21 日推出的一款手机通讯软件。用户可以通过摇一摇、搜索号码、扫描二维码等添加好友和关注公众平台,同时可以将自己看到的精彩内容分享到微信朋友圈。

    133 引用 • 796 回帖 • 2 关注
  • Maven

    Maven 是基于项目对象模型(POM)、通过一小段描述信息来管理项目的构建、报告和文档的软件项目管理工具。

    188 引用 • 319 回帖 • 240 关注
  • 新人

    让我们欢迎这对新人。哦,不好意思说错了,让我们欢迎这位新人!
    新手上路,请谨慎驾驶!

    52 引用 • 228 回帖
  • 禅道

    禅道是一款国产的开源项目管理软件,她的核心管理思想基于敏捷方法 scrum,内置了产品管理和项目管理,同时又根据国内研发现状补充了测试管理、计划管理、发布管理、文档管理、事务管理等功能,在一个软件中就可以将软件研发中的需求、任务、bug、用例、计划、发布等要素有序的跟踪管理起来,完整地覆盖了项目管理的核心流程。

    10 引用 • 15 回帖 • 2 关注
  • 酷鸟浏览器

    安全 · 稳定 · 快速
    为跨境从业人员提供专业的跨境浏览器

    3 引用 • 59 回帖 • 51 关注
  • 996
    13 引用 • 200 回帖 • 2 关注
  • Follow
    4 引用 • 12 回帖 • 2 关注
  • C

    C 语言是一门通用计算机编程语言,应用广泛。C 语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。

    86 引用 • 165 回帖 • 2 关注
  • Laravel

    Laravel 是一套简洁、优雅的 PHP Web 开发框架。它采用 MVC 设计,是一款崇尚开发效率的全栈框架。

    19 引用 • 23 回帖 • 738 关注
  • FFmpeg

    FFmpeg 是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。

    23 引用 • 32 回帖 • 2 关注
  • uTools

    uTools 是一个极简、插件化、跨平台的现代桌面软件。通过自由选配丰富的插件,打造你得心应手的工具集合。

    7 引用 • 28 回帖
  • Wide

    Wide 是一款基于 Web 的 Go 语言 IDE。通过浏览器就可以进行 Go 开发,并有代码自动完成、查看表达式、编译反馈、Lint、实时结果输出等功能。

    欢迎访问我们运维的实例: https://wide.b3log.org

    30 引用 • 218 回帖 • 642 关注
  • Ant-Design

    Ant Design 是服务于企业级产品的设计体系,基于确定和自然的设计价值观上的模块化解决方案,让设计者和开发者专注于更好的用户体验。

    17 引用 • 23 回帖 • 5 关注
  • 印象笔记
    3 引用 • 16 回帖 • 1 关注
  • Rust

    Rust 是一门赋予每个人构建可靠且高效软件能力的语言。Rust 由 Mozilla 开发,最早发布于 2014 年 9 月。

    59 引用 • 22 回帖 • 9 关注
  • Swagger

    Swagger 是一款非常流行的 API 开发工具,它遵循 OpenAPI Specification(这是一种通用的、和编程语言无关的 API 描述规范)。Swagger 贯穿整个 API 生命周期,如 API 的设计、编写文档、测试和部署。

    26 引用 • 35 回帖 • 2 关注
  • 游戏

    沉迷游戏伤身,强撸灰飞烟灭。

    187 引用 • 831 回帖
  • 友情链接

    确认过眼神后的灵魂连接,站在链在!

    24 引用 • 373 回帖