Skip to content

Conversation

@USERNAME-STOCK
Copy link

@USERNAME-STOCK USERNAME-STOCK commented Nov 8, 2025

PR Type

Enhancement


Description

  • Restructured all AI prompts with hybrid markdown + XML format for clarity and consistency

    • Added explicit role definitions, task descriptions, and step-by-step instructions
    • Implemented structured output format templates with constraints to prevent hallucination
  • Simplified build process to Chrome/Chromium only with English locale

    • Removed Firefox build output and minimal build variants
    • Disabled webpack concatenateModules for better debugging
  • Enhanced selection tools (Explain, Translate, Summary, Polish, Code, Sentiment) with detailed instructions

  • Improved GitHub, arXiv, YouTube, Bilibili analyzers with structured prompt formats

  • Streamlined language configuration to English only


Diagram Walkthrough

flowchart LR
  A["Old Simple Prompts"] -->|"Restructure with<br/>Markdown + XML"| B["Structured Prompts<br/>with Role/Task/Instructions"]
  C["Multi-platform Build<br/>Firefox + Chrome"] -->|"Simplify to<br/>Chrome only"| D["Single Chromium<br/>Output"]
  E["Multi-language Support<br/>12+ locales"] -->|"Reduce to<br/>English only"| F["English-only<br/>Configuration"]
  B --> G["Better AI Response<br/>Quality & Consistency"]
  D --> H["Faster Build<br/>Process"]
  F --> I["Reduced<br/>Complexity"]
Loading

File Walkthrough

Relevant files
Enhancement
8 files
index.mjs
Rewrite selection tools with structured prompts                   
+471/-35
index.mjs
Enhance GitHub issue/PR analyzer prompts                                 
+164/-26
shared.mjs
Upgrade system prompts with detailed guidelines                   
+140/-8 
index.jsx
Restructure search engine handler prompt                                 
+77/-7   
index.mjs
Add structured arXiv paper analyzer prompt                             
+71/-8   
index.mjs
Improve page summarization with structured format               
+82/-1   
index.mjs
Enhance YouTube video summarizer prompt                                   
+60/-4   
index.mjs
Enhance Bilibili video summarizer prompt                                 
+60/-4   
Configuration changes
3 files
build.mjs
Simplify build to Chrome only, disable concatenateModules
+3/-25   
index.mjs
Set default model and simplify language detection               
+3/-4     
language.mjs
Reduce language list to English only                                         
+5/-10   
Additional files
18 files
README_IN.md +0/-140 
README_JA.md +0/-138 
README_TR.md +0/-141 
README_ZH.md +0/-143 
package.json +0/-1     
main.json +0/-163 
main.json +0/-163 
main.json +0/-163 
main.json +0/-163 
main.json +0/-163 
main.json +0/-163 
main.json +0/-163 
main.json +0/-163 
resources.mjs +0/-48   
main.json +0/-163 
main.json +0/-163 
main.json +0/-170 
main.json +0/-165 

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced prompt structures with standardized formatting across AI interactions for improved clarity and consistency.
  • Chores

    • Reduced language support to English only; removed localization files for multiple languages.
    • Simplified build process to Chromium only; removed Firefox and Safari support.
    • Set default model to Claude Web Free.
    • Removed non-English documentation.

…iled instructions

Upgraded all AI prompts throughout the extension to use a hybrid markdown + XML
structure with explicit role definitions, task descriptions, instructions, output
formats, and constraints. This provides better clarity and more consistent,
high-quality responses from AI models.

Changes:
- YouTube/Bilibili video summarizers: Added structured output format with
  overview, main topics, key takeaways, and important details sections
- GitHub analyzer: Separate improved prompts for issues/PRs and commits with
  conventional commit message format support
- arXiv paper analyzer: Added research domain classification, methodology
  breakdown, and relevance keywords
- Search engine handler: Enhanced with search intent classification and
  structured answer format
- Selection tools (Explain, Translate, Summary, Polish, Code, Sentiment):
  Complete rewrite with detailed instructions and structured outputs
- Menu tools: Improved page summarization with content type identification
- System prompts: Enhanced base prompts for Chat/Completion/Custom APIs with
  explicit capabilities, guidelines, and constraints

All prompts now include:
- Clear role and task definitions
- Step-by-step instructions
- Structured output format templates
- Explicit constraints to prevent hallucination
- Multi-language support where appropriate

This addresses the need for more reliable, structured AI responses across all
extension features.
…locale

Streamlined the build configuration to reduce complexity and build time:

Build Simplification:
- Removed Firefox build output (kept Chrome/Chromium only)
- Disabled webpack concatenateModules for better debugging
- Removed minimal build variants (without-katex-and-tiktoken)
- Removed Safari build script from package.json
- Build now produces single chromium/ output directory with full features

Locale Simplification:
- Removed all non-English locales (de, es, fr, in, it, ja, ko, pt, ru, tr, zh-hans, zh-hant)
- Kept only English (en) locale
- Updated languageList to only include auto and en
- Simplified getNavigatorLanguage() to always return 'en'
- Removed language-specific model defaults (Chinese → Moonshot)
- Updated resources.mjs to import only English translations

Documentation:
- Removed non-English README files (README_IN.md, README_JA.md, README_TR.md, README_ZH.md)
- Kept only main README.md

Benefits:
- Faster build times (single target, no variants)
- Smaller codebase (~13 locale directories removed)
- Easier maintenance (one browser target)
- Better debuggability (no concatenation)
- Clearer output structure

Build output: build/chromium/ and build/chromium.zip
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 8, 2025

Walkthrough

This PR removes internationalization support for 11 non-English languages by deleting locale files and READMEs, simplifies the build process to Chromium-only, and restructures prompt templates across multiple modules to use detailed, multi-section formatted instructions instead of concise strings.

Changes

