Skip to content

[Feature] Implement shared-prompt-renderer with advanced template features#569

Merged
dingyi222666 merged 10 commits into
v1-devfrom
feat/prompt-template
Oct 4, 2025
Merged

[Feature] Implement shared-prompt-renderer with advanced template features#569
dingyi222666 merged 10 commits into
v1-devfrom
feat/prompt-template

Conversation

@dingyi222666
Copy link
Copy Markdown
Member

This PR introduces a new shared-prompt-renderer package that provides a powerful and flexible template rendering system with JavaScript-like syntax, along with refactoring changes to improve project structure.

New Features

  • New shared-prompt-renderer package: A complete template rendering system with:
    • JavaScript-like expression syntax (variables, functions, operators)
    • Advanced control flow: if/elseif/else multi-level conditionals
    • Multiple loop types: for (array iteration), while (boolean condition), repeat (count-based)
    • Dynamic function calling: functions can be called as variables and support property chain access
    • Object and array manipulation with member/index access
    • Ternary operators and comprehensive operator support
    • LRU caching for improved performance
  • Core integration: Integrated the new renderer into @chatluna/core for prompt template processing
  • Package restructuring: Renamed adapter packages with adapter- prefix for better organization
  • Extension tools enhancement: Updated todos tracking to use conversationId for better context association

Bug Fixes

  • Fixed null safety checks for model operations in core
  • Fixed todos tool to properly track conversations using conversationId

Other Changes

  • Reorganized folder structure with consistent naming conventions
  • Updated package homepage paths to reflect new directory structure
  • Removed legacy prompt tokenization code in favor of new shared renderer
  • Added comprehensive documentation with examples for the new template system

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.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 4, 2025

Note

Other AI code review bot(s) detected

CodeRabbit 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

Cohort / File(s) 变更概要
文档与资源
CLAUDE.MD, README.MD, README_EN.MD, README_JP.MD
新增 Windows 路径使用说明文件 CLAUDE.MD;将 README 中项目 logo 路径从 ./logo.png 改为 ./resources/logo.png(各语言版均更新)。
服务替换:Variable → PromptRenderer
packages/core/src/services/prompt_renderer.ts, packages/core/src/services/variable.ts, packages/core/src/services/chat.ts, packages/core/src/utils/string.ts
新增 ChatLunaPromptRenderService 并将服务引用从 ChatLunaVariableService 切换为 ChatLunaPromptRenderService;移除老的 variable.ts 实现;ChatLunaService 暴露 promptRenderer();调用处由 formatPresetTemplateString/variable 改为 renderTemplate(..., { configurable: { session } }) / promptRenderer
链与提示管线适配
packages/core/src/llm-core/chain/prompt.ts, packages/core/src/llm-core/chain/chat_chain.ts, packages/core/src/llm-core/chain/plugin_chat_chain.ts, packages/core/src/llm-core/chat/default.ts
输入接口与类字段类型从 ChatLunaVariableService 替换为 ChatLunaPromptRenderService;构造/工厂调用改传 promptRenderServiceChatLunaChatPrompt 的临时 preset 及提示生成流程相应调整以使用渲染服务。
预设解析与分词移除
packages/core/src/llm-core/prompt/preset_prompt_parse.ts, packages/core/src/llm-core/prompt/tokenize.ts
删除旧的 TXT 预设回退逻辑与整个 tokenize.ts 文件;loadPreset 在 YAML 解析失败时不再回退为 TXT,而是抛出错误;导出从 ./tokenize 改为 ./type
中间件与房间处理
packages/core/src/chains/rooms.ts, packages/core/src/middlewares/room/check_room.ts, packages/core/src/middlewares/room/resolve_room.ts, packages/core/src/middlewares/model/request_model.ts
rooms:获取默认模型名使用可选链/null 检查,leaveConversationRoom 在清理时也移除 groupId;check_room:若检测到用户不在房间,尝试调用 leaveConversationRoom 做清理(try/catch);resolve_room:对 config.defaultModel 做空安全长度判断;request_model:格式化用户提示时提取并传播 result.text
扩展工具调整:Todos
packages/extension-tools/src/plugins/todos.ts
conversationId(来自 config.configurable.conversationId)贯通到动作逻辑,generateTodos 签名新增 conversationId 并用于选择 todosId

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 相关实现
Loading
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
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Poem

