[Feature] Implement shared-prompt-renderer with advanced template features#569
Conversation
Add optional chaining for model name retrieval and validation to prevent runtime errors when defaultModel is undefined. This ensures proper handling of edge cases where model selection may fail. Changes: - Add optional chaining to toModelName() calls in rooms.ts - Add null check for defaultModel in room configuration validation - Improve defaultModel string validation with safe length check
- Corrected directory and homepage fields in multiple adapter package.json files to match the actual package names. - Renamed plugin packages to extension packages and updated related paths. - Fixed dependency version specifier in adapter-rwkv package.json. - Updated repository directory and homepage URL for consistency across packages.
…ssing - Introduce a new tokenizer to parse prompt templates with variables and functions - Support escaped braces, nested structures, and quoted strings with escape sequences - Add basic ChatLunaPromptRenderer class structure - Fix file paths in README files to point to correct resource locations - Move processDynamicImport script into scripts directory - Rename screenshots and logo.png to reside under resources directory - Add critical note about using backslashes for file paths on Windows systems
…ystem
- Implement AST-based expression parser supporting:
- Variable interpolation with member access (obj.prop)
- Array indexing (arr[0])
- Function calls with arguments
- Operators (arithmetic, comparison, logical, unary)
- Conditional expressions (ternary operator)
- Add control flow structures:
- if/else conditional blocks
- for loops for array iteration
- Implement evaluator with async support
- Add LRU caching for tokenization (1000 entries)
- Create comprehensive documentation with migration guide
- Export public API from index.ts
BREAKING CHANGE: Old syntax {func:arg1::arg2} is no longer supported. Use new syntax {func(arg1, arg2)} instead.
Replace custom tokenization and variable service with @chatluna/shared-prompt-renderer package. This migration consolidates template rendering logic into a dedicated shared package and removes deprecated TXT preset format support. - Replace ChatLunaVariableService with ChatLunaPromptRenderService - Update all chain and prompt classes to use new renderer service - Remove deprecated tokenize.ts and TXT preset loader - Add @chatluna/shared-prompt-renderer dependency - Update method calls to match new renderer API (formatPresetTemplate -> renderPresetTemplate, formatMessages -> renderMessages, formatPresetTemplateString -> renderTemplate) - Update variable service references across chat chains and middlewares
…amic function calls - Add while loop support with boolean condition evaluation - Add repeat loop for count-based iteration - Add elseif branches to if statements for multi-level conditionals - Support calling functions as variables (auto-invocation without parens) - Support expression-based function calls with property chain access - Add safety limits: while loop max 10000 iterations - Update README with comprehensive examples for new features
Use conversationId from configurable context for todos generation and retrieval to ensure todos are properly associated with conversations instead of generating random IDs. This provides better context tracking and persistence.
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. Walkthrough该 PR 将 VariableService 架构迁移为 PromptRenderService:新增并暴露 ChatLunaPromptRenderService,替换并移除原 VariableService 及 tokenizer、TXT 预设回退;并对链、服务、room 中间件与扩展工具等处做相应适配与空安全修正,同时更新若干文档和资源路径(logo 与新增 CLAUDE.MD)。 Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant User as 用户
participant App as ChatLunaService
participant PR as PromptRenderService
participant CP as ChatLunaChatPrompt
participant LLM as LLM
User->>App: 发起对话请求
App->>CP: 构建 ChatLunaChatPrompt (传入 promptRenderService)
CP->>PR: renderPresetTemplate / renderMessages (configurable: { session })
Note right of PR #f6f8fa: 渲染变量与函数提供者\n生成 BaseMessage 列表
PR-->>CP: 返回渲染后的消息集合
CP->>LLM: 发送消息序列
LLM-->>User: 返回模型响应
Note over App,PR: 已移除 VariableService 与 tokenize 相关实现
sequenceDiagram
autonumber
participant MW as check_room 中间件
participant Rooms as leaveConversationRoom
participant DB as 数据存储/房间组
participant User as 用户
MW->>MW: 检查用户是否在目标房间
alt 用户不在房间
MW->>Rooms: 尝试调用 leaveConversationRoom (try/catch)
Rooms->>DB: 移除 defaultRoomId 与 groupId(若适用)
Rooms-->>MW: 返回(错误被吞掉)
MW-->>User: 返回“不在房间”并结束处理
else 用户已在房间
MW-->>User: 继续处理
end
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
🔇 Additional comments (4)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Summary of ChangesHello @dingyi222666, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly upgrades the project's templating capabilities by introducing a powerful new shared prompt renderer with extensive features, integrating it deeply into the core. Alongside this major feature, the project structure has been thoroughly reorganized through consistent package renaming, improving maintainability and clarity. Several bug fixes and minor enhancements are also included to bolster stability and functionality. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces a significant and well-executed refactoring. The core of the changes is the implementation of the new shared-prompt-renderer package and its integration throughout the codebase, replacing the legacy VariableService and tokenizer. This is a great improvement, offering more powerful and flexible templating capabilities.
The extensive renaming and restructuring of packages (adapter-*, extension-*, service-*, renderer-*) brings better organization and clarity to the project structure. I appreciate the consistency in updating all related package.json files and paths.
Additionally, the PR includes valuable improvements like enhanced null-safety checks in packages/core/src/chains/rooms.ts and better context association for the todos tool by using conversationId.
I've found a couple of minor issues in the documentation files, which I've commented on. Overall, this is an excellent contribution that modernizes the prompt system and improves the project's architecture.
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (6)
packages/core/src/middlewares/room/check_room.ts (1)
41-46: 建议添加错误日志。虽然在检测到用户不在房间时尝试清理房间成员关系是个好的实践,但当前实现完全忽略了所有错误。建议至少记录错误日志以便调试。
应用以下修改添加错误日志:
// 可能进行退出房间 try { await leaveConversationRoom(ctx, session, room) } catch (e) { - // 忽略 + // 清理失败时记录日志但不中断流程 + logger.debug(`Failed to leave room ${room.roomId}: ${e.message}`) }packages/core/src/llm-core/chain/plugin_chat_chain.ts (1)
37-37: 考虑重命名属性以保持一致性。接口和类属性仍命名为
variableService,但在构造 ChatLunaChatPrompt 时传递的键名为promptRenderService(第 107 行)。这种命名不一致可能导致混淆。建议重命名属性以与传递的键名保持一致:
export interface ChatLunaPluginChainInput { prompt: ChatLunaChatPrompt historyMemory: BufferMemory embeddings: ChatLunaBaseEmbeddings agentMode?: 'tool-calling' | 'react' - variableService: ChatLunaPromptRenderService + promptRenderService: ChatLunaPromptRenderService preset: () => Promise<PresetTemplate> }并在类定义中做相应修改:
- variableService: ChatLunaPromptRenderService + promptRenderService: ChatLunaPromptRenderServiceAlso applies to: 61-61
packages/core/src/services/prompt_renderer.ts (2)
106-122: 消除重复的函数实现。
url和fetch函数提供者的实现完全相同(第 106-113 行和第 115-122 行),这是不必要的代码重复。可以让一个函数复用另一个:
this.registerFunctionProvider('url', async (args) => { return await fetchUrl( args[1], args[0], args[2], parseInt(args[3] ?? '1000') ) }) - this.registerFunctionProvider('fetch', async (args) => { - return await fetchUrl( - args[1], - args[0], - args[2], - parseInt(args[3] ?? '1000') - ) - }) + this.registerFunctionProvider('fetch', async (args) => { + // 'fetch' 是 'url' 的别名,复用相同实现 + const urlProvider = this._renderer['_functionProviders']['url'] + return await urlProvider(args, {}) + })或者将实现提取为私有方法:
+ private async _handleFetchUrl(args: string[]) { + return await fetchUrl( + args[1], + args[0], + args[2], + parseInt(args[3] ?? '1000') + ) + } - this.registerFunctionProvider('url', async (args) => { - return await fetchUrl( - args[1], - args[0], - args[2], - parseInt(args[3] ?? '1000') - ) - }) + this.registerFunctionProvider('url', async (args) => { + return await this._handleFetchUrl(args) + }) - this.registerFunctionProvider('fetch', async (args) => { - return await fetchUrl( - args[1], - args[0], - args[2], - parseInt(args[3] ?? '1000') - ) - }) + this.registerFunctionProvider('fetch', async (args) => { + return await this._handleFetchUrl(args) + })
106-122: 考虑添加错误处理。
url和fetch函数提供者调用的fetchUrl函数可能抛出网络错误或其他异常。当前实现没有错误处理,可能导致模板渲染失败时错误信息不明确。建议添加 try-catch 处理:
this.registerFunctionProvider('url', async (args) => { + try { return await fetchUrl( args[1], args[0], args[2], parseInt(args[3] ?? '1000') ) + } catch (error) { + logger.warn(`Failed to fetch URL: ${error.message}`) + return '[URL fetch failed]' + } }) this.registerFunctionProvider('fetch', async (args) => { + try { return await fetchUrl( args[1], args[0], args[2], parseInt(args[3] ?? '1000') ) + } catch (error) { + logger.warn(`Failed to fetch: ${error.message}`) + return '[Fetch failed]' + } })packages/core/src/llm-core/chain/chat_chain.ts (2)
24-24: 建议重命名属性以提高代码清晰度。属性名仍为
variableService,但类型已更改为ChatLunaPromptRenderService。这种命名不一致可能会让开发者困惑,建议将属性重命名为promptRenderService以与其类型保持一致。应用以下差异以重命名属性:
export interface ChatLunaChatChainInput { botName: string preset: () => Promise<PresetTemplate> humanMessagePrompt?: string historyMemory: BufferMemory - variableService: ChatLunaPromptRenderService + promptRenderService: ChatLunaPromptRenderService }export class ChatLunaChatChain extends ChatLunaLLMChainWrapper implements ChatLunaChatChainInput { botName: string chain: ChatLunaLLMChain historyMemory: BufferMemory preset: () => Promise<PresetTemplate> - variableService: ChatLunaPromptRenderService + promptRenderService: ChatLunaPromptRenderService注意:此重构需要同步更新构造函数和所有调用方。
Also applies to: 39-39
41-56: 构造函数参数命名与类型不匹配。构造函数参数仍命名为
variableService,但其类型为ChatLunaPromptRenderService。如果采纳上述重命名建议,此处也需要相应更新。应用以下差异以更新构造函数参数名:
constructor({ botName, historyMemory, preset, chain, - variableService + promptRenderService }: ChatLunaChatChainInput & { chain: ChatLunaLLMChain }) { super() this.botName = botName this.historyMemory = historyMemory this.preset = preset - this.variableService = variableService + this.promptRenderService = promptRenderService this.chain = chain }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (99)
.claude/settings.local.jsonis excluded by!**/*.jsonpackage.jsonis excluded by!**/*.jsonpackages/adapter-azure-openai/package.jsonis excluded by!**/*.jsonpackages/adapter-azure-openai/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-azure-openai/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-azure-openai/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-claude/package.jsonis excluded by!**/*.jsonpackages/adapter-claude/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-claude/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-claude/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-deepseek/package.jsonis excluded by!**/*.jsonpackages/adapter-deepseek/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-deepseek/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-deepseek/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-dify/package.jsonis excluded by!**/*.jsonpackages/adapter-dify/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-dify/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-dify/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-doubao/package.jsonis excluded by!**/*.jsonpackages/adapter-doubao/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-doubao/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-doubao/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-gemini/package.jsonis excluded by!**/*.jsonpackages/adapter-gemini/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-gemini/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-gemini/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-hunyuan/package.jsonis excluded by!**/*.jsonpackages/adapter-hunyuan/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-hunyuan/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-hunyuan/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-ollama/package.jsonis excluded by!**/*.jsonpackages/adapter-ollama/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-ollama/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-ollama/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-openai-like/package.jsonis excluded by!**/*.jsonpackages/adapter-openai-like/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-openai-like/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-openai-like/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-openai/package.jsonis excluded by!**/*.jsonpackages/adapter-openai/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-openai/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-openai/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-qwen/package.jsonis excluded by!**/*.jsonpackages/adapter-qwen/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-qwen/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-qwen/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-rwkv/package.jsonis excluded by!**/*.jsonpackages/adapter-rwkv/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-rwkv/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-rwkv/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-spark/package.jsonis excluded by!**/*.jsonpackages/adapter-spark/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-spark/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-spark/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-wenxin/package.jsonis excluded by!**/*.jsonpackages/adapter-wenxin/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-wenxin/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-wenxin/tsconfig.jsonis excluded by!**/*.jsonpackages/adapter-zhipu/package.jsonis excluded by!**/*.jsonpackages/adapter-zhipu/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/adapter-zhipu/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/adapter-zhipu/tsconfig.jsonis excluded by!**/*.jsonpackages/core/package.jsonis excluded by!**/*.jsonpackages/extension-long-memory/memory.pdfis excluded by!**/*.pdf,!**/*.pdfpackages/extension-long-memory/package.jsonis excluded by!**/*.jsonpackages/extension-long-memory/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/extension-long-memory/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/extension-long-memory/tsconfig.jsonis excluded by!**/*.jsonpackages/extension-mcp/package.jsonis excluded by!**/*.jsonpackages/extension-mcp/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/extension-mcp/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/extension-mcp/tsconfig.jsonis excluded by!**/*.jsonpackages/extension-tools/package.jsonis excluded by!**/*.jsonpackages/extension-tools/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/extension-tools/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/extension-tools/tsconfig.jsonis excluded by!**/*.jsonpackages/extension-variable/package.jsonis excluded by!**/*.jsonpackages/extension-variable/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/extension-variable/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/extension-variable/tsconfig.jsonis excluded by!**/*.jsonpackages/renderer-image/package.jsonis excluded by!**/*.jsonpackages/renderer-image/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/renderer-image/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/renderer-image/tsconfig.jsonis excluded by!**/*.jsonpackages/service-embeddings/package.jsonis excluded by!**/*.jsonpackages/service-embeddings/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/service-embeddings/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/service-embeddings/tsconfig.jsonis excluded by!**/*.jsonpackages/service-image/package.jsonis excluded by!**/*.jsonpackages/service-image/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/service-image/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/service-image/tsconfig.jsonis excluded by!**/*.jsonpackages/service-search/package.jsonis excluded by!**/*.jsonpackages/service-search/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/service-search/src/locales/zh-CN.schema.ymlis excluded by!**/*.ymlpackages/service-search/tsconfig.jsonis excluded by!**/*.jsonpackages/service-vector-store/package.jsonis excluded by!**/*.jsonpackages/service-vector-store/src/locales/en-US.schema.ymlis excluded by!**/*.ymlpackages/service-vector-store/src/locales/zh-CN.schema.ymlis excluded by!**/*.yml
📒 Files selected for processing (19)
CLAUDE.MD(1 hunks)README.MD(1 hunks)README_EN.MD(1 hunks)README_JP.MD(1 hunks)packages/core/src/chains/rooms.ts(4 hunks)packages/core/src/llm-core/chain/chat_chain.ts(4 hunks)packages/core/src/llm-core/chain/plugin_chat_chain.ts(4 hunks)packages/core/src/llm-core/chain/prompt.ts(8 hunks)packages/core/src/llm-core/chat/default.ts(2 hunks)packages/core/src/llm-core/prompt/preset_prompt_parse.ts(1 hunks)packages/core/src/llm-core/prompt/tokenize.ts(0 hunks)packages/core/src/middlewares/model/request_model.ts(2 hunks)packages/core/src/middlewares/room/check_room.ts(2 hunks)packages/core/src/middlewares/room/resolve_room.ts(1 hunks)packages/core/src/services/chat.ts(5 hunks)packages/core/src/services/prompt_renderer.ts(1 hunks)packages/core/src/services/variable.ts(0 hunks)packages/core/src/utils/string.ts(2 hunks)packages/extension-tools/src/plugins/todos.ts(1 hunks)
💤 Files with no reviewable changes (2)
- packages/core/src/llm-core/prompt/tokenize.ts
- packages/core/src/services/variable.ts
🧰 Additional context used
🧬 Code graph analysis (7)
packages/core/src/middlewares/room/resolve_room.ts (1)
packages/core/src/llm-core/platform/client.ts (1)
config(91-93)
packages/core/src/llm-core/chain/chat_chain.ts (1)
packages/core/src/services/prompt_renderer.ts (1)
ChatLunaPromptRenderService(25-223)
packages/core/src/services/prompt_renderer.ts (4)
packages/shared-prompt-renderer/src/renderer.ts (1)
ChatLunaPromptRenderer(9-86)packages/core/src/utils/string.ts (5)
getTimeDiff(150-155)selectFromList(157-164)rollDice(166-182)fetchUrl(184-199)getMessageContent(91-107)packages/shared-prompt-renderer/src/types.ts (3)
FunctionProvider(4-7)VariableProvider(2-2)RenderResult(22-25)packages/core/src/llm-core/prompt/type.ts (1)
PresetTemplate(80-110)
packages/core/src/services/chat.ts (1)
packages/core/src/services/prompt_renderer.ts (1)
ChatLunaPromptRenderService(25-223)
packages/core/src/llm-core/chain/plugin_chat_chain.ts (1)
packages/core/src/services/prompt_renderer.ts (1)
ChatLunaPromptRenderService(25-223)
packages/core/src/middlewares/room/check_room.ts (1)
packages/core/src/chains/rooms.ts (1)
leaveConversationRoom(448-470)
packages/core/src/llm-core/chain/prompt.ts (5)
packages/core/src/services/prompt_renderer.ts (1)
ChatLunaPromptRenderService(25-223)packages/core/src/llm-core/prompt/type.ts (1)
PresetTemplate(80-110)packages/core/src/llm-core/chain/base.ts (1)
SystemPrompts(27-27)packages/core/src/services/chat.ts (1)
preset(323-325)packages/core/src/llm-core/chat/app.ts (1)
preset(344-346)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: lint
- GitHub Check: build
🔇 Additional comments (14)
packages/extension-tools/src/plugins/todos.ts (3)
106-115: LGTM! 一致的 conversationId 回退逻辑不同操作对 conversationId 的使用是合理的:
- 'generate' 操作: 直接传递
conversationId(在函数内部回退到generateId())- 'set'/'get' 操作: 使用
conversationId || id回退到用户提供的 ID这种设计确保了:
- 生成新待办事项时优先使用 conversationId,无则生成新 ID
- 访问现有待办事项时优先使用 conversationId,无则使用用户提供的 ID
- 运行时验证(第 176、216 行)会捕获未定义的 ID
130-130: LGTM! 合理的回退机制使用
conversationId || generateId()确保了在 conversationId 不可用时生成新的待办事项 ID。这与第 156 行将生成的 ID 发送给用户的逻辑配合良好,用户可以在后续操作中使用该 ID。
102-102: 确认 conversationId 可选类型
请在ChatLunaToolRunnable的configurable中验证conversationId是否声明为string | undefined,以确保类型签名与使用的可选逻辑一致。packages/core/src/utils/string.ts (1)
379-399: LGTM! 服务迁移正确。成功将调用从旧的
variable.formatPresetTemplateString迁移到新的promptRenderer.renderTemplate,并正确传递了包含 session 的 configurable 选项。这与整个 PR 的架构升级保持一致。packages/core/src/llm-core/chat/default.ts (1)
72-72: LGTM! 服务引用已更新。正确地将服务引用从
ctx.chatluna.variable更新为ctx.chatluna.promptRenderer,与新的 PromptRenderService 架构保持一致。Also applies to: 90-90
packages/core/src/middlewares/model/request_model.ts (1)
277-311: LGTM! 正确处理新的渲染结果。正确地从渲染结果中提取
.text属性,适配了新的renderTemplateAPI 返回对象(包含 text 和 variables 字段)的变化。在单消息和多消息路径中的处理保持一致。packages/core/src/llm-core/chain/plugin_chat_chain.ts (1)
107-107: LGTM! 正确使用新的服务键名。在构造 ChatLunaChatPrompt 时正确使用了
promptRenderService作为键名,与新的服务架构保持一致。packages/core/src/services/chat.ts (1)
56-56: LGTM! 服务重构完整且一致。成功地将内部字段、getter 和导出都从旧的 VariableService 迁移到新的 PromptRenderService。命名在整个文件中保持一致(_promptRenderer 和 promptRenderer()),架构升级清晰明确。
Also applies to: 71-71, 84-84, 339-341, 1114-1114
packages/core/src/chains/rooms.ts (1)
193-193: LGTM! 添加了空值安全检查。使用可选链操作符
model?.toModelName()是良好的防御性编程实践,可以避免在 model 为 null/undefined 时出现运行时错误。Also applies to: 213-213
packages/core/src/services/prompt_renderer.ts (3)
157-183: LGTM! 消息渲染实现正确。
renderMessages方法正确地:
- 渲染每个消息的内容
- 根据消息类型创建新的消息实例(保持不可变性)
- 保留原始的 additional_kwargs
实现清晰且类型安全。
185-222: LGTM! 预设模板渲染实现完善。
renderPresetTemplate方法不仅渲染消息,还收集所有使用的变量,这对于调试和验证模板非常有用。实现逻辑清晰且功能完整。
225-229: LGTM! 模块扩展设计良好。通过模块扩展为
RenderConfigurable接口添加session属性是一个很好的设计,允许渲染器访问 Koishi 会话上下文,同时保持包的解耦。packages/core/src/llm-core/chain/chat_chain.ts (2)
13-13: 导入语句更新正确。类型导入已正确更新为
ChatLunaPromptRenderService,与 PR 的架构迁移目标一致。
59-86: 请手动验证所有调用 ChatLunaChatChain.fromLLM 的位置是否正确传入了 variableService 并匹配 ChatLunaChatPrompt.promptRenderService
Update processDynamicImport.ts to use new package directory names following the recent repository restructure.
- Fix incorrect logo path in README_EN.MD (resources -> resources) - Remove unnecessary database cleanup in leaveConversationRoom - Add default empty object parameters to prompt renderer methods for better usability
This PR introduces a new
shared-prompt-rendererpackage that provides a powerful and flexible template rendering system with JavaScript-like syntax, along with refactoring changes to improve project structure.New Features
shared-prompt-rendererpackage: A complete template rendering system with:if/elseif/elsemulti-level conditionalsfor(array iteration),while(boolean condition),repeat(count-based)@chatluna/corefor prompt template processingadapter-prefix for better organizationBug Fixes
Other Changes