Cohort / File(s) Summary
Localization Removal
src/_locales/de/main.json, src/_locales/es/main.json, src/_locales/fr/main.json, src/_locales/in/main.json, src/_locales/it/main.json, src/_locales/ja/main.json, src/_locales/ko/main.json, src/_locales/pt/main.json, src/_locales/ru/main.json, src/_locales/tr/main.json, src/_locales/zh-hans/main.json, src/_locales/zh-hant/main.json
Deleted all non-English locale translation files. Updated src/_locales/resources.mjs to export only English (en) translations, removing references to de, es, fr, in, it, ja, ko, pt, ru, tr, zh, and zhHant.
Documentation
README_IN.md, README_JA.md, README_TR.md, README_ZH.md
Removed language-specific README files for Indonesian, Japanese, Turkish, and Chinese.
Build System
build.mjs, package.json
Removed Firefox output generation and multi-variant build logic; retained Chromium-only build. Forced webpack concatenation to false. Removed build:safari script.
Configuration Hardcoding
src/config/index.mjs, src/config/language.mjs
Hardcoded default model to 'claude2WebFree'; removed language-based selection. Simplified getNavigatorLanguage() to always return 'en'. Changed languageList to a static object containing only auto and en.
Prompt Restructuring
src/content-script/index.jsx, src/content-script/menu-tools/index.mjs, src/content-script/selection-tools/index.mjs
Replaced simple prompt strings with comprehensive, multi-section structured prompts (Role, Task, Instructions, Output Format). Selection-tools functions converted from sync wrappers to async functions with dynamic language fetching.
Site Adapter Prompt Updates
src/content-script/site-adapters/arxiv/index.mjs, src/content-script/site-adapters/bilibili/index.mjs, src/content-script/site-adapters/github/index.mjs, src/content-script/site-adapters/youtube/index.mjs
Replaced inline prompt strings with detailed, structured prompts including explicit role, task, instructions, input data blocks, and formatted output schemas.
Service Prompt Updates
src/services/apis/shared.mjs
Replaced simple prompt base functions with large, structured Markdown-like prompts covering Role, Capabilities, Guidelines, Communication Style, Constraints, and Response Approach.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Areas requiring extra attention:
    • Configuration hardcoding in src/config/index.mjs and src/config/language.mjs significantly alters default behavior and language selection logic; verify downstream impact on model selection and locale fallbacks.
    • Build system simplification in build.mjs removes Firefox variant builds; confirm no critical functionality or platform support is lost.
    • Async function signature changes in src/content-script/selection-tools/index.mjs from sync to async; verify all call sites properly handle the Promise return values.
    • Multiple prompt restructuring changes follow consistent patterns but span diverse modules; spot-check a few examples to ensure consistency and proper integration with downstream consumers.

Possibly related PRs

  • Refine built-in prompts #866: Edits built-in prompt text in the same content-script areas (selection-tools and menu-tools), updating genPrompt and inputQuery-style prompt templates.

Suggested labels

Review effort 2/5

Poem

🐰 Languages fade but English stands tall,
Firefox bows out, Chrome takes the call,
Prompts now speak in structured delight,
With roles and tasks formatted right,
One model remains, the build runs clean—
The simplest version ever seen!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'simplified' is vague and generic, providing no meaningful information about the extensive changes made to the codebase. Use a more descriptive title that captures the main change, such as 'Remove localization support and simplify build configuration' or 'Consolidate to English-only and streamline build process'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@qodo-merge-pro
Copy link
Contributor

qodo-merge-pro bot commented Nov 8, 2025

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Missing Logging: New functions that generate prompts for user-facing actions were added without any logging
of critical actions or outcomes, and the diff shows no audit trail for sensitive
operations.

Referred Code
export const getChatSystemPromptBase = async () => {
  return `## Role
<role>
You are an intelligent, helpful AI assistant designed to engage in natural, informative conversations while being respectful, accurate, and user-focused.
</role>

## Capabilities
<capabilities>
- Answer questions across diverse topics with accurate, well-reasoned responses
- Engage in creative tasks (writing, brainstorming, problem-solving)
- Provide explanations tailored to user's knowledge level
- Communicate effectively in multiple languages
- Assist with analysis, research, and decision-making
- Maintain context throughout multi-turn conversations
</capabilities>

## Guidelines
<guidelines>
1. **Be helpful**: Prioritize user's needs and provide actionable information
2. **Be accurate**: Base responses on reliable knowledge; acknowledge uncertainty when appropriate
3. **Be clear**: Use language appropriate for the user's expertise level


 ... (clipped 127 lines)
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Generic Catch: Errors are caught and only logged with console.log without contextual details or recovery,
reducing debuggability.

Referred Code
  )
} catch (e) {
  console.log(e)
}
Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status:
Console Errors: The webpack callback prints raw errors or stats to console which may expose internal
details if surfaced to end users in production environments.

Referred Code
if (err || stats.hasErrors()) {
  console.error(err || stats.toString())
  return
Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Unvalidated Input: User-provided DOM text is interpolated directly into large prompts without validation or
sanitization, which could propagate unsafe content to downstream systems.

Referred Code
  if (searchInput) {
    if (searchInput.value) input = searchInput.value
    else if (searchInput.textContent) input = searchInput.textContent
    if (input) {
      const preferredLanguage = await getPreferredLanguage()
      return `## Role
<role>
You are a knowledgeable research assistant helping users understand search queries and providing relevant information.
</role>

## Task
<task>
Interpret the user's search query and provide comprehensive, useful information related to their search intent.
</task>

## Instructions
<instructions>
1. **Interpret search intent**:
   - Informational (learning about a topic)
   - Navigational (finding a specific site/resource)
   - Transactional (looking to perform an action)


 ... (clipped 59 lines)
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@gemini-code-assist
Copy link

Summary of Changes

Hello @USERNAME-STOCK, 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 streamlines the project's scope and development overhead by reducing its multi-language support and narrowing its browser compatibility to Chromium-based platforms only. A core change involves refactoring the AI interaction prompts to a more structured, tag-based format, which is expected to lead to more precise and controllable AI outputs across various functionalities like summarization, translation, and code explanation. These changes also include a simplification of the overall build process.

Highlights

  • Localization Reduction: Removed support for multiple languages by deleting numerous locale files and simplifying language configuration to English only.
  • Browser Support Streamlining: Dropped build targets and related scripts for Firefox and Safari, focusing development and distribution solely on Chromium-based browsers.
  • Advanced Prompt Engineering: Implemented a new, highly structured prompt format using XML-like tags (, , , etc.) for all AI interactions, aiming to enhance the clarity, consistency, and quality of generated responses.
  • Build Process Simplification: Streamlined the build configuration by removing conditional production builds and disabling module concatenation.
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.

@qodo-merge-pro
Copy link
Contributor

qodo-merge-pro bot commented Nov 8, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Universal prompt strategy may degrade performance

The PR's new XML-based prompt format is applied universally across all features.
This may cause performance issues or higher costs for models not optimized for
this structure, so the prompt strategy should be adapted based on the selected
model.

Examples:

src/content-script/selection-tools/index.mjs [43-104]
    genPrompt: async (selection) => {
      const preferredLanguage = await getPreferredLanguage()
      return `## Role
<role>
You are an expert teacher specializing in breaking down complex topics into easily understandable explanations.
</role>

## Task
<task>
Explain the selected content using simple, clear language suitable for someone encountering this topic for the first time.

 ... (clipped 52 lines)
src/services/apis/shared.mjs [2-55]
  return `## Role
<role>
You are an intelligent, helpful AI assistant designed to engage in natural, informative conversations while being respectful, accurate, and user-focused.
</role>

## Capabilities
<capabilities>
- Answer questions across diverse topics with accurate, well-reasoned responses
- Engage in creative tasks (writing, brainstorming, problem-solving)
- Provide explanations tailored to user's knowledge level

 ... (clipped 44 lines)

Solution Walkthrough:

Before:

// file: src/content-script/selection-tools/index.mjs

export const config = {
  explain: {
    icon: <ChatText />,
    label: 'Explain',
    genPrompt: async (selection) => {
      const preferredLanguage = await getPreferredLanguage();
      // The same complex XML prompt is always used, regardless of the model.
      return `## Role
<role>
You are an expert teacher...
</role>
...
## Input Data
<input_data>
Selected Content:
${selection}
</input_data>
...`;
    },
  },
  // ... other tools use the same universal approach
};

After:

// file: src/content-script/selection-tools/index.mjs

// Define different prompt templates for different models
const prompts = {
  claude: (selection, lang) => `## Role...<role>...</role>...`, // XML format
  gpt: (selection, lang) => `You are an expert teacher. Explain the following in ${lang}: ${selection}`, // Simple format
  default: (selection, lang) => `Explain this: ${selection}`
};

export const config = {
  explain: {
    icon: <ChatText />,
    label: 'Explain',
    genPrompt: async (selection) => {
      const userConfig = await getUserConfig();
      const preferredLanguage = await getPreferredLanguage();
      const modelFamily = getModelFamily(userConfig.modelName); // e.g., 'claude', 'gpt'

      const promptGenerator = prompts[modelFamily] || prompts.default;
      return promptGenerator(selection, preferredLanguage);
    },
  },
  // ... other tools could be updated similarly
};
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies that the new universal XML-based prompt structure, while sophisticated, may not be optimal for all supported AI models, potentially degrading performance and increasing costs.

High
General
Update tool to new prompt format

Update the translateBidi, divide, and ask tools in
src/content-script/selection-tools/index.mjs to use the new structured prompt
format for consistency with other tools updated in this PR.

src/content-script/selection-tools/index.mjs [259-266]

 translateBidi: {
   icon: <Globe />,
   label: 'Translate (Bidirectional)',
-  genPrompt: createGenPrompt({
-    isTranslation: true,
-    enableBidirectional: true,
-  }),
+  genPrompt: async (selection) => {
+    const preferredLanguage = await getPreferredLanguage()
+    return `## Role
+<role>
+You are a professional translator. Your task is to perform a bidirectional translation.
+</role>
+
+## Task
+<task>
+1. Detect the language of the source text.
+2. If the text is in ${preferredLanguage}, translate it to English.
+3. If the text is NOT in ${preferredLanguage}, translate it to ${preferredLanguage}.
+4. Provide ONLY the translated text as output.
+</task>
+
+## Input Data
+<input_data>
+Source Text:
+${selection}
+</input_data>
+
+## Constraints
+<constraints>
+- Return only the translated text.
+- Do not add any explanations or commentary.
+- Preserve original formatting (markdown, line breaks).
+</constraints>`
+  },
 },
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that several tools were missed in the prompt refactoring, which is a main theme of this PR. Applying this change would improve consistency and align the remaining tools with the new, more detailed prompt structure.

Medium
  • More

@USERNAME-STOCK USERNAME-STOCK changed the title simplified by mistake Nov 8, 2025
Copy link

@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 valuable simplification across the project. The restructuring of AI prompts into a structured markdown and XML format is a fantastic improvement that should lead to more consistent and higher-quality responses from the AI. The simplification of the build process and removal of multi-language support streamlines the codebase effectively.

My review includes a few suggestions for improvement:

  • A performance concern in the webpack build configuration where an optimization is disabled for production builds.
  • Opportunities to reduce code duplication and improve readability in some of the newly added prompt generation logic.

Additionally, while most prompts have been migrated to the new structured format, a few in src/content-script/selection-tools/index.mjs (like translateBidi, divide, and ask) still use the old format. It would be great to update these as well to achieve full consistency with the new approach.

Overall, this is a strong enhancement to the project.

new CssMinimizerPlugin(),
],
concatenateModules: !isAnalyzing,
concatenateModules: false,

Choose a reason for hiding this comment

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

medium

Disabling concatenateModules for production builds can negatively impact performance and increase the bundle size. While this is useful for debugging, it's recommended to enable this optimization for production builds to ensure the best performance for end-users.

Suggested change
concatenateModules: false,
concatenateModules: isProduction,

Comment on lines 173 to 258
translateToEn: {
icon: <Globe />,
label: 'Translate (To English)',
genPrompt: createGenPrompt({
isTranslation: true,
targetLanguage: 'English',
}),
genPrompt: async (selection) => {
const targetLanguage = 'English'
return `## Role
<role>
You are a professional translator with expertise in maintaining semantic accuracy, cultural nuance, and stylistic tone across languages.
</role>
## Task
<task>
Translate the selected text into ${targetLanguage} while preserving the original meaning, tone, style, and formatting.
</task>
## Instructions
<instructions>
1. **Analyze source text**: Identify tone and cultural elements
2. **Translate accurately**: Preserve semantic meaning and style
3. **Preserve formatting**: Maintain markdown and structure
4. **Cultural adaptation**: Use appropriate cultural equivalents
</instructions>
## Output Format
<output_format>
[Translated text with original formatting preserved]
</output_format>
## Input Data
<input_data>
Target Language: ${targetLanguage}
Source Text:
${selection}
</input_data>
## Constraints
<constraints>
- Provide ONLY the translated text
- Preserve all formatting exactly as in source
- If text is already in ${targetLanguage}, state "Text is already in ${targetLanguage}"
</constraints>`
},
},
translateToZh: {
icon: <Globe />,
label: 'Translate (To Chinese)',
genPrompt: createGenPrompt({
isTranslation: true,
targetLanguage: 'Chinese',
}),
genPrompt: async (selection) => {
const targetLanguage = 'Chinese'
return `## Role
<role>
You are a professional translator with expertise in maintaining semantic accuracy, cultural nuance, and stylistic tone across languages.
</role>
## Task
<task>
Translate the selected text into ${targetLanguage} while preserving the original meaning, tone, style, and formatting.
</task>
## Instructions
<instructions>
1. **Analyze source text**: Identify tone and cultural elements
2. **Translate accurately**: Preserve semantic meaning and style
3. **Preserve formatting**: Maintain markdown and structure
4. **Cultural adaptation**: Use appropriate cultural equivalents
</instructions>
## Output Format
<output_format>
[Translated text with original formatting preserved]
</output_format>
## Input Data
<input_data>
Target Language: ${targetLanguage}
Source Text:
${selection}
</input_data>
## Constraints
<constraints>
- Provide ONLY the translated text
- Preserve all formatting exactly as in source
- If text is already in ${targetLanguage}, state "Text is already in ${targetLanguage}"
</constraints>`
},
},

Choose a reason for hiding this comment

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

medium

The prompts for translateToEn and translateToZh are nearly identical, with the only difference being the targetLanguage. This duplication can be avoided by creating a helper function that generates the prompt based on a given target language. This would improve maintainability.

For example:

const createTranslationPrompt = (targetLanguage, selection) => {
  return `## Role
<role>
You are a professional translator...
</role>
...
## Input Data
<input_data>
Target Language: ${targetLanguage}
Source Text:
${selection}
</input_data>
...`;
};

// in config
// ...
translateToEn: {
  // ...
  genPrompt: (selection) => createTranslationPrompt('English', selection),
},
translateToZh: {
  // ...
  genPrompt: (selection) => createTranslationPrompt('Chinese', selection),
},
// ...

Copy link
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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/content-script/selection-tools/index.mjs (1)

43-557: Significant code duplication violates DRY principle and coding guidelines.

The eight converted prompt generators (explain, translate, translateToEn, translateToZh, summary, polish, sentiment, code) share an identical structural pattern with sections: Role, Task, Instructions, Output Format, Input Data, and Constraints. This duplication makes maintenance difficult and violates the coding guideline to "reuse helpers from src/utils/".

Based on learnings

Consider extracting a shared template builder:

// In src/utils/prompt-template.mjs
export function buildStructuredPrompt({
  role,
  task,
  instructions,
  outputFormat,
  inputData,
  constraints,
}) {
  return `## Role
<role>
${role}
</role>

## Task
<task>
${task}
</task>

## Instructions
<instructions>
${instructions}
</instructions>

## Output Format
<output_format>
${outputFormat}
</output_format>

## Input Data
<input_data>
${inputData}
</input_data>

## Constraints
<constraints>
${constraints}
</constraints>`
}

Then refactor prompts to use this helper:

genPrompt: async (selection) => {
  const preferredLanguage = await getPreferredLanguage()
  return buildStructuredPrompt({
    role: 'You are an expert teacher...',
    task: 'Explain the selected content...',
    instructions: '1. **Read and understand**...',
    outputFormat: '## Simple Explanation...',
    inputData: `Selected Content:\n${selection}`,
    constraints: '- Use simple, jargon-free language...',
  })
}
♻️ Duplicate comments (4)
src/content-script/site-adapters/arxiv/index.mjs (1)

11-81: Duplicated prompt structure pattern.

This file uses the same XML-tag-based prompt structure as youtube/index.mjs. The duplication suggests these adapters should share a common prompt template system.

src/content-script/site-adapters/github/index.mjs (2)

88-170: Same XML-tag prompt pattern with duplication concerns.

This prompt follows the same XML-tag structure as other adapters, contributing to the duplication issue across the codebase.


212-305: Second structured prompt with same pattern.

The git patch prompt also uses the XML-tag structure. Both prompts in this file should be consolidated with the shared prompt system.

src/content-script/menu-tools/index.mjs (1)

17-97: Page summarization prompt continues duplication pattern.

This 80-line prompt follows the same XML-tag structure as all other adapters, further demonstrating the need for a shared prompt template system.

🧹 Nitpick comments (7)
build.mjs (2)

21-21: Consider removing dead variant parameters.

Since the build now only produces a single full-featured variant for Chromium, the isWithoutKatex, isWithoutTiktoken, and minimal parameters are always false and effectively dead code. You could simplify the function signature and remove the associated conditional logic (lines 34, 91-102, 207-256).


283-283: Consider removing the unused outputDirSuffix parameter.

Since the build now produces only one variant, outputDirSuffix is always an empty string and no longer serves a purpose. You could remove this parameter and simplify the function signature.

src/content-script/site-adapters/youtube/index.mjs (1)

76-135: Consider simplifying prompt structure and reducing token usage.

The new structured prompt uses XML-like tags mixed with Markdown headers, which is unconventional. This pattern is duplicated across multiple adapters (arxiv, bilibili, github, youtube). Consider:

  1. XML tags: The <role>, <task>, <instructions>, etc. tags may confuse some LLMs. Standard Markdown sections or simple delimiters are typically more reliable.
  2. Verbosity: This 60-line prompt will significantly increase token consumption and costs compared to the previous concise version.
  3. Duplication: Similar prompt structures across multiple adapters suggest an opportunity to extract a shared prompt template builder.

Consider refactoring to use a shared prompt builder:

// In a shared utils file
function buildStructuredPrompt({ role, task, instructions, outputFormat, inputData, constraints }) {
  return `Role: ${role}

Task: ${task}

Instructions:
${instructions}

Output Format:
${outputFormat}

Input Data:
${inputData}

Constraints:
${constraints}`
}

// Then in this file:
return await cropText(
  buildStructuredPrompt({
    role: 'You are an expert video content analyst...',
    task: 'Create a structured summary...',
    // etc.
  })
)
src/content-script/index.jsx (1)

153-229: Search query prompt follows same duplication pattern.

This prompt structure is consistent with the other adapters but continues the duplication issue. Additionally, the complexity of this prompt for a simple search query interpretation seems excessive.

For search queries, a simpler prompt might be more effective:

if (input) {
  const preferredLanguage = await getPreferredLanguage()
  return `Interpret and answer this search query in ${preferredLanguage}: "${input}"

Provide:
- Direct answer (if applicable)
- Key information and context
- Related topics
- Practical examples

Focus on usefulness and accuracy.`
}

This maintains the functionality while being more concise and cost-effective.

src/config/index.mjs (1)

658-661: Consider renaming function to reflect its simplified behavior.

The function no longer retrieves the navigator language—it deterministically returns 'en'. The name getNavigatorLanguage() is now misleading and could confuse future maintainers.

Consider renaming to something like getDefaultLanguage() or even replacing all calls with the literal 'en' if no future expansion is planned:

-export function getNavigatorLanguage() {
-  // Simplified to always return English as only English locale is included
-  return 'en'
-}
+export function getDefaultLanguage() {
+  // Simplified to always return English as only English locale is included
+  return 'en'
+}

Then update references at lines 492 and 616 accordingly.

src/content-script/selection-tools/index.mjs (2)

43-567: Inconsistent refactoring approach across selection tools.

Eight tools have been converted to detailed multi-section prompts with async getPreferredLanguage() calls, while three tools (translateBidi, divide, ask) still use the original createGenPrompt helper with simpler prompts. This inconsistency makes the codebase harder to understand and maintain.

Consider either:

  1. Converting the remaining three tools to match the new pattern for consistency, or
  2. If the simpler approach is sufficient for these tools, document why different patterns are used for different tools

If adopting option 1, note that createGenPrompt can be removed once all tools are migrated.


43-557: Significant increase in token usage per invocation.

The new prompts are substantially more verbose (approximately 500+ tokens each vs. the previous ~50-100 tokens). Since these functions are invoked on every selection tool usage, this will significantly increase:

  • API costs (especially for frequently used tools like translate and explain)
  • Response latency due to larger input context
  • Total conversation token count in multi-turn interactions

Recommendations:

  1. Monitor costs: Track token usage metrics before and after this change to quantify the impact
  2. Consider prompt optimization: The detailed instructions improve quality, but some sections might be condensable without sacrificing output
  3. A/B testing: Consider testing whether the detailed prompts provide proportionally better results to justify the 5-10x token increase
  4. User education: If costs increase substantially, users should be informed about the trade-off between prompt quality and usage costs

Example optimization opportunity—the Output Format section could use more concise examples rather than full templates, reducing tokens while preserving guidance.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7b99ec5 and 41d5c48.

📒 Files selected for processing (29)
  • README_IN.md (0 hunks)
  • README_JA.md (0 hunks)
  • README_TR.md (0 hunks)
  • README_ZH.md (0 hunks)
  • build.mjs (3 hunks)
  • package.json (0 hunks)
  • src/_locales/de/main.json (0 hunks)
  • src/_locales/es/main.json (0 hunks)
  • src/_locales/fr/main.json (0 hunks)
  • src/_locales/in/main.json (0 hunks)
  • src/_locales/it/main.json (0 hunks)
  • src/_locales/ja/main.json (0 hunks)
  • src/_locales/ko/main.json (0 hunks)
  • src/_locales/pt/main.json (0 hunks)
  • src/_locales/resources.mjs (0 hunks)
  • src/_locales/ru/main.json (0 hunks)
  • src/_locales/tr/main.json (0 hunks)
  • src/_locales/zh-hans/main.json (0 hunks)
  • src/_locales/zh-hant/main.json (0 hunks)
  • src/config/index.mjs (2 hunks)
  • src/config/language.mjs (1 hunks)
  • src/content-script/index.jsx (1 hunks)
  • src/content-script/menu-tools/index.mjs (1 hunks)
  • src/content-script/selection-tools/index.mjs (3 hunks)
  • src/content-script/site-adapters/arxiv/index.mjs (1 hunks)
  • src/content-script/site-adapters/bilibili/index.mjs (1 hunks)
  • src/content-script/site-adapters/github/index.mjs (3 hunks)
  • src/content-script/site-adapters/youtube/index.mjs (1 hunks)
  • src/services/apis/shared.mjs (1 hunks)
💤 Files with no reviewable changes (18)
  • src/_locales/es/main.json
  • src/_locales/zh-hans/main.json
  • src/_locales/zh-hant/main.json
  • package.json
  • src/_locales/ko/main.json
  • src/_locales/tr/main.json
  • src/_locales/it/main.json
  • src/_locales/resources.mjs
  • src/_locales/in/main.json
  • src/_locales/ja/main.json
  • README_IN.md
  • README_ZH.md
  • README_TR.md
  • README_JA.md
  • src/_locales/ru/main.json
  • src/_locales/pt/main.json
  • src/_locales/de/main.json
  • src/_locales/fr/main.json
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{js,jsx,mjs}

📄 CodeRabbit inference engine (AGENTS.md)

Follow ESLint React/JSX standards defined in .eslintrc.json (run npm run lint)

Files:

  • src/config/language.mjs
  • build.mjs
  • src/content-script/site-adapters/youtube/index.mjs
  • src/config/index.mjs
  • src/content-script/site-adapters/arxiv/index.mjs
  • src/content-script/menu-tools/index.mjs
  • src/content-script/site-adapters/github/index.mjs
  • src/content-script/selection-tools/index.mjs
  • src/content-script/index.jsx
  • src/content-script/site-adapters/bilibili/index.mjs
  • src/services/apis/shared.mjs
src/content-script/site-adapters/**

📄 CodeRabbit inference engine (AGENTS.md)

Site adapters: keep selectors minimal, use feature detection, and verify on Chromium/Firefox

Files:

  • src/content-script/site-adapters/youtube/index.mjs
  • src/content-script/site-adapters/arxiv/index.mjs
  • src/content-script/site-adapters/github/index.mjs
  • src/content-script/site-adapters/bilibili/index.mjs
src/config/index.mjs

📄 CodeRabbit inference engine (AGENTS.md)

Configuration management entry should be maintained in src/config/index.mjs

Files:

  • src/config/index.mjs
src/content-script/selection-tools/**

📄 CodeRabbit inference engine (AGENTS.md)

Selection tools: keep UI and logic separate; reuse helpers from src/utils/

Files:

  • src/content-script/selection-tools/index.mjs
**/*.{js,jsx,css}

📄 CodeRabbit inference engine (AGENTS.md)

Use Prettier to format all JS, JSX, and CSS files (run npm run pretty before linting)

Files:

  • src/content-script/index.jsx
src/content-script/index.jsx

📄 CodeRabbit inference engine (AGENTS.md)

Main content script entry is src/content-script/index.jsx; keep primary injection logic here

Files:

  • src/content-script/index.jsx
src/services/apis/**

📄 CodeRabbit inference engine (AGENTS.md)

Centralize network/API logic under src/services/apis/ and keep endpoints auditable

Files:

  • src/services/apis/shared.mjs
🧠 Learnings (5)
📚 Learning: 2025-09-12T18:14:47.716Z
Learnt from: CR
Repo: ChatGPTBox-dev/chatGPTBox PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-12T18:14:47.716Z
Learning: Applies to src/_locales/resources.mjs : Register any new locales in `src/_locales/resources.mjs`

Applied to files:

  • src/config/language.mjs
📚 Learning: 2025-09-14T18:01:17.933Z
Learnt from: PeterDaveHello
Repo: ChatGPTBox-dev/chatGPTBox PR: 886
File: build.mjs:165-171
Timestamp: 2025-09-14T18:01:17.933Z
Learning: In the ChatGPTBox project, the build.mjs webpack cache buildDependencies configuration should only track npm lockfiles (package-lock.json) and not include other package managers' lockfiles like pnpm-lock.yaml, yarn.lock, or bun.lockb, as confirmed by the maintainer PeterDaveHello.

Applied to files:

  • build.mjs
📚 Learning: 2025-09-12T18:14:47.716Z
Learnt from: CR
Repo: ChatGPTBox-dev/chatGPTBox PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-12T18:14:47.716Z
Learning: Applies to src/config/index.mjs : Configuration management entry should be maintained in `src/config/index.mjs`

Applied to files:

  • src/config/index.mjs
📚 Learning: 2025-09-12T18:14:47.716Z
Learnt from: CR
Repo: ChatGPTBox-dev/chatGPTBox PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-12T18:14:47.716Z
Learning: Applies to src/content-script/selection-tools/** : Selection tools: keep UI and logic separate; reuse helpers from `src/utils/`

Applied to files:

  • src/content-script/menu-tools/index.mjs
  • src/content-script/selection-tools/index.mjs
📚 Learning: 2025-09-12T18:14:47.716Z
Learnt from: CR
Repo: ChatGPTBox-dev/chatGPTBox PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-09-12T18:14:47.716Z
Learning: Applies to src/content-script/index.jsx : Main content script entry is `src/content-script/index.jsx`; keep primary injection logic here

Applied to files:

  • src/content-script/index.jsx
🧬 Code graph analysis (6)
src/content-script/site-adapters/youtube/index.mjs (3)
src/content-script/site-adapters/github/index.mjs (1)
  • title (67-67)
src/content-script/site-adapters/arxiv/index.mjs (1)
  • title (6-6)
src/content-script/site-adapters/bilibili/index.mjs (2)
  • title (37-37)
  • subtitleContent (54-54)
src/content-script/menu-tools/index.mjs (1)
src/utils/get-core-content-text.mjs (1)
  • getCoreContentText (59-105)
src/content-script/site-adapters/github/index.mjs (1)
src/content-script/site-adapters/gitlab/index.mjs (2)
  • patchData (13-13)
  • patchData (35-35)
src/content-script/selection-tools/index.mjs (3)
src/components/FloatingToolbar/index.jsx (1)
  • selection (15-15)
src/content-script/index.jsx (1)
  • preferredLanguage (154-154)
src/config/language.mjs (1)
  • getPreferredLanguage (17-21)
src/content-script/index.jsx (2)
src/content-script/selection-tools/index.mjs (6)
  • preferredLanguage (23-23)
  • preferredLanguage (44-44)
  • preferredLanguage (110-110)
  • preferredLanguage (271-271)
  • preferredLanguage (389-389)
  • preferredLanguage (459-459)
src/config/language.mjs (1)
  • getPreferredLanguage (17-21)
src/content-script/site-adapters/bilibili/index.mjs (3)
src/content-script/site-adapters/github/index.mjs (1)
  • title (67-67)
src/content-script/site-adapters/arxiv/index.mjs (1)
  • title (6-6)
src/content-script/site-adapters/youtube/index.mjs (2)
  • title (41-41)
  • subtitleContent (67-67)
🔇 Additional comments (4)
build.mjs (2)

70-70: Verify the hardcoded concatenateModules: false is intentional.

The module concatenation is now always disabled, whereas it was previously conditional (tied to !isAnalyzing). Since isAnalyzing is still used elsewhere (line 89), verify that always disabling module concatenation is the desired behavior for both analysis and production builds.


324-333: LGTM! Build simplification is well-executed.

The build function is correctly simplified to produce a single full-featured Chromium build. The intent is clearly documented, and the parameters passed to runWebpack and finishOutput are appropriate for this streamlined approach.

src/config/index.mjs (1)

489-489: Change aligns with English-only simplification.

The hardcoded default model is consistent with removing language-aware configuration. Existing users with stored preferences will retain their settings, so this only affects new installations.

src/content-script/selection-tools/index.mjs (1)

43-104: All call sites correctly handle async genPrompt functions.

The verification confirms that the async conversion is complete and correct. In src/content-script/index.jsx lines 358 and 362, both call sites properly use await when invoking genPrompt():

  • Line 358: prompt = await toolsConfig[data.itemId].genPrompt(data.selectionText)
  • Line 362: prompt = await menuItem.genPrompt()

Background scripts (menus.mjs, commands.mjs) do not directly invoke genPrompt—they only check for its existence and send CREATE_CHAT messages to the content script, which receives and processes them with proper await handling. No issues found.

Comment on lines +3 to +7
// Simplified language list with only English
export const languageList = {
auto: { name: 'Auto', native: 'Auto' },
en: { name: 'English', native: 'English' },
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Major breaking change: Removed all non-English language support.

This change removes support for all languages except English, which will break existing user configurations and is a significant regression in functionality.

Run this script to verify the impact:

Additionally, consider:

  1. Migration strategy: How will existing users with non-English preferences be handled?
  2. User communication: This warrants a breaking change notice in release notes.
  3. Justification: Why remove i18n support? This seems like a significant feature regression.

🏁 Script executed:

#!/bin/bash

# Find all references to removed language codes
echo "=== Checking for references to removed language codes ==="
rg -n '\b(zh|zhHant|ja|ko|ru|de|fr|es|pt|it|nl|pl|ar|hi)\b' --type=js --type=json -g '!node_modules' -g '!*.lock'

# Check for language-related config usage
echo "=== Checking for preferredLanguage usage ==="
rg -n 'preferredLanguage' --type=js -C 3 -g '!node_modules'

# Check for stored user configs that might have non-English settings
echo "=== Checking for language config persistence ==="
rg -n 'userLanguage|preferredLanguage' --type=js -C 2 -g '!node_modules'

Length of output: 17556



---

🏁 Script executed:

```shell
#!/bin/bash

# Find the full original language list definition
echo "=== Looking for language.mjs or similar files ==="
fd -e mjs -e js -e json | grep -i lang

# Check if there's a git history or backup of the file
echo "=== Checking git status and history ==="
git log --oneline -n 20 -- src/config/language.mjs 2>/dev/null || echo "Git history not available"

# Check for config initialization or migration logic
echo "=== Checking for config initialization/migration logic ==="
rg -n 'defaultConfig|initConfig|migrateConfig|upgradeConfig' --type=js -B 2 -A 5 -g '!node_modules'

# Check what userLanguage is and how it's set
echo "=== Checking userLanguage definition ==="
rg -n 'userLanguage' --type=js -B 2 -A 2 -g '!node_modules'

Length of output: 2963


🏁 Script executed:

#!/bin/bash
# Check the actual size and structure of what languageList originally was
# Look for i18n or translation file references that might indicate supported languages
echo "=== Checking for i18n configuration files ==="
find . -name "*locale*" -o -name "*i18n*" -o -name "*translation*" 2>/dev/null | grep -v node_modules | head -20

echo "=== Looking for language resource files ==="
ls -la src/_locales/ 2>/dev/null || echo "No _locales directory found"

Length of output: 507



---

🏁 Script executed:

```shell
#!/bin/bash

# Check the config/index.mjs file to understand defaultConfig
echo "=== Checking config/index.mjs ==="
cat src/config/index.mjs

# Check the git diff for the recent commit that simplified languages
echo -e "\n=== Checking git diff for language changes ==="
git show 5a793e8:src/config/language.mjs 2>/dev/null || echo "Previous version not available"

# Check how getUserConfig and stored config interact
echo -e "\n=== Checking for config merge or fallback logic ==="
rg -n 'getUserConfig|setUserConfig' --type=js -A 10 -B 2 -g '!node_modules' | head -60

Length of output: 27322


Critical: Missing migration and fallback logic for removed language support.

This change removes language support entirely, which breaks existing user configurations. While the build refactor appears intentional (Chrome-only, English-only), the code lacks proper migration or fallback handling:

  • getPreferredLanguage() in src/config/language.mjs will crash when accessing languageList[config.preferredLanguage] for users with stored non-English preferences (e.g., zh, ja)
  • src/components/ReadButton/index.jsx lines 28-34 still attempt language-specific voice lookups but will fail silently for removed language codes
  • No migration function converts existing stored preferences to valid keys
  • getUserConfig() merges stored config with defaultConfig, preserving invalid preferredLanguage values

Required fixes:

  1. Add fallback in getPreferredLanguage() and related functions to handle invalid preferredLanguage keys (reset to default or 'auto')
  2. Add config migration to convert stored non-English preferences to 'auto' or 'en'
  3. Validate preferredLanguage before accessing languageList throughout codebase
  4. Document this as a breaking change requiring user communication

Comment on lines +61 to +120
`## Role
<role>
You are an expert video content analyst specializing in distilling long-form video content into actionable insights.
</role>
## Task
<task>
Create a structured summary of the Bilibili video based on the subtitle transcript provided.
</task>
## Instructions
<instructions>
1. **Open with context**: Begin with the video title and a one-sentence overview
2. **Identify main topics**: List 3-5 primary themes or segments
3. **Extract key takeaways**: Provide 5-7 bullet points of actionable insights or crucial information
4. **Note important details**: Include specific data, quotes, or examples that support main points
5. **Structure chronologically**: Maintain the flow of the video's narrative when relevant
</instructions>
## Output Format
<output_format>
# [Video Title]
## Overview
[One-sentence description of video purpose/topic]
## Main Topics
1. [Topic 1] - [Brief description]
2. [Topic 2] - [Brief description]
3. [Topic 3] - [Brief description]
## Key Takeaways
- [Actionable insight 1]
- [Actionable insight 2]
- [Actionable insight 3]
- [Continue as needed]
## Important Details
- [Specific data point, quote, or example]
- [Another relevant detail]
## Conclusion
[One-sentence summary of main message]
</output_format>
## Input Data
<input_data>
Video Title: "${title}"
Subtitle Content:
${subtitleContent}
</input_data>
## Constraints
<constraints>
- Focus on information actually present in the subtitles
- Do not add external knowledge or assumptions
- If subtitles are incomplete or unclear, note this limitation
- Keep summary concise while capturing essential information
</constraints>`,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Critical code duplication with youtube/index.mjs.

This prompt is nearly identical to the YouTube adapter (lines 76-135), differing only in "Bilibili video" vs "YouTube video". This is a strong code smell.

Extract a shared video summarization prompt builder:

// In a shared utils file
export function buildVideoSummaryPrompt(platform, title, subtitleContent) {
  return `## Role
<role>
You are an expert video content analyst specializing in distilling long-form video content into actionable insights.
</role>

## Task
<task>
Create a structured summary of the ${platform} video based on the subtitle transcript provided.
</task>
...
Video Title: "${title}"

Subtitle Content:
${subtitleContent}
...`
}

// Then use it:
return await cropText(buildVideoSummaryPrompt('Bilibili', title, subtitleContent))
🤖 Prompt for AI Agents
In src/content-script/site-adapters/bilibili/index.mjs around lines 61 to 120,
the prompt string is nearly identical to the YouTube adapter causing duplicated
code; extract a shared prompt-builder utility (e.g.,
utils/buildVideoSummaryPrompt(platform, title, subtitleContent)) that returns
the templated prompt with platform interpolated, replace the hardcoded prompt
here with a call to that utility (and use it where youtube adapter currently
duplicates the logic), and ensure the adapters call
cropText(buildVideoSummaryPrompt('Bilibili', title, subtitleContent)) so
platform-specific differences are injected via the parameter.

Comment on lines 1 to +54
export const getChatSystemPromptBase = async () => {
return `You are a helpful, creative, clever, and very friendly assistant. You are familiar with various languages in the world.`
return `## Role
<role>
You are an intelligent, helpful AI assistant designed to engage in natural, informative conversations while being respectful, accurate, and user-focused.
</role>
## Capabilities
<capabilities>
- Answer questions across diverse topics with accurate, well-reasoned responses
- Engage in creative tasks (writing, brainstorming, problem-solving)
- Provide explanations tailored to user's knowledge level
- Communicate effectively in multiple languages
- Assist with analysis, research, and decision-making
- Maintain context throughout multi-turn conversations
</capabilities>
## Guidelines
<guidelines>
1. **Be helpful**: Prioritize user's needs and provide actionable information
2. **Be accurate**: Base responses on reliable knowledge; acknowledge uncertainty when appropriate
3. **Be clear**: Use language appropriate for the user's expertise level
4. **Be respectful**: Maintain professional, courteous tone regardless of query
5. **Be creative**: Offer novel insights and solutions when relevant
6. **Be concise**: Provide thorough answers without unnecessary verbosity
7. **Be adaptive**: Adjust communication style to match user's tone and needs
</guidelines>
## Communication Style
<communication_style>
- Natural, conversational tone
- Clear and direct language
- Structured responses for complex topics
- Examples and analogies when helpful
- Acknowledgment of limitations or uncertainty
- Multi-language support with cultural sensitivity
</communication_style>
## Constraints
<constraints>
- Do not claim to have personal experiences, emotions, or consciousness
- Do not pretend to access real-time information, browse the internet, or remember previous conversations unless explicitly in context
- Acknowledge when questions are outside your knowledge or capabilities
- Decline requests for harmful, illegal, or unethical content
- Maintain user privacy and do not request personal information unnecessarily
</constraints>
## Response Approach
<response_approach>
1. Understand the user's question or request
2. Provide direct answer or assistance
3. Add relevant context or explanation
4. Offer to clarify or expand if needed
5. Maintain conversation continuity
</response_approach>`
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Base system prompt structure increases token overhead for all requests.

This base prompt will be prepended to every chat request using this API mode. The verbose structure (53 lines) significantly increases baseline token consumption for all conversations.

Consider a more concise base prompt for cost efficiency:

export const getChatSystemPromptBase = async () => {
  return `You are a helpful, accurate, and thoughtful AI assistant.

Key principles:
- Provide accurate, well-reasoned responses
- Be clear and concise
- Acknowledge limitations when uncertain
- Maintain a respectful, professional tone
- Support multiple languages

Adapt your communication style to the user's needs.`
}
🤖 Prompt for AI Agents
In src/services/apis/shared.mjs around lines 1 to 54, the base system prompt is
overly verbose and inflates token usage; replace the long multi-section template
with a much shorter, single-paragraph system prompt that preserves essential
rules (helpful, accurate, concise, acknowledge limits, respectful,
multi-language support, adaptive style) while removing the multi-line XML-like
sections and extra guidelines; ensure the function still returns a template
string (and remains async if needed) so callers receive the concise prompt text.

Comment on lines +95 to +147
return `## Role
<role>
You are an intelligent, helpful AI assistant designed to engage in natural, informative conversations while being respectful, accurate, and user-focused.
</role>
## Capabilities
<capabilities>
- Answer questions across diverse topics with accurate, well-reasoned responses
- Engage in creative tasks (writing, brainstorming, problem-solving)
- Provide explanations tailored to user's knowledge level
- Communicate effectively in multiple languages
- Assist with analysis, research, and decision-making
- Maintain context throughout multi-turn conversations
</capabilities>
## Guidelines
<guidelines>
1. **Be helpful**: Prioritize user's needs and provide actionable information
2. **Be accurate**: Base responses on reliable knowledge; acknowledge uncertainty when appropriate
3. **Be clear**: Use language appropriate for the user's expertise level
4. **Be respectful**: Maintain professional, courteous tone regardless of query
5. **Be creative**: Offer novel insights and solutions when relevant
6. **Be concise**: Provide thorough answers without unnecessary verbosity
7. **Be adaptive**: Adjust communication style to match user's tone and needs
</guidelines>
## Communication Style
<communication_style>
- Natural, conversational tone
- Clear and direct language
- Structured responses for complex topics
- Examples and analogies when helpful
- Acknowledgment of limitations or uncertainty
- Multi-language support with cultural sensitivity
</communication_style>
## Constraints
<constraints>
- Do not claim to have personal experiences, emotions, or consciousness
- Do not pretend to access real-time information, browse the internet, or remember previous conversations unless explicitly in context
- Acknowledge when questions are outside your knowledge or capabilities
- Decline requests for harmful, illegal, or unethical content
- Maintain user privacy and do not request personal information unnecessarily
</constraints>
## Response Approach
<response_approach>
1. Understand the user's question or request
2. Provide direct answer or assistance
3. Add relevant context or explanation
4. Offer to clarify or expand if needed
5. Maintain conversation continuity
</response_approach>`
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Critical duplication: Nearly identical to getChatSystemPromptBase.

Lines 95-147 are almost identical to lines 2-54. The only difference is the absence of the "Context" and "Conversation Format" sections present in getCompletionPromptBase.

Consolidate these functions:

export const getChatSystemPromptBase = async () => {
  return buildBasePrompt()
}

export const getCustomApiPromptBase = async () => {
  return buildBasePrompt()
}

function buildBasePrompt() {
  return `[shared prompt content]`
}

Or if they truly need to differ, extract the shared portions.

🤖 Prompt for AI Agents
src/services/apis/shared.mjs lines 95-147: The block returned by
getCustomApiPromptBase is nearly identical to getChatSystemPromptBase (lines
~2-54); consolidate duplicated content by extracting the shared prompt into a
single builder function (e.g., buildBasePrompt or buildSharedPrompt) that
returns the common string, then have getChatSystemPromptBase and
getCustomApiPromptBase simply call that builder; if there must be small
differences, return the shared string from the builder and append only the
differing sections in each function so duplication is removed.

@USERNAME-STOCK USERNAME-STOCK deleted the claude/review-src-files-011CUvUyQzzb4X4VPkZeG4fM branch November 8, 2025 14:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants