Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style: add promptfoo to improve prompts quality (#9568)

Arvin Xu33874c20d1b3
diff --git a/package.json b/package.json
index ee484460d65..3b34bdc2ed1 100644
--- a/package.json
+++ b/package.json
@@ -379,7 +379,8 @@
},
"pnpm": {
"onlyBuiltDependencies": [
- "@vercel/speed-insights"
+ "@vercel/speed-insights",
+ "better-sqlite3"
],
"overrides": {
"mdast-util-gfm-autolink-literal": "2.0.0"
diff --git a/packages/prompts/.gitignore b/packages/prompts/.gitignore
new file mode 100644
index 00000000000..d85b1793eb5
--- /dev/null
+++ b/packages/prompts/.gitignore
@@ -0,0 +1,15 @@
+# Promptfoo results and cache
+promptfoo-results.json
+results/
+.promptfoo/
+*.promptfoo.cache
+
+# Node modules
+node_modules/
+
+# Test coverage
+coverage/
+
+# Environment variables
+.env
+.env.local
\ No newline at end of file
diff --git a/packages/prompts/CLAUDE.md b/packages/prompts/CLAUDE.md
new file mode 100644
index 00000000000..10101715b56
--- /dev/null
+++ b/packages/prompts/CLAUDE.md
@@ -0,0 +1,329 @@
+# Prompt Engineering Guide for @lobechat/prompts
+
+本文档提供使用 Claude Code 优化 LobeChat 提示词的指南和最佳实践。
+
+## 提示词优化工作流
+
+### 1. 运行测试并识别问题
+
+```bash
+# 运行特定提示词测试
+pnpm promptfoo eval -c promptfoo/ < prompt-name > /eval.yaml
+
+# 查看失败的测试详情
+pnpm promptfoo eval -c promptfoo/ < prompt-name > /eval.yaml 2>&1 | grep -A 20 "FAIL"
+```
+
+**关注点:**
+
+- 失败率和失败模式
+- 不同模型的行为差异
+- 具体的失败原因(来自 llm-rubric 的评价)
+
+### 2. 分析失败原因
+
+**常见问题模式:**
+
+- **输出格式问题**:模型添加了不需要的解释或上下文
+- **语言混淆**:在多语言场景下使用了错误的语言
+- **过度 / 不足翻译**:技术术语被翻译或保留不当
+- **上下文理解**:未正确理解何时使用 / 忽略上下文
+- **一致性问题**:不同模型间的行为不一致
+
+### 3. 更新提示词
+
+**优化策略:**
+
+#### 使用英文提示词
+
+```typescript
+// ❌ 不好 - 中文提示词在多语言场景下容易混淆
+content: '你是一名翻译助手,请将内容翻译为...';
+
+// ✅ 好 - 英文提示词更通用
+content: 'You are a translation assistant. Translate the content to...';
+```
+
+#### 明确输出要求
+
+```typescript
+// ❌ 不好 - 模糊的指令
+content: 'Please translate the text';
+
+// ✅ 好 - 具体的规则
+content: `Translate the text.
+
+Rules:
+- Output ONLY the translated text, no explanations
+- Preserve technical terms exactly as they appear
+- No additional commentary`;
+```
+
+#### 使用示例指导行为
+
+```typescript
+// ✅ 提供具体示例
+content: `Select an emoji for the content.
+
+Examples:
+- "I got a promotion" → 🎉
+- "Code wizard" → 🧙‍♂️
+- "Business plan" → 🚀`;
+```
+
+#### 使用 MUST/SHOULD/MAY 表达优先级
+
+```typescript
+// ✅ 明确的优先级
+content: `Answer based on context.
+
+Rules:
+- MUST use context information as foundation
+- SHOULD supplement with general knowledge
+- MAY provide additional examples`;
+```
+
+### 4. 迭代验证
+
+每次修改后重新运行测试:
+
+```bash
+pnpm promptfoo eval -c promptfoo/ < prompt-name > /eval.yaml
+```
+
+**目标:**
+
+- 每轮优化应提升 5-10% 通过率
+- 通常需要 3-5 轮迭代达到 100%
+- 关注不同模型间的一致性
+
+## 提示词模式库
+
+### 翻译 (Translation)
+
+```typescript
+export const chainTranslate = (content: string, targetLang: string) => ({
+ messages: [
+ {
+ content: `You are a professional translator. Translate to ${targetLang}.
+
+Rules:
+- Output ONLY the translated text, no explanations
+- Preserve technical terms, code identifiers, API keys exactly
+- Maintain original formatting
+- Use natural, idiomatic expressions`,
+ role: 'system',
+ },
+ {
+ content,
+ role: 'user',
+ },
+ ],
+});
+```
+
+**关键点:**
+
+- 使用英文系统提示词
+- 明确 "仅输出翻译内容"
+- 列举需要保留的内容类型
+
+### 知识库问答 (Knowledge Q\&A)
+
+```typescript
+export const chainAnswerWithContext = ({ context, question }) => {
+ const hasContext = context.filter((c) => c.trim()).length > 0;
+
+ return {
+ messages: [
+ {
+ content: hasContext
+ ? `Answer based on provided context.
+
+Rules:
+- If context is COMPLETELY DIFFERENT topic: state this and do NOT answer
+- If context is related (even if limited):
+ * MUST use context as foundation
+ * SHOULD supplement with general knowledge
+ * For "how to" questions, provide actionable steps
+ * Example: Context about "Docker containerization" + "How to deploy?"
+ → Explain deployment steps using your knowledge`
+ : `Answer using your knowledge.`,
+ role: 'user',
+ },
+ ],
+ };
+};
+```
+
+**关键点:**
+
+- 区分 "无上下文" 和 "不相关上下文"
+- 明确何时可以补充通用知识
+- 提供具体示例说明预期行为
+
+### Emoji 选择 (Emoji Picker)
+
+```typescript
+export const chainPickEmoji = (content: string) => ({
+ messages: [
+ {
+ content: `You are an emoji expert.
+
+Rules:
+- Output ONLY a single emoji (1-2 characters)
+- Focus on CONTENT meaning, not language
+- Prioritize topic-specific emojis over generic emotions
+- For work/projects, use work-related emojis not cultural symbols`,
+ role: 'system',
+ },
+ { content: 'I got a promotion', role: 'user' },
+ { content: '🎉', role: 'assistant' },
+ { content, role: 'user' },
+ ],
+});
+```
+
+**关键点:**
+
+- 使用示例引导行为
+- 明确优先级(主题 > 情绪)
+- 避免文化符号混淆
+
+### 标题生成 (Summary Title)
+
+```typescript
+export const chainSummaryTitle = (messages, locale) => ({
+ messages: [
+ {
+ content: `Generate a concise title.
+
+Rules:
+- Maximum 10 words
+- Maximum 50 characters
+- No punctuation marks
+- Use language: ${locale}
+- Keep it short and to the point`,
+ role: 'system',
+ },
+ {
+ content: messages.map((m) => `${m.role}: ${m.content}`).join('\n'),
+ role: 'user',
+ },
+ ],
+});
+```
+
+**关键点:**
+
+- 同时限制词数和字符数
+- 明确输出语言
+- 简洁明了的规则
+
+## 测试策略
+
+### 多语言测试
+
+每个提示词应测试至少 3-5 种语言:
+
+```yaml
+tests:
+ # 英语
+ - vars:
+ content: 'Hello, how are you?'
+ # 中文
+ - vars:
+ content: '你好,你好吗?'
+ # 西班牙语
+ - vars:
+ content: 'Hola, ¿cómo estás?'
+```
+
+### 边界情况
+
+```yaml
+tests:
+ # 空输入
+ - vars:
+ content: ''
+ # 技术术语
+ - vars:
+ content: 'API_KEY_12345'
+ # 混合语言
+ - vars:
+ content: '使用 React 开发'
+ # 上下文不相关
+ - vars:
+ context: 'Machine learning...'
+ query: 'Explain blockchain'
+```
+
+### 断言类型
+
+```yaml
+assert:
+ # LLM 评判
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: 'Should translate accurately without extra commentary'
+
+ # 包含检查
+ - type: contains-any
+ value: ['React', 'JavaScript']
+
+ # 排除检查
+ - type: not-contains
+ value: 'explanation'
+```
+
+## 常见问题
+
+### Q: 如何处理不同模型的差异行为?
+
+A: 使用更明确的指令和示例。如果某个模型持续失败,考虑:
+
+1. 添加该模型的具体示例
+2. 使用更强的指令(MUST 而非 SHOULD)
+3. 在提示词中明确该场景
+
+### Q: 何时使用中文 vs 英文提示词?
+
+A:
+
+- **英文**:多语言场景、技术内容、跨模型一致性
+- **中文**:纯中文输入输出、中文特定的语言理解任务
+
+### Q: 如何达到 100% 通过率?
+
+A: 迭代流程:
+
+1. 运行测试 → 2. 分析失败 → 3. 更新提示词 → 4. 重新测试
+
+- 通常需要 3-5 轮
+- 关注最后 5% 的边界情况
+- 考虑调整测试断言(如果过于严格)
+
+### Q: 什么时候应该修改测试而非提示词?
+
+A: 当:
+
+- 测试期望不合理(如要求模型做不到的事)
+- 断言过于严格(如精确匹配特定词语)
+- 多个模型都以不同但合理的方式回答
+
+## 最佳实践总结
+
+1. **使用英文系统提示词**以获得更好的跨语言一致性
+2. **明确输出格式**:"Output ONLY...","No explanations"
+3. **使用示例**引导模型行为
+4. **分层规则**:MUST > SHOULD > MAY
+5. **具体化**:列举具体情况而非抽象描述
+6. **迭代验证**:小步快跑,每次改进一个问题
+7. **跨模型测试**:至少测试 3 个不同的模型
+8. **版本控制**:记录每次优化的原因和结果
+
+## 参考资源
+
+- [promptfoo 文档](https://promptfoo.dev)
+- [OpenAI Prompt Engineering Guide](https://platform.openai.com/docs/guides/prompt-engineering)
+- [Anthropic Prompt Engineering](https://docs.anthropic.com/claude/docs/prompt-engineering)
diff --git a/packages/prompts/README.md b/packages/prompts/README.md
new file mode 100644
index 00000000000..ee7d31fb89d
--- /dev/null
+++ b/packages/prompts/README.md
@@ -0,0 +1,224 @@
+# @lobechat/prompts
+
+This package contains prompt chains and templates for the LobeChat application, with comprehensive testing using promptfoo.
+
+## Features
+
+- **Prompt Chains**: Reusable prompt templates for various AI tasks
+- **AI Testing**: Comprehensive testing using promptfoo for prompt quality assurance
+- **Multi-language Support**: Prompts and tests for multiple languages
+- **Type Safety**: Full TypeScript support with proper type definitions
+
+## Available Prompt Chains
+
+- `chainSummaryTitle` - Generate conversation titles
+- `chainLangDetect` - Detect language of input text
+- `chainTranslate` - Translate content between languages
+- `chainPickEmoji` - Select appropriate emojis for content
+- `chainAnswerWithContext` - Answer questions using knowledge base context
+
+## Testing with promptfoo
+
+This package uses [promptfoo](https://promptfoo.dev) for AI-powered testing of prompts. The testing suite evaluates prompt quality, consistency, and performance across different AI models.
+
+### Prerequisites
+
+Set up your API keys in your environment:
+
+```bash
+export OPENAI_API_KEY="your-openai-key"
+export ANTHROPIC_API_KEY="your-anthropic-key" # optional
+```
+
+### Running Tests
+
+```bash
+# Run all prompt tests
+pnpm test:prompts
+
+# Run tests in watch mode for development
+pnpm test:prompts:watch
+
+# Generate summary report
+pnpm test:prompts:summary
+
+# Run tests for CI (no cache, structured output)
+pnpm test:prompts:ci
+
+# View test results in web UI
+pnpm promptfoo:view
+```
+
+### Test Configuration
+
+Tests are organized by prompt type in the `promptfoo/` directory:
+
+```
+promptfoo/
+├── summary-title/
+│ ├── eval.yaml # Test configuration
+│ └── prompt.ts # Prompt wrapper
+├── translation/
+│ ├── eval.yaml
+│ └── prompt.ts
+├── language-detection/
+│ ├── eval.yaml
+│ └── prompt.ts
+├── emoji-picker/
+│ ├── eval.yaml
+│ └── prompt.ts
+└── knowledge-qa/
+ ├── eval.yaml
+ └── prompt.ts
+```
+
+Each test configuration includes:
+
+- Multiple test cases with different inputs
+- Assertions for output validation (regex, JSON, custom logic)
+- LLM-based rubric evaluation for semantic correctness
+- Performance and cost monitoring
+
+### Test Structure
+
+Tests directly use the actual prompt chain functions from `src/chains/`. The TypeScript wrapper files in `promptfoo/prompts/` import and call the real chain functions, ensuring perfect synchronization.
+
+```yaml
+description: Test description
+providers:
+ - openai:gpt-4o-mini
+ - anthropic:claude-3-5-haiku-latest
+prompts:
+ - file://prompts/summary-title.ts # Imports and uses src/chains/summaryTitle.ts
+tests:
+ - vars:
+ messages: [...]
+ locale: 'en-US'
+ assert:
+ - type: llm-rubric
+ value: 'Expected behavior description'
+ provider: openai:gpt-4o # Specify grader model for LLM rubric
+ - type: contains
+ value: 'expected text'
+ - type: not-contains
+ value: 'unwanted text'
+```
+
+### Adding New Tests
+
+1. Create a test configuration file in `promptfoo/`
+2. Create a TypeScript wrapper in `promptfoo/prompts/` that imports and calls your chain function from `src/chains/`
+3. Add the test to `promptfooconfig.yaml`
+4. Run tests to validate
+
+**Advantage**: The wrapper files automatically stay in sync with source code changes since they directly import and use the actual chain functions.
+
+### Performance Monitoring
+
+Tests include performance monitoring:
+
+- Response time tracking
+- Cost per request monitoring
+- Quality score evaluation
+- Cross-model consistency checks
+
+### CI Integration
+
+The `test:prompts:ci` script is designed for continuous integration:
+
+- Structured JSON output for parsing
+- No interactive prompts
+- Clear pass/fail status codes
+- Detailed error reporting
+
+## Development
+
+```bash
+# Install dependencies
+pnpm install
+
+# Run unit tests
+pnpm test
+
+# Run prompt tests
+pnpm test:prompts
+
+# Run all tests
+pnpm test && pnpm test:prompts
+```
+
+## Contributing
+
+When adding new prompt chains:
+
+1. Implement the prompt function in `src/chains/`
+2. Add unit tests in `src/chains/__tests__/`
+3. Create promptfoo tests in `promptfoo/`
+4. Update this README with the new chain description
+
+## Architecture
+
+The package follows a layered architecture:
+
+```
+src/
+├── chains/ # Prompt chain implementations
+├── prompts/ # Prompt templates and utilities
+└── index.ts # Main exports
+
+promptfoo/
+├── prompts/ # Prompt implementations for testing
+├── *.yaml # Test configurations
+└── results/ # Test output directory
+```
+
+## Best Practices
+
+1. **Test Coverage**: Every prompt chain should have comprehensive promptfoo tests
+2. **Multi-language**: Test prompts with multiple languages when applicable
+3. **Edge Cases**: Include tests for edge cases and error conditions
+4. **Performance**: Monitor cost and response time in tests
+5. **Consistency**: Use consistent assertion patterns across tests
+6. **Prompt Optimization**: Use test results to iteratively improve prompts (see CLAUDE.md for optimization workflow)
+
+## Prompt Optimization Workflow
+
+This package follows an iterative prompt optimization process using promptfoo test results:
+
+### Example: Translation Prompt Optimization
+
+**Initial State**: 85% pass rate with issues:
+
+- Claude models added explanatory text ("以下是翻译...")
+- GPT models over-translated technical terms (`API_KEY_12345` → `API 密钥_12345`)
+
+**Optimization Process**:
+
+1. **Identify Failures**: Run tests and analyze specific failure patterns
+2. **Update Prompts**: Modify prompt rules based on failure analysis
+ - Added: "Output ONLY the translated text, no explanations"
+ - Added: "Preserve technical terms, code identifiers, API keys exactly as they appear"
+3. **Re-run Tests**: Validate improvements across all models
+4. **Iterate**: Repeat until 100% pass rate achieved
+
+**Final Result**: 100% pass rate (14/14 tests) across GPT-5-mini, Claude-3.5-Haiku, and Gemini-Flash
+
+### Example: Knowledge Q\&A Optimization
+
+**Initial State**: 71.43% pass rate with context handling issues
+
+**Optimization Journey**:
+
+- **Round 1** (80.95%): Clarified context relevance checking
+- **Round 2** (90.48%): Distinguished between "no context" vs "irrelevant context"
+- **Round 3** (92.86%): Added explicit rules for partial context
+- **Round 4** (96.43%): Emphasized supplementing with general knowledge
+- **Final** (100%): Added concrete example and MUST/SHOULD directives
+
+**Key Learning**: When context is topic-relevant but information-limited, models should:
+
+- Use context as foundation
+- Supplement with general knowledge
+- Provide practical, actionable guidance
+
+See `CLAUDE.md` for detailed prompt engineering guidelines.
diff --git a/packages/prompts/package.json b/packages/prompts/package.json
index f5723fba521..89fe7b0a4a4 100644
--- a/packages/prompts/package.json
+++ b/packages/prompts/package.json
@@ -4,10 +4,23 @@
"private": true,
"main": "./src/index.ts",
"scripts": {
+ "promptfoo:init": "promptfoo init",
+ "promptfoo:view": "promptfoo view",
"test": "vitest",
- "test:coverage": "vitest --coverage --silent='passed-only'"
+ "test:coverage": "vitest --coverage --silent='passed-only'",
+ "test:prompts": "pnpm test:prompts:translate && pnpm test:prompts:summary && pnpm test:prompts:lang && pnpm test:prompts:emoji && pnpm test:prompts:qa",
+ "test:prompts:emoji": "promptfoo eval -c promptfoo/emoji-picker/eval.yaml",
+ "test:prompts:lang": "promptfoo eval -c promptfoo/language-detection/eval.yaml",
+ "test:prompts:qa": "promptfoo eval -c promptfoo/knowledge-qa/eval.yaml",
+ "test:prompts:summary": "promptfoo eval -c promptfoo/summary-title/eval.yaml",
+ "test:prompts:translate": "promptfoo eval -c promptfoo/translate/eval.yaml",
+ "test:update": "vitest -u"
},
"dependencies": {
"@lobechat/types": "workspace:*"
+ },
+ "devDependencies": {
+ "promptfoo": "^0.118.11",
+ "tsx": "^4.20.4"
}
}
diff --git a/packages/prompts/promptfoo/emoji-picker/eval.yaml b/packages/prompts/promptfoo/emoji-picker/eval.yaml
new file mode 100644
index 00000000000..427f813058f
--- /dev/null
+++ b/packages/prompts/promptfoo/emoji-picker/eval.yaml
@@ -0,0 +1,170 @@
+description: Test emoji selection for different conversation topics and contexts
+
+providers:
+ - openai:chat:gpt-5-mini
+ - openai:chat:claude-3-5-haiku-latest
+ - openai:chat:gemini-flash-latest
+ - openai:chat:deepseek-chat
+
+prompts:
+ - file://promptfoo/emoji-picker/prompt.ts
+
+tests:
+ - vars:
+ content: "I just got a promotion at work! I'm so excited!"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select a positive, celebratory emoji appropriate for work success (e.g., 🎉, 🎊, ⭐, 💼, 🚀)"
+ - type: not-contains
+ value: "explanation"
+
+ - vars:
+ content: "My dog passed away yesterday. I'm really sad."
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select a sympathetic, sad emoji appropriate for loss and grief (e.g., 😢, 😭, 💔, 😔)"
+ - type: not-contains
+ value: "explanation"
+
+ - vars:
+ content: "Can you help me with this math problem?"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to learning, thinking, or mathematics (e.g., 🤔, 📚, ✏️, 🧮, 🔢)"
+ - type: not-contains
+ value: "explanation"
+
+ - vars:
+ content: "I'm going on vacation to Hawaii next week!"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to vacation, travel, or tropical themes (e.g., 🌺, 🏖️, ✈️, 🌴, ☀️)"
+ - type: not-contains
+ value: "explanation"
+
+ - vars:
+ content: "I'm learning to cook Italian food"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to cooking or Italian food (e.g., 🍝, 🍕, 👨‍🍳, 🍽️)"
+ - type: not-contains
+ value: "explanation"
+
+ - vars:
+ content: "Technical documentation about API endpoints"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to technology, development, or documentation (e.g., 💻, 📖, ⚙️, 🔧, 📝)"
+ - type: not-contains
+ value: "explanation"
+
+ # Chinese language tests
+ - vars:
+ content: "我刚刚升职了!太激动了!"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select a positive, celebratory emoji appropriate for work success (e.g., 🎉, 🎊, ⭐, 💼, 🚀)"
+ - type: not-contains
+ value: "explanation"
+
+ - vars:
+ content: "我的猫咪昨天去世了,我很难过"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select a sympathetic, sad emoji appropriate for loss and grief (e.g., 😢, 😭, 💔, 😔)"
+ - type: not-contains
+ value: "explanation"
+
+ - vars:
+ content: "我正在学习做日本料理"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to cooking or Japanese food (e.g., 🍱, 🍣, 🍜, 👨‍🍳)"
+ - type: not-contains
+ value: "explanation"
+
+ # Spanish language tests
+ - vars:
+ content: "¡Me voy de vacaciones a la playa la próxima semana!"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to vacation, beach, or tropical themes (e.g., 🏖️, ☀️, 🌊, 🏝️)"
+ - type: not-contains
+ value: "explanation"
+
+ - vars:
+ content: "Estoy estudiando para mi examen de matemáticas"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to studying, learning, or mathematics (e.g., 📚, 🤓, 🧮, ✏️, 📊, 📐, 📏)"
+ - type: not-contains
+ value: "explanation"
+
+ # French language tests
+ - vars:
+ content: "Je viens de terminer mon marathon! Je suis épuisé mais heureux"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to running, sports, or achievement (e.g., 🏃, 🏅, 💪, 🎯)"
+ - type: not-contains
+ value: "explanation"
+
+ - vars:
+ content: "J'apprends à jouer de la guitare"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to music or guitar (e.g., 🎸, 🎵, 🎶, 🎼)"
+ - type: not-contains
+ value: "explanation"
+
+ # Japanese language tests
+ - vars:
+ content: "新しいプロジェクトが始まりました!頑張ります"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to new beginning, work, or motivation (e.g., 🚀, 💼, 💪, ✨)"
+ - type: not-contains
+ value: "explanation"
+
+ - vars:
+ content: "桜が咲いて本当に綺麗です"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to cherry blossoms, flowers, or beauty (e.g., 🌸, 🌺, 🌼, 🌷)"
+ - type: not-contains
+ value: "explanation"
+
+ # German language tests
+ - vars:
+ content: "Ich habe gerade ein neues Auto gekauft!"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to cars or excitement (e.g., 🚗, 🎉, 🚙)"
+ - type: not-contains
+ value: "explanation"
+
+ # Russian language tests
+ - vars:
+ content: "Я люблю читать книги по вечерам"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should select an emoji related to reading or books (e.g., 📚, 📖, 📕, 🤓)"
+ - type: not-contains
+ value: "explanation"
diff --git a/packages/prompts/promptfoo/emoji-picker/prompt.ts b/packages/prompts/promptfoo/emoji-picker/prompt.ts
new file mode 100644
index 00000000000..e398740e75f
--- /dev/null
+++ b/packages/prompts/promptfoo/emoji-picker/prompt.ts
@@ -0,0 +1,16 @@
+// TypeScript prompt wrapper that uses actual chain implementation
+import { chainPickEmoji } from '@lobechat/prompts';
+
+interface PromptVars {
+ content: string;
+}
+
+export default function generatePrompt({ vars }: { vars: PromptVars }) {
+ const { content } = vars;
+
+ // Use the actual chain function from src
+ const result = chainPickEmoji(content);
+
+ // Return messages array as expected by promptfoo
+ return result.messages || [];
+}
diff --git a/packages/prompts/promptfoo/knowledge-qa/eval.yaml b/packages/prompts/promptfoo/knowledge-qa/eval.yaml
new file mode 100644
index 00000000000..39c5b721498
--- /dev/null
+++ b/packages/prompts/promptfoo/knowledge-qa/eval.yaml
@@ -0,0 +1,89 @@
+description: Test knowledge base Q&A with context retrieval and answer generation
+
+providers:
+ - openai:chat:gpt-5-mini
+ - openai:chat:claude-3-5-haiku-latest
+ - openai:chat:gemini-flash-latest
+ - openai:chat:deepseek-chat
+
+prompts:
+ - file://promptfoo/knowledge-qa/prompt.ts
+
+tests:
+ - vars:
+ context: "React is a JavaScript library for building user interfaces. It was developed by Facebook and is now maintained by Facebook and the community. React uses a virtual DOM to efficiently update and render components. Key features include component-based architecture, JSX syntax, and state management through hooks."
+ query: "What is React and who developed it?"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "The response should accurately explain what React is and mention Facebook as the developer"
+ - type: contains-any
+ value: ["React", "JavaScript", "library", "Facebook"]
+ - type: not-contains
+ value: "I don't know"
+
+ - vars:
+ context: "TypeScript is a strongly typed programming language that builds on JavaScript by adding static type definitions. It was developed by Microsoft. TypeScript code compiles to clean, simple JavaScript code which runs on any browser, Node.js environment, or any JavaScript engine that supports ECMAScript 3 or newer."
+ query: "How does TypeScript relate to JavaScript?"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "The response should explain the relationship between TypeScript and JavaScript, mentioning type definitions"
+ - type: contains-any
+ value: ["TypeScript", "JavaScript", "type", "compiles", "strongly typed"]
+ - type: not-contains
+ value: "不知道"
+
+ - vars:
+ context: "Node.js是一个基于Chrome V8引擎的JavaScript运行时环境。它使用了事件驱动、非阻塞I/O模型,使其轻量而高效。Node.js的包管理器npm是世界上最大的开源库生态系统。"
+ query: "Node.js有什么特点?"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "The response should describe Node.js features in Chinese, mentioning event-driven and non-blocking I/O"
+ - type: contains-any
+ value: ["Node.js", "事件驱动", "非阻塞", "JavaScript", "运行时"]
+ - type: not-contains
+ value: "I don't know"
+
+ - vars:
+ context: "Docker is a containerization platform that allows developers to package applications and their dependencies into lightweight, portable containers. Containers share the OS kernel but run in isolated user spaces. This makes applications more consistent across different environments."
+ query: "How can I deploy my app with Docker?"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "The response should provide helpful information about deploying with Docker based on the containerization context. It should mention containers, packaging, or provide deployment-related guidance."
+ - type: contains-any
+ value: ["Docker", "container", "package", "deploy"]
+
+ - vars:
+ context: "GraphQL is a query language for APIs and a runtime for fulfilling those queries with existing data. Unlike REST APIs that require multiple requests to different endpoints, GraphQL allows clients to request exactly the data they need in a single request."
+ query: "What are the benefits of using GraphQL over REST?"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "The response should compare GraphQL and REST, highlighting GraphQL's advantages such as single request capability or requesting specific data"
+ - type: contains-any
+ value: ["GraphQL", "REST"]
+
+ - vars:
+ context: "Machine learning algorithms can be categorized into supervised, unsupervised, and reinforcement learning. Supervised learning uses labeled data to train models, unsupervised learning finds patterns in unlabeled data, and reinforcement learning learns through trial and error with rewards."
+ query: "Can you explain blockchain technology?"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "The response should indicate that the provided context is about machine learning, not blockchain, and cannot answer the blockchain question based on the context"
+ - type: contains-any
+ value: ["machine learning", "cannot", "不能", "no information", "context", "does not contain"]
+
+ - vars:
+ context: ""
+ query: "How do I set up a web server?"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "The response should provide helpful information about setting up a web server using general knowledge"
+ - type: contains-any
+ value: ["server", "web", "setup", "install", "configure"]
+ - type: not-contains
+ value: "cannot answer"
diff --git a/packages/prompts/promptfoo/knowledge-qa/prompt.ts b/packages/prompts/promptfoo/knowledge-qa/prompt.ts
new file mode 100644
index 00000000000..ce13b2cdd1c
--- /dev/null
+++ b/packages/prompts/promptfoo/knowledge-qa/prompt.ts
@@ -0,0 +1,26 @@
+// TypeScript prompt wrapper that uses actual chain implementation
+import { chainAnswerWithContext } from '@lobechat/prompts';
+
+interface PromptVars {
+ context: string | string[];
+ knowledge?: string | string[];
+ query: string;
+}
+
+export default function generatePrompt({ vars }: { vars: PromptVars }) {
+ const { context, query, knowledge = ['general knowledge'] } = vars;
+
+ // Ensure context and knowledge are arrays
+ const contextArray = Array.isArray(context) ? context : [context];
+ const knowledgeArray = Array.isArray(knowledge) ? knowledge : [knowledge];
+
+ // Use the actual chain function from src
+ const result = chainAnswerWithContext({
+ context: contextArray,
+ knowledge: knowledgeArray,
+ question: query,
+ });
+
+ // Return messages array as expected by promptfoo
+ return result.messages || [];
+}
diff --git a/packages/prompts/promptfoo/language-detection/eval.yaml b/packages/prompts/promptfoo/language-detection/eval.yaml
new file mode 100644
index 00000000000..ffd9d8c7b30
--- /dev/null
+++ b/packages/prompts/promptfoo/language-detection/eval.yaml
@@ -0,0 +1,65 @@
+description: Test language detection accuracy for various text inputs
+
+providers:
+ - openai:chat:gpt-5-mini
+ - openai:chat:claude-3-5-haiku-latest
+ - openai:chat:gemini-flash-latest
+ - openai:chat:deepseek-chat
+
+prompts:
+ - file://promptfoo/language-detection/prompt.ts
+
+tests:
+ - vars:
+ content: "Hello, how are you today? I hope you're having a great day!"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should output a valid locale code for English (e.g., en-US, en-GB, en)"
+ - type: contains-any
+ value: ["en-", "en"]
+
+ - vars:
+ content: "Bonjour, comment allez-vous? J'espère que vous passez une excellente journée!"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should output a valid locale code for French (e.g., fr-FR, fr-CA, fr)"
+ - type: contains-any
+ value: ["fr-", "fr"]
+
+ - vars:
+ content: "你好,你今天怎么样?希望你过得愉快!"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should output a valid locale code for Chinese (e.g., zh-CN, zh-TW, zh)"
+ - type: contains-any
+ value: ["zh-", "zh"]
+
+ - vars:
+ content: "Hola, ¿cómo estás hoy? ¡Espero que tengas un gran día!"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should output a valid locale code for Spanish (e.g., es-ES, es-MX, es)"
+ - type: contains-any
+ value: ["es-", "es"]
+
+ - vars:
+ content: "Привет, как дела сегодня? Надеюсь, у тебя отличный день!"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should output a valid locale code for Russian (e.g., ru-RU, ru)"
+ - type: contains-any
+ value: ["ru-", "ru"]
+
+ - vars:
+ content: "こんにちは、今日はいかがですか?素晴らしい一日をお過ごしください!"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "Should output a valid locale code for Japanese (e.g., ja-JP, ja)"
+ - type: contains-any
+ value: ["ja-", "ja"]
diff --git a/packages/prompts/promptfoo/language-detection/prompt.ts b/packages/prompts/promptfoo/language-detection/prompt.ts
new file mode 100644
index 00000000000..b9eadcea7f8
--- /dev/null
+++ b/packages/prompts/promptfoo/language-detection/prompt.ts
@@ -0,0 +1,16 @@
+// TypeScript prompt wrapper that uses actual chain implementation
+import { chainLangDetect } from '@lobechat/prompts';
+
+interface PromptVars {
+ content: string;
+}
+
+export default function generatePrompt({ vars }: { vars: PromptVars }) {
+ const { content } = vars;
+
+ // Use the actual chain function from src
+ const result = chainLangDetect(content);
+
+ // Return messages array as expected by promptfoo
+ return result.messages || [];
+}
diff --git a/packages/prompts/promptfoo/summary-title/eval.yaml b/packages/prompts/promptfoo/summary-title/eval.yaml
new file mode 100644
index 00000000000..25ca5797654
--- /dev/null
+++ b/packages/prompts/promptfoo/summary-title/eval.yaml
@@ -0,0 +1,85 @@
+description: Test summary title generation for different conversation types
+
+providers:
+ - openai:chat:gpt-5-mini
+ - openai:chat:claude-3-5-haiku-latest
+ - openai:chat:gemini-flash-latest
+ - openai:chat:deepseek-chat
+
+prompts:
+ - file://promptfoo/summary-title/prompt.ts
+
+tests:
+ - vars:
+ messages:
+ - role: "user"
+ content: "How do I install Node.js on my computer?"
+ - role: "assistant"
+ content: "To install Node.js, you can download it from the official website nodejs.org and follow the installation instructions for your operating system."
+ - role: "user"
+ content: "What about using a version manager?"
+ - role: "assistant"
+ content: "Yes! I recommend using nvm (Node Version Manager) which allows you to install and switch between different Node.js versions easily."
+ locale: "en-US"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "The response should be a concise title (10 words or less) that summarizes the conversation about Node.js installation"
+ - type: regex
+ value: "^.{1,50}$" # Title should be between 1-50 characters
+ - type: not-contains
+ value: "标点符号" # Should not contain punctuation as requested in Chinese
+
+ - vars:
+ messages:
+ - role: "user"
+ content: "我想学习做蛋炒饭"
+ - role: "assistant"
+ content: "蛋炒饭是很经典的家常菜!你需要准备鸡蛋、米饭、葱花、盐和生抽等基本材料。"
+ - role: "user"
+ content: "具体步骤是什么?"
+ - role: "assistant"
+ content: "首先打散鸡蛋炒熟盛起,然后下米饭炒散,最后加入鸡蛋和调料炒匀即可。"
+ locale: "zh-CN"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "The response should be a Chinese title summarizing the conversation about fried rice cooking"
+ - type: regex
+ value: "^.{1,30}$" # Chinese titles can be shorter
+ - type: contains-any
+ value: ["蛋炒饭", "做饭", "烹饪", "料理"]
+
+ - vars:
+ messages:
+ - role: "user"
+ content: "Can you help me debug this Python error?"
+ - role: "assistant"
+ content: "Of course! Please share the error message and the relevant code."
+ - role: "user"
+ content: "I'm getting 'AttributeError: 'NoneType' object has no attribute 'split''"
+ - role: "assistant"
+ content: "This error occurs when you're trying to call .split() on a None value. The variable is likely None instead of a string."
+ locale: "en-US"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+
+ value: "The response should be a title about Python debugging or error resolution"
+ - type: contains-any
+ value: ["Python", "debug", "error", "AttributeError", "code"]
+
+ - vars:
+ messages:
+ - role: "user"
+ content: "¿Cómo está el tiempo hoy?"
+ - role: "assistant"
+ content: "No tengo acceso a información meteorológica en tiempo real, pero puedes consultar el clima en tu área usando aplicaciones como Weather.com o tu app del tiempo local."
+ locale: "es-ES"
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+
+ value: "The response should be a Spanish title about weather inquiry"
+ - type: regex
+ value: "^.{1,50}$"
diff --git a/packages/prompts/promptfoo/summary-title/prompt.ts b/packages/prompts/promptfoo/summary-title/prompt.ts
new file mode 100644
index 00000000000..2cbf6ebddf8
--- /dev/null
+++ b/packages/prompts/promptfoo/summary-title/prompt.ts
@@ -0,0 +1,18 @@
+// TypeScript prompt wrapper that uses actual chain implementation
+import { chainSummaryTitle } from '@lobechat/prompts';
+import type { OpenAIChatMessage } from '@lobechat/types';
+
+interface PromptVars {
+ locale: string;
+ messages: OpenAIChatMessage[];
+}
+
+export default function generatePrompt({ vars }: { vars: PromptVars }) {
+ const { messages, locale } = vars;
+
+ // Use the actual chain function from src
+ const result = chainSummaryTitle(messages, locale);
+
+ // Return messages array as expected by promptfoo
+ return result.messages || [];
+}
diff --git a/packages/prompts/promptfoo/translate/eval.yaml b/packages/prompts/promptfoo/translate/eval.yaml
new file mode 100644
index 00000000000..0b0a18bbac5
--- /dev/null
+++ b/packages/prompts/promptfoo/translate/eval.yaml
@@ -0,0 +1,79 @@
+description: Test translation accuracy between different languages
+
+providers:
+ - openai:chat:gpt-5-mini
+ - openai:chat:claude-3-5-haiku-latest
+ - openai:chat:gemini-flash-latest
+ - openai:chat:deepseek-chat
+
+prompts:
+ - file://promptfoo/translate/prompt.ts
+
+tests:
+ - vars:
+ content: 'Hello, how are you?'
+ from: 'en-US'
+ to: 'zh-CN'
+ assert:
+ - type: contains-any
+ value: ['你好', '您好']
+ - type: not-contains
+ value: 'Hello'
+
+ - vars:
+ content: '你好,你怎么样?'
+ from: 'zh-CN'
+ to: 'en-US'
+ assert:
+ - type: contains-any
+ value: ['Hello', 'Hi', 'how are you', 'How are you']
+ - type: not-contains
+ value: '你好'
+
+ - vars:
+ content: 'Je suis content de vous rencontrer'
+ from: 'fr-FR'
+ to: 'en-US'
+ assert:
+ - type: contains-any
+ value: ['pleased', 'happy', 'glad', 'meet', 'meeting']
+ - type: not-contains
+ value: 'Je suis'
+
+ - vars:
+ content: 'The weather is beautiful today'
+ from: 'en-US'
+ to: 'es-ES'
+ assert:
+ - type: contains-any
+ value: ['tiempo', 'clima', 'hermoso', 'bonito', 'hoy', 'día', 'precioso']
+ - type: not-contains
+ value: 'weather'
+
+ - vars:
+ content: 'I love programming with TypeScript'
+ from: 'en-US'
+ to: 'ja-JP'
+ assert:
+ - type: contains
+ value: 'TypeScript' # Technical terms often remain unchanged
+ - type: not-contains
+ value: 'I love'
+
+ - vars:
+ content: 'Machine learning is revolutionizing technology'
+ from: 'en-US'
+ to: 'de-DE'
+ assert:
+ - type: contains-any
+ value: ['Technologie', 'revolutioniert', 'maschinelles', 'Lernen']
+ - type: not-contains
+ value: 'Machine learning'
+
+ - vars:
+ content: 'API_KEY_12345'
+ from: 'en-US'
+ to: 'zh-CN'
+ assert:
+ - type: contains
+ value: 'API_KEY_12345'
diff --git a/packages/prompts/promptfoo/translate/prompt.ts b/packages/prompts/promptfoo/translate/prompt.ts
new file mode 100644
index 00000000000..98e3878cbb3
--- /dev/null
+++ b/packages/prompts/promptfoo/translate/prompt.ts
@@ -0,0 +1,18 @@
+// TypeScript prompt wrapper that uses actual chain implementation
+import { chainTranslate } from '@lobechat/prompts';
+
+interface PromptVars {
+ content: string;
+ from: string;
+ to: string;
+}
+
+export default function generatePrompt({ vars }: { vars: PromptVars }) {
+ const { content, to } = vars;
+
+ // Use the actual chain function from src
+ const result = chainTranslate(content, to);
+
+ // Return messages array as expected by promptfoo
+ return result.messages || [];
+}
diff --git a/packages/prompts/promptfooconfig.yaml b/packages/prompts/promptfooconfig.yaml
new file mode 100644
index 00000000000..6bf4716eaa6
--- /dev/null
+++ b/packages/prompts/promptfooconfig.yaml
@@ -0,0 +1,35 @@
+description: LobeHub Prompts Testing Suite
+
+# Test configurations - run all prompt tests
+testPaths:
+ - promptfoo/translate/eval.yaml
+ - promptfoo/summary-title/eval.yaml
+ - promptfoo/language-detection/eval.yaml
+ - promptfoo/emoji-picker/eval.yaml
+ - promptfoo/knowledge-qa/eval.yaml
+
+# Output configuration
+outputPath: promptfoo-results.json
+
+# Default test settings
+defaultTest:
+ assert:
+ - type: llm-rubric
+ provider: openai:gpt-5-mini
+ value: "The response should be relevant and well-formatted"
+ - type: cost
+ threshold: 0.01 # Maximum cost per test in USD
+
+# Environment variables for API keys
+env:
+ OPENAI_API_KEY: ${OPENAI_API_KEY}
+ ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY}
+
+# Evaluation settings
+evaluateOptions:
+ maxConcurrency: 5
+ delay: 100
+
+# TypeScript support
+transforms:
+ - "typescript"
diff --git a/packages/prompts/src/chains/__tests__/__snapshots__/answerWithContext.test.ts.snap b/packages/prompts/src/chains/__tests__/__snapshots__/answerWithContext.test.ts.snap
new file mode 100644
index 00000000000..fb8598298ee
--- /dev/null
+++ b/packages/prompts/src/chains/__tests__/__snapshots__/answerWithContext.test.ts.snap
@@ -0,0 +1,164 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`chainAnswerWithContext > should filter out empty context strings 1`] = `
+{
+ "messages": [
+ {
+ "content": "You are a helpful assistant specialized in Test. Your task is to answer questions based on the provided context passages.
+
+IMPORTANT RULES:
+- First, check if the context is relevant to the question topic
+- If the context is about a COMPLETELY DIFFERENT topic than the question:
+ * State what topic the context is about
+ * Clearly state "The provided context does not contain information about [question topic]"
+ * Do NOT answer using your general knowledge
+- If the context is related to the question topic (even if information is limited):
+ * ALWAYS use the context information as a foundation
+ * You SHOULD supplement with your general knowledge to provide a complete, helpful answer
+ * For "how to" questions, MUST provide practical, actionable steps combining context + your expertise
+ * The context provides the topic relevance - you provide the comprehensive answer
+ * Example: If context mentions "Docker is for containerization", and question is "How to deploy with Docker?", you should explain deployment steps using your knowledge
+- Answer in the same language as the question
+- Use markdown formatting for better readability
+
+The provided context passages:
+
+<context>
+Valid context
+Another valid context
+</context>
+
+Question to answer:
+
+Test question",
+ "role": "user",
+ },
+ ],
+}
+`;
+
+exports[`chainAnswerWithContext > should generate correct payload with context and knowledge 1`] = `
+{
+ "messages": [
+ {
+ "content": "You are a helpful assistant specialized in AI/Machine Learning. Your task is to answer questions based on the provided context passages.
+
+IMPORTANT RULES:
+- First, check if the context is relevant to the question topic
+- If the context is about a COMPLETELY DIFFERENT topic than the question:
+ * State what topic the context is about
+ * Clearly state "The provided context does not contain information about [question topic]"
+ * Do NOT answer using your general knowledge
+- If the context is related to the question topic (even if information is limited):
+ * ALWAYS use the context information as a foundation
+ * You SHOULD supplement with your general knowledge to provide a complete, helpful answer
+ * For "how to" questions, MUST provide practical, actionable steps combining context + your expertise
+ * The context provides the topic relevance - you provide the comprehensive answer
+ * Example: If context mentions "Docker is for containerization", and question is "How to deploy with Docker?", you should explain deployment steps using your knowledge
+- Answer in the same language as the question
+- Use markdown formatting for better readability
+
+The provided context passages:
+
+<context>
+Context passage 1
+Context passage 2
+</context>
+
+Question to answer:
+
+What is artificial intelligence?",
+ "role": "user",
+ },
+ ],
+}
+`;
+
+exports[`chainAnswerWithContext > should handle empty context array 1`] = `
+{
+ "messages": [
+ {
+ "content": "You are a helpful assistant specialized in AI. Please answer the following question using your knowledge.
+
+Answer in the same language as the question and use markdown formatting for better readability.
+
+Question to answer:
+
+What is AI?",
+ "role": "user",
+ },
+ ],
+}
+`;
+
+exports[`chainAnswerWithContext > should handle multiple knowledge areas 1`] = `
+{
+ "messages": [
+ {
+ "content": "You are a helpful assistant specialized in AI/ML/NLP/Computer Vision. Your task is to answer questions based on the provided context passages.
+
+IMPORTANT RULES:
+- First, check if the context is relevant to the question topic
+- If the context is about a COMPLETELY DIFFERENT topic than the question:
+ * State what topic the context is about
+ * Clearly state "The provided context does not contain information about [question topic]"
+ * Do NOT answer using your general knowledge
+- If the context is related to the question topic (even if information is limited):
+ * ALWAYS use the context information as a foundation
+ * You SHOULD supplement with your general knowledge to provide a complete, helpful answer
+ * For "how to" questions, MUST provide practical, actionable steps combining context + your expertise
+ * The context provides the topic relevance - you provide the comprehensive answer
+ * Example: If context mentions "Docker is for containerization", and question is "How to deploy with Docker?", you should explain deployment steps using your knowledge
+- Answer in the same language as the question
+- Use markdown formatting for better readability
+
+The provided context passages:
+
+<context>
+Context
+</context>
+
+Question to answer:
+
+Tell me about these fields",
+ "role": "user",
+ },
+ ],
+}
+`;
+
+exports[`chainAnswerWithContext > should handle single knowledge area 1`] = `
+{
+ "messages": [
+ {
+ "content": "You are a helpful assistant specialized in Technology. Your task is to answer questions based on the provided context passages.
+
+IMPORTANT RULES:
+- First, check if the context is relevant to the question topic
+- If the context is about a COMPLETELY DIFFERENT topic than the question:
+ * State what topic the context is about
+ * Clearly state "The provided context does not contain information about [question topic]"
+ * Do NOT answer using your general knowledge
+- If the context is related to the question topic (even if information is limited):
+ * ALWAYS use the context information as a foundation
+ * You SHOULD supplement with your general knowledge to provide a complete, helpful answer
+ * For "how to" questions, MUST provide practical, actionable steps combining context + your expertise
+ * The context provides the topic relevance - you provide the comprehensive answer
+ * Example: If context mentions "Docker is for containerization", and question is "How to deploy with Docker?", you should explain deployment steps using your knowledge
+- Answer in the same language as the question
+- Use markdown formatting for better readability
+
+The provided context passages:
+
+<context>
+Single context
+</context>
+
+Question to answer:
+
+How does it work?",
+ "role": "user",
+ },
+ ],
+}
+`;
diff --git a/packages/prompts/src/chains/__tests__/__snapshots__/pickEmoji.test.ts.snap b/packages/prompts/src/chains/__tests__/__snapshots__/pickEmoji.test.ts.snap
new file mode 100644
index 00000000000..11d94748734
--- /dev/null
+++ b/packages/prompts/src/chains/__tests__/__snapshots__/pickEmoji.test.ts.snap
@@ -0,0 +1,58 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`chainPickEmoji > should return a payload with the correct structure and embedded user content 1`] = `
+{
+ "messages": [
+ {
+ "content": "You are an emoji expert who selects the most appropriate emoji to represent concepts, emotions, or topics.
+
+Rules:
+- Output ONLY a single emoji (1-2 characters maximum)
+- Focus on the CONTENT meaning, not the language it's written in
+- Choose an emoji that best represents the core topic, activity, or subject matter
+- Prioritize topic-specific emojis over generic emotion emojis (e.g., for sports, use 🏃 instead of 😅)
+- For work/projects, use work-related emojis (💼, 🚀, 💪) not cultural symbols
+- For pure emotions without specific topics, use face emojis (happy: 🎉, sad: 😢, thinking: 🤔)
+- For activities or subjects, use object or symbol emojis that represent the main topic
+- No explanations or additional text",
+ "role": "system",
+ },
+ {
+ "content": "I am a copywriting master who helps name design and art works with literary depth",
+ "role": "user",
+ },
+ {
+ "content": "✒️",
+ "role": "assistant",
+ },
+ {
+ "content": "I am a code wizard who converts JavaScript code to TypeScript",
+ "role": "user",
+ },
+ {
+ "content": "🧙‍♂️",
+ "role": "assistant",
+ },
+ {
+ "content": "I just got a promotion at work",
+ "role": "user",
+ },
+ {
+ "content": "🎉",
+ "role": "assistant",
+ },
+ {
+ "content": "I am a business plan expert who helps with startup strategies and marketing",
+ "role": "user",
+ },
+ {
+ "content": "🚀",
+ "role": "assistant",
+ },
+ {
+ "content": "你是一名星际探索者",
+ "role": "user",
+ },
+ ],
+}
+`;
diff --git a/packages/prompts/src/chains/__tests__/__snapshots__/summaryTitle.test.ts.snap b/packages/prompts/src/chains/__tests__/__snapshots__/summaryTitle.test.ts.snap
new file mode 100644
index 00000000000..7a4ae9eaea5
--- /dev/null
+++ b/packages/prompts/src/chains/__tests__/__snapshots__/summaryTitle.test.ts.snap
@@ -0,0 +1,26 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`chainSummaryTitle > should use the default model if the token count is below the GPT-3.5 limit 1`] = `
+{
+ "messages": [
+ {
+ "content": "You are a professional conversation summarizer. Generate a concise title that captures the essence of the conversation.
+
+Rules:
+- Output ONLY the title text, no explanations or additional context
+- Maximum 10 words
+- Maximum 50 characters
+- No punctuation marks
+- Use the language specified by the locale code: en-US
+- The title should accurately reflect the main topic of the conversation
+- Keep it short and to the point",
+ "role": "system",
+ },
+ {
+ "content": "assistant: Hello, how can I assist you?
+user: I need help with my account.",
+ "role": "user",
+ },
+ ],
+}
+`;
diff --git a/packages/prompts/src/chains/__tests__/__snapshots__/translate.test.ts.snap b/packages/prompts/src/chains/__tests__/__snapshots__/translate.test.ts.snap
new file mode 100644
index 00000000000..e0530869b5b
--- /dev/null
+++ b/packages/prompts/src/chains/__tests__/__snapshots__/translate.test.ts.snap
@@ -0,0 +1,22 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`chainTranslate > should create a payload with system and user messages for translation 1`] = `
+{
+ "messages": [
+ {
+ "content": "You are a professional translator. Translate the input text to zh-CN.
+
+Rules:
+- Output ONLY the translated text, no explanations or additional context
+- Preserve technical terms, code identifiers, API keys, and proper nouns exactly as they appear
+- Maintain the original formatting and structure
+- Use natural, idiomatic expressions in the target language",
+ "role": "system",
+ },
+ {
+ "content": "This is a test sentence.",
+ "role": "user",
+ },
+ ],
+}
+`;
diff --git a/packages/prompts/src/chains/__tests__/answerWithContext.test.ts b/packages/prompts/src/chains/__tests__/answerWithContext.test.ts
index 000cc722fa4..bbc42c6f6e7 100644
--- a/packages/prompts/src/chains/__tests__/answerWithContext.test.ts
+++ b/packages/prompts/src/chains/__tests__/answerWithContext.test.ts
@@ -3,98 +3,53 @@ import { describe, expect, it } from 'vitest';
import { chainAnswerWithContext } from '../answerWithContext';
describe('chainAnswerWithContext', () => {
- it('should generate correct chat payload with context and knowledge', () => {
- const testParams = {
+ it('should generate correct payload with context and knowledge', () => {
+ const result = chainAnswerWithContext({
context: ['Context passage 1', 'Context passage 2'],
knowledge: ['AI', 'Machine Learning'],
question: 'What is artificial intelligence?',
- };
+ });
- const result = chainAnswerWithContext(testParams);
-
- expect(result.messages).toHaveLength(1);
- expect(result.messages![0].role).toBe('user');
- expect(result.messages![0].content).toContain('AI/Machine Learning');
- expect(result.messages![0].content).toContain('Context passage 1');
- expect(result.messages![0].content).toContain('Context passage 2');
- expect(result.messages![0].content).toContain('What is artificial intelligence?');
+ expect(result).toMatchSnapshot();
});
it('should handle single knowledge area', () => {
- const testParams = {
+ const result = chainAnswerWithContext({
context: ['Single context'],
knowledge: ['Technology'],
question: 'How does it work?',
- };
-
- const result = chainAnswerWithContext(testParams);
+ });
- expect(result.messages![0].content).toContain('Technology');
+ expect(result).toMatchSnapshot();
});
it('should handle multiple knowledge areas', () => {
- const testParams = {
+ const result = chainAnswerWithContext({
context: ['Context'],
knowledge: ['AI', 'ML', 'NLP', 'Computer Vision'],
question: 'Tell me about these fields',
- };
+ });
- const result = chainAnswerWithContext(testParams);
-
- expect(result.messages![0].content).toContain('AI/ML/NLP/Computer Vision');
+ expect(result).toMatchSnapshot();
});
it('should handle empty context array', () => {
- const testParams = {
+ const result = chainAnswerWithContext({
context: [],
knowledge: ['AI'],
question: 'What is AI?',
- };
-
- const result = chainAnswerWithContext(testParams);
+ });
- expect(result.messages![0].content).toContain('<Context>');
- expect(result.messages![0].content).toContain('</Context>');
+ expect(result).toMatchSnapshot();
});
- it('should include proper context formatting', () => {
- const testParams = {
- context: ['First passage', 'Second passage'],
+ it('should filter out empty context strings', () => {
+ const result = chainAnswerWithContext({
+ context: ['Valid context', '', ' ', 'Another valid context'],
knowledge: ['Test'],
question: 'Test question',
- };
-
- const result = chainAnswerWithContext(testParams);
-
- expect(result.messages![0].content).toContain(
- '<Context>\nFirst passage\nSecond passage\n</Context>',
- );
- });
-
- it('should include proper instructions about using passages', () => {
- const testParams = {
- context: ['Context'],
- knowledge: ['Knowledge'],
- question: 'Question',
- };
-
- const result = chainAnswerWithContext(testParams);
- const content = result.messages![0].content;
-
- expect(content).toContain('passages might not be relevant');
- expect(content).toContain('please only use the passages that are relevant');
- expect(content).toContain('answer using your knowledge');
- });
-
- it('should include markdown formatting instruction', () => {
- const testParams = {
- context: ['Context'],
- knowledge: ['Knowledge'],
- question: 'Question',
- };
-
- const result = chainAnswerWithContext(testParams);
+ });
- expect(result.messages![0].content).toContain('follow markdown syntax');
+ expect(result).toMatchSnapshot();
});
});
diff --git a/packages/prompts/src/chains/__tests__/pickEmoji.test.ts b/packages/prompts/src/chains/__tests__/pickEmoji.test.ts
index 7567ff7f74d..c1d7edc9816 100644
--- a/packages/prompts/src/chains/__tests__/pickEmoji.test.ts
+++ b/packages/prompts/src/chains/__tests__/pickEmoji.test.ts
@@ -1,46 +1,11 @@
-import { ChatStreamPayload } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import { chainPickEmoji } from '../pickEmoji';
-// 描述测试块
describe('chainPickEmoji', () => {
- // 测试用例:验证函数返回的结构
it('should return a payload with the correct structure and embedded user content', () => {
- // 用户输入的内容
- const userContent = '你是一名星际探索者';
+ const result = chainPickEmoji('你是一名星际探索者');
- // 预期的返回值结构
- const expectedPayload: Partial<ChatStreamPayload> = {
- messages: [
- {
- content:
- '你是一名擅长进行概念抽象的设计师与 Emoji 专家,你需要根据角色能力的描述抽象出一个表达物理实体的概念 Emoji 作为角色头像, 格式要求如下:\n输入: {文本作为JSON引用字符串}\n输出: {一个Emoji}',
- role: 'system',
- },
- {
- content: `输入: {你是一名文案大师,帮我为一些设计 / 艺术作品起名,名字需要有文学内涵,注重精炼和赋子意境,表达作品的情景氛国,使名称既简洁又富有诗意。}`,
- role: 'user',
- },
- { content: '✒️', role: 'assistant' },
- {
- content: `输入: {你是一名代码巫师,请将下面的代码转成 ts,不要修改实现。如果原本 js 中没有定义的全局变量,需要补充 declare 的类型声明。}`,
- role: 'user',
- },
- { content: '🧙‍♂️', role: 'assistant' },
- {
- content: `输入: {你是一名创业计划撰写专家,可以提供包括创意名称、简短的标语、目标用户画像、用户痛点、主要价值主张、销售/营销渠道、收入流、成本结构等计划生成。}`,
- role: 'user',
- },
- { content: '🚀', role: 'assistant' },
- { content: `输入: {${userContent}}`, role: 'user' },
- ],
- };
-
- // 执行函数并获取结果
- const result = chainPickEmoji(userContent);
-
- // 断言结果是否符合预期
- expect(result).toEqual(expectedPayload);
+ expect(result).toMatchSnapshot();
});
});
diff --git a/packages/prompts/src/chains/__tests__/summaryTitle.test.ts b/packages/prompts/src/chains/__tests__/summaryTitle.test.ts
index ec46bf829e0..f1626b003b7 100644
--- a/packages/prompts/src/chains/__tests__/summaryTitle.test.ts
+++ b/packages/prompts/src/chains/__tests__/summaryTitle.test.ts
@@ -11,25 +11,11 @@ describe('chainSummaryTitle', () => {
{ content: 'I need help with my account.', role: 'user' },
];
const currentLanguage = 'en-US';
- const tokenCount = 10000; // Arbitrary token count below the GPT-3.5 limit
// Act
- const result = await chainSummaryTitle(messages, currentLanguage);
+ const result = chainSummaryTitle(messages, currentLanguage);
// Assert
- expect(result).toEqual({
- messages: [
- {
- content: '你是一名擅长会话的助理,你需要将用户的会话总结为 10 个字以内的标题',
- role: 'system',
- },
- {
- content: `assistant: Hello, how can I assist you?\nuser: I need help with my account.
-
-请总结上述对话为10个字以内的标题,不需要包含标点符号,输出语言语种为:${currentLanguage}`,
- role: 'user',
- },
- ],
- });
+ expect(result).toMatchSnapshot();
});
});
diff --git a/packages/prompts/src/chains/__tests__/translate.test.ts b/packages/prompts/src/chains/__tests__/translate.test.ts
index 0a0e4fb4062..8e3bad65e34 100644
--- a/packages/prompts/src/chains/__tests__/translate.test.ts
+++ b/packages/prompts/src/chains/__tests__/translate.test.ts
@@ -12,17 +12,6 @@ describe('chainTranslate', () => {
const result = chainTranslate(content, targetLang);
// Assert
- expect(result).toEqual({
- messages: [
- {
- content: '你是一名擅长翻译的助理,你需要将输入的语言翻译为目标语言',
- role: 'system',
- },
- {
- content: `请将以下内容 ${content},翻译为 ${targetLang} `,
- role: 'user',
- },
- ],
- });
+ expect(result).toMatchSnapshot();
});
});
diff --git a/packages/prompts/src/chains/answerWithContext.ts b/packages/prompts/src/chains/answerWithContext.ts
index fddb5ca6394..269fe497f70 100644
--- a/packages/prompts/src/chains/answerWithContext.ts
+++ b/packages/prompts/src/chains/answerWithContext.ts
@@ -1,33 +1,57 @@
import { ChatStreamPayload } from '@lobechat/types';
+interface AnswerWithContext {
+ context: string[];
+ knowledge: string[];
+ question: string;
+}
export const chainAnswerWithContext = ({
context,
knowledge,
question,
-}: {
- context: string[];
- knowledge: string[];
- question: string;
-}): Partial<ChatStreamPayload> => ({
- messages: [
- {
- content: `You are also a helpful assistant good answering questions related to ${knowledge.join('/')}. And you'll be provided with a question and several passages that might be relevant. And currently your task is to provide answer based on the question and passages.
+}: AnswerWithContext): Partial<ChatStreamPayload> => {
+ const filteredContext = context.filter((c) => c.trim());
+ const hasContext = filteredContext.length > 0;
+
+ return {
+ messages: [
+ {
+ content: hasContext
+ ? `You are a helpful assistant specialized in ${knowledge.join('/')}. Your task is to answer questions based on the provided context passages.
+
+IMPORTANT RULES:
+- First, check if the context is relevant to the question topic
+- If the context is about a COMPLETELY DIFFERENT topic than the question:
+ * State what topic the context is about
+ * Clearly state "The provided context does not contain information about [question topic]"
+ * Do NOT answer using your general knowledge
+- If the context is related to the question topic (even if information is limited):
+ * ALWAYS use the context information as a foundation
+ * You SHOULD supplement with your general knowledge to provide a complete, helpful answer
+ * For "how to" questions, MUST provide practical, actionable steps combining context + your expertise
+ * The context provides the topic relevance - you provide the comprehensive answer
+ * Example: If context mentions "Docker is for containerization", and question is "How to deploy with Docker?", you should explain deployment steps using your knowledge
+- Answer in the same language as the question
+- Use markdown formatting for better readability
+
+The provided context passages:
-Note that passages might not be relevant to the question, please only use the passages that are relevant. Or if there is no relevant passage, please answer using your knowledge.
+<context>
+${filteredContext.join('\n')}
+</context>
-Answer should use the same original language as the question and follow markdown syntax.
+Question to answer:
-The provided passages as context:
+${question}`
+ : `You are a helpful assistant specialized in ${knowledge.join('/')}. Please answer the following question using your knowledge.
-<Context>
-${context.join('\n')}
-</Context>
+Answer in the same language as the question and use markdown formatting for better readability.
-The question to answer is:
+Question to answer:
-${question}
-`,
- role: 'user',
- },
- ],
-});
+${question}`,
+ role: 'user',
+ },
+ ],
+ };
+};
diff --git a/packages/prompts/src/chains/pickEmoji.ts b/packages/prompts/src/chains/pickEmoji.ts
index 64f1ab79a8c..d8d2168f304 100644
--- a/packages/prompts/src/chains/pickEmoji.ts
+++ b/packages/prompts/src/chains/pickEmoji.ts
@@ -7,25 +7,39 @@ import { ChatStreamPayload } from '@lobechat/types';
export const chainPickEmoji = (content: string): Partial<ChatStreamPayload> => ({
messages: [
{
- content:
- '你是一名擅长进行概念抽象的设计师与 Emoji 专家,你需要根据角色能力的描述抽象出一个表达物理实体的概念 Emoji 作为角色头像, 格式要求如下:\n输入: {文本作为JSON引用字符串}\n输出: {一个Emoji}',
+ content: `You are an emoji expert who selects the most appropriate emoji to represent concepts, emotions, or topics.
+
+Rules:
+- Output ONLY a single emoji (1-2 characters maximum)
+- Focus on the CONTENT meaning, not the language it's written in
+- Choose an emoji that best represents the core topic, activity, or subject matter
+- Prioritize topic-specific emojis over generic emotion emojis (e.g., for sports, use 🏃 instead of 😅)
+- For work/projects, use work-related emojis (💼, 🚀, 💪) not cultural symbols
+- For pure emotions without specific topics, use face emojis (happy: 🎉, sad: 😢, thinking: 🤔)
+- For activities or subjects, use object or symbol emojis that represent the main topic
+- No explanations or additional text`,
role: 'system',
},
{
- content: `输入: {你是一名文案大师,帮我为一些设计 / 艺术作品起名,名字需要有文学内涵,注重精炼和赋子意境,表达作品的情景氛国,使名称既简洁又富有诗意。}`,
+ content: 'I am a copywriting master who helps name design and art works with literary depth',
role: 'user',
},
{ content: '✒️', role: 'assistant' },
{
- content: `输入: {你是一名代码巫师,请将下面的代码转成 ts,不要修改实现。如果原本 js 中没有定义的全局变量,需要补充 declare 的类型声明。}`,
+ content: 'I am a code wizard who converts JavaScript code to TypeScript',
role: 'user',
},
{ content: '🧙‍♂️', role: 'assistant' },
{
- content: `输入: {你是一名创业计划撰写专家,可以提供包括创意名称、简短的标语、目标用户画像、用户痛点、主要价值主张、销售/营销渠道、收入流、成本结构等计划生成。}`,
+ content: 'I just got a promotion at work',
+ role: 'user',
+ },
+ { content: '🎉', role: 'assistant' },
+ {
+ content: 'I am a business plan expert who helps with startup strategies and marketing',
role: 'user',
},
{ content: '🚀', role: 'assistant' },
- { content: `输入: {${content}}`, role: 'user' },
+ { content, role: 'user' },
],
});
diff --git a/packages/prompts/src/chains/summaryTitle.ts b/packages/prompts/src/chains/summaryTitle.ts
index ab11849aa3f..5c9206bec80 100644
--- a/packages/prompts/src/chains/summaryTitle.ts
+++ b/packages/prompts/src/chains/summaryTitle.ts
@@ -3,19 +3,24 @@ import { ChatStreamPayload, OpenAIChatMessage } from '@/types/openai/chat';
export const chainSummaryTitle = (
messages: OpenAIChatMessage[],
locale: string,
-): Partial<ChatStreamPayload> => {
- return {
- messages: [
- {
- content: '你是一名擅长会话的助理,你需要将用户的会话总结为 10 个字以内的标题',
- role: 'system',
- },
- {
- content: `${messages.map((message) => `${message.role}: ${message.content}`).join('\n')}
+): Partial<ChatStreamPayload> => ({
+ messages: [
+ {
+ content: `You are a professional conversation summarizer. Generate a concise title that captures the essence of the conversation.
-请总结上述对话为10个字以内的标题,不需要包含标点符号,输出语言语种为:${locale}`,
- role: 'user',
- },
- ],
- };
-};
+Rules:
+- Output ONLY the title text, no explanations or additional context
+- Maximum 10 words
+- Maximum 50 characters
+- No punctuation marks
+- Use the language specified by the locale code: ${locale}
+- The title should accurately reflect the main topic of the conversation
+- Keep it short and to the point`,
+ role: 'system',
+ },
+ {
+ content: messages.map((message) => `${message.role}: ${message.content}`).join('\n'),
+ role: 'user',
+ },
+ ],
+});
diff --git a/packages/prompts/src/chains/translate.ts b/packages/prompts/src/chains/translate.ts
index 51cbfb11537..de20479baef 100644
--- a/packages/prompts/src/chains/translate.ts
+++ b/packages/prompts/src/chains/translate.ts
@@ -6,11 +6,17 @@ export const chainTranslate = (
): Partial<ChatStreamPayload> => ({
messages: [
{
- content: '你是一名擅长翻译的助理,你需要将输入的语言翻译为目标语言',
+ content: `You are a professional translator. Translate the input text to ${targetLang}.
+
+Rules:
+- Output ONLY the translated text, no explanations or additional context
+- Preserve technical terms, code identifiers, API keys, and proper nouns exactly as they appear
+- Maintain the original formatting and structure
+- Use natural, idiomatic expressions in the target language`,
role: 'system',
},
{
- content: `请将以下内容 ${content},翻译为 ${targetLang} `,
+ content,
role: 'user',
},
],