Context Engine
Relevant source files
The following files were used as context for generating this wiki page:
- src/tools/artifacts/systemRole.ts
- src/tools/local-system/systemRole.ts
- src/tools/web-browsing/systemRole.ts
- packages/database/src/repositories/dataImporter/tests/fixtures/agentsToSessions.json
- scripts/seedBundledApps/index.ts
- packages/prompts/src/chains/summaryDescription.ts
- packages/prompts/src/prompts/systemRole/index.test.ts
- src/locales/default/discover.ts
- packages/database/src/repositories/dataImporter/deprecated/tests/fixtures/messages.json
The System Role is a foundational component in LobeChat that defines an AI agent's behavior, personality, skills, and constraints. It is a set of instructions provided to the Large Language Model (LLM) at the beginning of a conversation, acting as a constitution for the agent. By crafting a detailed System Role, developers can create specialized assistants tailored for specific tasks, from technical code reviews to creative content writing.
The System Role is a core part of an agent's configuration and is instrumental in guiding the model's responses, ensuring they are relevant, consistent, and adhere to predefined rules and formats. This mechanism is central to creating the diverse and capable agents available in the LobeChat ecosystem.
Core Concepts
The System Role is a powerful prompt engineering technique that establishes the context and operational parameters for an AI agent.
Structure of a System Role
A well-defined System Role typically consists of several key sections that instruct the AI on how to behave. These sections provide a clear framework for the agent's persona and capabilities.
This diagram illustrates the common components of a System Role prompt.
Common sections include:
- Role/Profile: A high-level description of the agent's persona and expertise.
- Skills: A detailed list of the agent's capabilities and what it can do for the user.
- Constraints/Rules: Strict limitations on the agent's behavior, such as language use, topics to avoid, or output formatting.
- Workflow: A step-by-step process the agent should follow to handle user requests.
- Initialization: Instructions for the agent's first message to the user, often including a greeting and an introduction.
The following table shows examples of agents and their systemRole definitions.
| Agent Title | Description | System Role Snippet |
|---|---|---|
| CAN | Experienced programmer proficient in multiple languages. | # 角色\n\n您是一位名为CAN的高级程序员,拥有多年编程经验。您的专业知识使您能够在任何编程语言中编写复杂的程序。 |
| Quant Trading Advisor | Specializes in quantitative trading and strategy optimization in the digital currency market. | # 角色\n\n该AI代理是一位专注于数字货币市场的量化交易专家,拥有多年的成功交易经验。 |
| AI Agent Generator | Specializes in creating AI agent role descriptions that meet requirements. | 您是一个AI代理创建者。您的任务是根据用户提供的信息创建一个新的AI代理。请按照以下格式生成AI代理的描述... |
Dynamic System Roles
System Roles can be dynamic, incorporating user-specific information at runtime. This is achieved by using placeholders in the prompt, which are then replaced with actual data before being sent to the LLM.
For example, the local-system tool uses placeholders like {{platform}} and {{desktopPath}} to inform the agent about the user's operating system and common file paths.
export const systemPrompt = `You have a Local System tool...
<user_context>
Here are some known locations and system details on the user's system. User is using the Operating System: {{platform}}({{arch}}). Use these paths when the user refers to these common locations by name (e.g., "my desktop", "downloads folder").
- Desktop: {{desktopPath}}
- Documents: {{documentsPath}}
- Downloads: {{downloadsPath}}
...
</user_context>
...
`;
This allows the agent to respond more intelligently to requests like "list files on my desktop" by using the correct, context-aware file path.
Sources: src/tools/local-system/systemRole.ts:3-11
Programmatic Composition
System Roles can be composed of multiple parts that are programmatically joined together. The BuiltinSystemRolePrompts function combines a welcome message, plugin information, and a chat history summary into a single, cohesive system prompt.
This flow shows how different prompt components are assembled.
The system wraps the history summary in a specific XML tag structure for the model to better understand it.
it('should return history summary when only history is provided', () => {
const result = BuiltinSystemRolePrompts({
historySummary: 'User discussed AI topics previously',
});
expect(result).toContain('<chat_history_summary>');
...
});
This modular approach allows for flexible and context-aware prompt generation.
Sources: packages/prompts/src/prompts/systemRole/index.test.ts
Tool-Specific System Roles
Many tools in LobeChat come with their own dedicated systemRole to instruct the AI on how to use them correctly. This includes defining the tool's capabilities, the expected input/output format, and any constraints.
Artifacts Tool
The Artifacts tool allows the agent to create substantial, self-contained content like code, documents, or diagrams in a separate UI window. The system role for this tool is extensive, providing strict guidelines on what constitutes a good artifact and how to format it.
Key Instructions:
- When to Use: For content that is substantial (>15 lines), self-contained, and likely to be modified by the user.
- Tag Structure: All artifacts must be wrapped in
<lobeArtifact>tags withidentifier,type, andtitleattributes. - Content Types: The
typeattribute specifies the content, with supported values for code, markdown, HTML, SVG, Mermaid diagrams, and React components. - Thinking Process: The agent is instructed to think in
<lobeThinking>tags before creating an artifact to justify its use.
This sequence diagram shows the process of creating an artifact.
Local System Tool
This tool grants the agent the ability to interact with the user's local file system. Its system role is focused on safety, clarity, and a precise response format.
Key Instructions:
- Capabilities: The agent is informed it can
listLocalFiles,readLocalFile,writeFile,searchLocalFiles,renameLocalFile, andmoveLocalFiles. - Response Format: Any file or directory path in the agent's response must be wrapped in a
<localFile>tag, e.g.,<localFile name="report.pdf" path="/Users/me/Documents/report.pdf" />. - Context-Awareness: The agent should use the dynamic paths provided in
<user_context>for common locations like "Desktop" or "Documents". - Security: The agent must confirm with the user before performing write or move operations.
Sources: src/tools/local-system/systemRole.ts:1-91
Web Browsing Tool
This tool allows the agent to search the internet and crawl web pages. The system role emphasizes effective search strategies and proper source citation.
Key Instructions:
- Capabilities: The agent can use
search,crawlMultiPages, andcrawlSinglePage. - Search Syntax: The agent is taught to use special syntax to select search engines (
!google), categories (!news), and time ranges (!year). - Citation: All information from the web must be cited using Markdown footnotes (e.g.,
[^1]) and a list of sources must be provided at the end of the response. - Error Handling: The agent is given a workflow for handling failed searches or crawls, such as by refining the query or trying a different engine.
Sources: src/tools/web-browsing/systemRole.ts:1-120
System Role in Prompt Chaining
System Roles are also used for smaller, highly specific tasks in a "prompt chain". In this pattern, a system message provides a one-shot instruction to the model to transform an input in a very particular way.
For example, the chainSummaryDescription function uses a system role to instruct the model to summarize an agent's skills into a brief, 20-character description in a target language.
{
content: `你是一名擅长技能总结的助理,你需要将用户的输入的内容总结为一个角色技能简介,不超过 20 个字。内容需要确保信息清晰、逻辑清晰,并有效地传达角色的技能和经验,需要并翻译为目标语言:${locale}。格式要求如下:\n输入: {文本作为JSON引用字符串} [locale]\n输出: {简介}`,
role: 'system',
}
This demonstrates the versatility of the System Role, using it not just for defining a persistent agent persona but also for single, atomic operations.
Sources: packages/prompts/src/chains/summaryDescription.ts:5-8, packages/prompts/src/chains/tests/summaryTags.test.ts:13-16
Conclusion
The System Role is a cornerstone of LobeChat's agent architecture. It provides a robust and flexible mechanism for defining the identity, capabilities, and behavior of AI assistants. Through structured prompts, dynamic context, and tool-specific instructions, System Roles enable the creation of a wide array of specialized agents. The use of this feature for both broad agent personas and narrow, chained tasks highlights its importance and versatility within the platform's prompt engineering strategy.