小兔翻页敲代码,提示渲染新登场,
旧变量散步去远方,分词刹那已成光。
房门整理留痕忙,会话 ID 舵已装。
Logo 换径笑颜长,开发路上共欢畅。 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed 标题准确概括了主要改动,即引入了 shared-prompt-renderer 包并实现了高级模板功能,简洁具体且与变更集内容高度一致,无多余或模糊表述。
Description Check ✅ Passed Pull request 描述详尽列出了新包 shared-prompt-renderer 的功能特性、内核集成、目录重构及文档示例,与实际变更内容高度相关且不会产生歧义,满足检查要求。
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/prompt-template

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 47d19fb and 45211d7.

📒 Files selected for processing (3)
  • README_EN.MD (1 hunks)
  • packages/core/src/chains/rooms.ts (4 hunks)
  • packages/core/src/services/prompt_renderer.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/services/prompt_renderer.ts
⏰ 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 (4)
packages/core/src/chains/rooms.ts (4)

183-194: LGTM! 可选链防御性编程。

在 Line 193 使用 model?.toModelName() 是正确的防御性编程实践,防止当 find() 返回 undefined 时出现空指针异常。


194-224: LGTM! 一致的空安全处理。

Line 213 的可选链使用与 Line 193 保持一致,确保整个模型选择流程的空安全性。


236-249: LGTM! 增强的配置验证逻辑。

Line 239 新增的 config.defaultModel == null 检查与上面的可选链改动相呼应,确保模板房间配置的完整性验证。


448-463: LGTM! 更精确的用户记录清理。

Lines 460-461 添加 groupId 参数使用户默认房间记录的删除更加精确,避免误删其他群组的记录,提升了数据完整性。


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @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

  • New Shared Prompt Renderer: Introduced a new shared-prompt-renderer package offering advanced templating features, including JavaScript-like expression syntax, multi-level conditionals (if/elseif/else), various loop types (for, while, repeat), dynamic function calling with property chain access, object/array manipulation, ternary operators, and LRU caching for performance.
  • Core Integration and Refactoring: The new prompt renderer has been integrated into @chatluna/core for enhanced prompt template processing. This change involved replacing the legacy prompt tokenization code and the ChatLunaVariableService with the new ChatLunaPromptRenderService.
  • Package Renaming and Restructuring: All adapter packages have been renamed to follow a consistent adapter- prefix (e.g., azure-openai-adapter became adapter-azure-openai). Similarly, extension packages now use extension- (e.g., long-memory became extension-long-memory), renderer packages use renderer-, and service packages use service- prefixes. This improves project organization and clarity.
  • Bug Fixes and Enhancements: Implemented null safety checks for model operations within the core logic and updated the todos tool to properly track conversations using conversationId, enhancing context association. The leaveConversationRoom function was also updated to correctly handle group memberships.
  • Deprecated TXT Preset Removal: The deprecated TXT preset format loading mechanism has been removed from packages/core/src/llm-core/prompt/preset_prompt_parse.ts, now requiring YAML for preset templates and throwing an error on failure instead of falling back.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread README_EN.MD Outdated
Comment thread CLAUDE.MD
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: ChatLunaPromptRenderService

Also applies to: 61-61

packages/core/src/services/prompt_renderer.ts (2)

106-122: 消除重复的函数实现。

urlfetch 函数提供者的实现完全相同(第 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: 考虑添加错误处理。

urlfetch 函数提供者调用的 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

📥 Commits

Reviewing files that changed from the base of the PR and between a4b2e92 and 47d19fb.

⛔ Files ignored due to path filters (99)
  • .claude/settings.local.json is excluded by !**/*.json
  • package.json is excluded by !**/*.json
  • packages/adapter-azure-openai/package.json is excluded by !**/*.json
  • packages/adapter-azure-openai/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-azure-openai/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-azure-openai/tsconfig.json is excluded by !**/*.json
  • packages/adapter-claude/package.json is excluded by !**/*.json
  • packages/adapter-claude/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-claude/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-claude/tsconfig.json is excluded by !**/*.json
  • packages/adapter-deepseek/package.json is excluded by !**/*.json
  • packages/adapter-deepseek/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-deepseek/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-deepseek/tsconfig.json is excluded by !**/*.json
  • packages/adapter-dify/package.json is excluded by !**/*.json
  • packages/adapter-dify/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-dify/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-dify/tsconfig.json is excluded by !**/*.json
  • packages/adapter-doubao/package.json is excluded by !**/*.json
  • packages/adapter-doubao/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-doubao/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-doubao/tsconfig.json is excluded by !**/*.json
  • packages/adapter-gemini/package.json is excluded by !**/*.json
  • packages/adapter-gemini/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-gemini/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-gemini/tsconfig.json is excluded by !**/*.json
  • packages/adapter-hunyuan/package.json is excluded by !**/*.json
  • packages/adapter-hunyuan/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-hunyuan/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-hunyuan/tsconfig.json is excluded by !**/*.json
  • packages/adapter-ollama/package.json is excluded by !**/*.json
  • packages/adapter-ollama/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-ollama/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-ollama/tsconfig.json is excluded by !**/*.json
  • packages/adapter-openai-like/package.json is excluded by !**/*.json
  • packages/adapter-openai-like/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-openai-like/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-openai-like/tsconfig.json is excluded by !**/*.json
  • packages/adapter-openai/package.json is excluded by !**/*.json
  • packages/adapter-openai/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-openai/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-openai/tsconfig.json is excluded by !**/*.json
  • packages/adapter-qwen/package.json is excluded by !**/*.json
  • packages/adapter-qwen/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-qwen/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-qwen/tsconfig.json is excluded by !**/*.json
  • packages/adapter-rwkv/package.json is excluded by !**/*.json
  • packages/adapter-rwkv/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-rwkv/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-rwkv/tsconfig.json is excluded by !**/*.json
  • packages/adapter-spark/package.json is excluded by !**/*.json
  • packages/adapter-spark/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-spark/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-spark/tsconfig.json is excluded by !**/*.json
  • packages/adapter-wenxin/package.json is excluded by !**/*.json
  • packages/adapter-wenxin/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-wenxin/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-wenxin/tsconfig.json is excluded by !**/*.json
  • packages/adapter-zhipu/package.json is excluded by !**/*.json
  • packages/adapter-zhipu/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-zhipu/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/adapter-zhipu/tsconfig.json is excluded by !**/*.json
  • packages/core/package.json is excluded by !**/*.json
  • packages/extension-long-memory/memory.pdf is excluded by !**/*.pdf, !**/*.pdf
  • packages/extension-long-memory/package.json is excluded by !**/*.json
  • packages/extension-long-memory/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/extension-long-memory/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/extension-long-memory/tsconfig.json is excluded by !**/*.json
  • packages/extension-mcp/package.json is excluded by !**/*.json
  • packages/extension-mcp/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/extension-mcp/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/extension-mcp/tsconfig.json is excluded by !**/*.json
  • packages/extension-tools/package.json is excluded by !**/*.json
  • packages/extension-tools/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/extension-tools/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/extension-tools/tsconfig.json is excluded by !**/*.json
  • packages/extension-variable/package.json is excluded by !**/*.json
  • packages/extension-variable/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/extension-variable/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/extension-variable/tsconfig.json is excluded by !**/*.json
  • packages/renderer-image/package.json is excluded by !**/*.json
  • packages/renderer-image/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/renderer-image/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/renderer-image/tsconfig.json is excluded by !**/*.json
  • packages/service-embeddings/package.json is excluded by !**/*.json
  • packages/service-embeddings/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/service-embeddings/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/service-embeddings/tsconfig.json is excluded by !**/*.json
  • packages/service-image/package.json is excluded by !**/*.json
  • packages/service-image/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/service-image/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/service-image/tsconfig.json is excluded by !**/*.json
  • packages/service-search/package.json is excluded by !**/*.json
  • packages/service-search/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/service-search/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • packages/service-search/tsconfig.json is excluded by !**/*.json
  • packages/service-vector-store/package.json is excluded by !**/*.json
  • packages/service-vector-store/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/service-vector-store/src/locales/zh-CN.schema.yml is 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

这种设计确保了:

  1. 生成新待办事项时优先使用 conversationId,无则生成新 ID
  2. 访问现有待办事项时优先使用 conversationId,无则使用用户提供的 ID
  3. 运行时验证(第 176、216 行)会捕获未定义的 ID

130-130: LGTM! 合理的回退机制

使用 conversationId || generateId() 确保了在 conversationId 不可用时生成新的待办事项 ID。这与第 156 行将生成的 ID 发送给用户的逻辑配合良好,用户可以在后续操作中使用该 ID。


102-102: 确认 conversationId 可选类型
请在 ChatLunaToolRunnableconfigurable 中验证 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 属性,适配了新的 renderTemplate API 返回对象(包含 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 方法正确地:

  1. 渲染每个消息的内容
  2. 根据消息类型创建新的消息实例(保持不可变性)
  3. 保留原始的 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

Comment thread packages/core/src/chains/rooms.ts Outdated
Comment thread packages/core/src/llm-core/chain/prompt.ts
Comment thread packages/extension-tools/src/plugins/todos.ts
Comment thread README_EN.MD Outdated
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant