Skip to content

Commit 518fe79

Browse files
feat: simplify the code and optimize prompts for complex tasks (#6)
* feat: simplify the code, remove unnecessary prompts, and optimize prompts for complex tasks * fix: context7 query with topic
1 parent 0d3acbe commit 518fe79

2 files changed

Lines changed: 212 additions & 425 deletions

File tree

src/tools/extract_antv_topic.ts

Lines changed: 73 additions & 221 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
/**
2-
* AntV Intelligent Assistant Preprocessing Tool
3-
*
4-
* 处理所有与 AntV 可视化库相关的用户查询,智能识别、解析并结构化用户需求。
5-
* 支持自动识别库类型、提取技术主题关键词、判断用户意图,并为后续 query_antv_document 工具准备结构化信息。
2+
* AntV Topic Extraction Tool - Preprocesses user queries for AntV libraries
63
*/
7-
84
import { z } from 'zod';
95
import type { AntVLibrary } from '../types';
106
import { logger } from '../utils';
@@ -51,251 +47,117 @@ interface ExtractAntVTopicArgs {
5147
}
5248

5349
function generateExtractionPrompt(args: ExtractAntVTopicArgs): string {
54-
const libraryContext = args.library
55-
? getLibraryConfig(args.library)
56-
: undefined;
57-
return generateUnifiedPrompt(args.query, args.maxTopics, libraryContext);
58-
}
59-
60-
function generateUnifiedPrompt(
61-
query: string,
62-
maxTopics: number,
63-
libraryContext?: { id: AntVLibrary; name: string },
64-
): string {
65-
const isLibrarySpecified = !!libraryContext;
66-
const allLibraries = Object.values(ANTV_LIBRARY_META);
67-
const libraryDeterminationSection = isLibrarySpecified
68-
? generateLibrarySpecifiedSection(libraryContext)
69-
: generateLibraryDetectionSection(allLibraries);
70-
const extractionRulesSection = generateExtractionRulesSection(
71-
maxTopics,
72-
libraryContext,
73-
);
74-
const outputFormatSection = generateOutputFormatSection();
75-
const examplesSection = generateExamplesSection();
76-
return `# AntV ${isLibrarySpecified ? 'Topic and Intent Extraction' : 'Smart Library Detection and Topic Extraction'} Task
77-
78-
## Task Objective
79-
${
80-
isLibrarySpecified
81-
? `Extract the most relevant technical topic phrases and user intent from user queries for ${libraryContext.name} documentation retrieval.`
82-
: `1. First: Detect and recommend the most suitable AntV library based on query intent and installed dependencies
83-
2. Second: Extract relevant technical topics and user intent for the determined library`
84-
}
85-
86-
## User Query
87-
\`\`\`
88-
${query}
89-
\`\`\`
90-
91-
${libraryDeterminationSection}
92-
93-
${extractionRulesSection}
94-
95-
## Output Format
96-
97-
${outputFormatSection}
98-
99-
## Examples
100-
101-
${examplesSection}
102-
103-
Now please begin ${isLibrarySpecified ? 'extraction' : 'the detection and extraction process'}:
50+
const { query, library, maxTopics } = args;
10451

105-
## Important Notice
106-
**MANDATORY NEXT STEP**: After completing this task, immediately call the \`query_antv_document\` tool with the extracted parameters.
107-
108-
**Requirements:**
109-
- Always use extracted library, topic, intent parameters with \`query_antv_document\` tool
110-
- Never skip \`query_antv_document\` tool call and answer directly
111-
- For complex tasks: pass subTasks parameter; for simple tasks: use basic parameters`;
112-
}
113-
114-
function generateLibrarySpecifiedSection(libraryContext: {
115-
id: AntVLibrary;
116-
name: string;
117-
}): string {
118-
return `## Phase 1: Library Context
119-
**Target Library**: ${libraryContext.name} (${libraryContext.id})`;
120-
}
121-
122-
function generateLibraryDetectionSection(
123-
allLibraries: Array<{ id: AntVLibrary; name: string; description: string }>,
124-
): string {
125-
// 动态生成库映射列表
52+
// Generate library mappings
12653
const libraryMappings = Object.values(ANTV_LIBRARY_META)
127-
.map((lib) => ` - \`@antv/${lib.id}\` → ${lib.name}`)
54+
.map((lib) => ` - **${lib.name} (${lib.id})**: ${lib.description}`)
12855
.join('\n');
12956

130-
return `## Phase 1: Library Detection and Recommendation
131-
132-
**Your first task is to determine the most suitable AntV library for this query.**
57+
// Get library-specific context if specified
58+
const libraryContext = library
59+
? {
60+
name: getLibraryConfig(library).name,
61+
keywords: getLibraryKeywords(library),
62+
}
63+
: null;
13364

134-
### Step 1.1: Project Dependency Scan
135-
Scan the user's current project for installed AntV dependencies:
136-
1. **Check package.json**: Look for AntV-related dependencies in both \`dependencies\` and \`devDependencies\`
137-
2. **Look for patterns**:
138-
${libraryMappings}
65+
const libraryTerminology = libraryContext
66+
? libraryContext.keywords
67+
: 'Use the terminology and components specific to the determined target library';
13968

140-
### Step 1.2: Smart Library Recommendation
141-
Based on query content and detected dependencies, recommend the most suitable library:
69+
return `# AntV Query Analysis & Topic Extraction
14270
143-
**Library Selection Rules (Priority Order):**
144-
1. **Query Intent Match**: Select library that best matches the technical requirements:
145-
${allLibraries
146-
.map((lib) => `- **${lib.name} (${lib.id})**: ${lib.description}`)
147-
.join('\n ')}
71+
## User Query
72+
**Query**: ${query}
73+
**Max Topics**: ${maxTopics}
74+
${library ? `**Specified Library**: ${getLibraryConfig(library).name} (${library})` : '**Library**: Auto-detect'}
14875
149-
2. **Installed Dependency Priority**: If multiple libraries match the intent, prioritize installed ones
150-
3. **Best Practice Guidance**: Consider the most commonly used library for the specific use case
76+
## Task Instructions
15177
152-
**Output the recommended library and reason before proceeding to Phase 2.**`;
153-
}
78+
### Phase 1: Library Detection ${library ? '(Skipped - Library Specified)' : ''}
79+
${
80+
library
81+
? `Using specified library: **${getLibraryConfig(library).name} (${library})**`
82+
: `**Determine the most suitable AntV library:**
15483
155-
function generateExtractionRulesSection(
156-
maxTopics: number,
157-
libraryContext?: { id: AntVLibrary; name: string },
158-
): string {
159-
const libraryTerminology = libraryContext
160-
? getLibraryKeywords(libraryContext.id)
161-
: 'Use the terminology and components specific to the determined target library';
162-
const librarySpecificPriority = libraryContext
163-
? `${libraryContext.name} specific component concepts and APIs`
164-
: 'Target library specific component concepts and APIs';
165-
return `## Phase 2: Topic Extraction and Intent Recognition
84+
Available Libraries:
85+
${libraryMappings}
16686
167-
Once you have the target library (either specified or determined), proceed with:
87+
**Selection Priority:**
88+
1. Match query intent with library purpose
89+
2. Check for existing project dependencies
90+
3. Consider common use cases for the query type`
91+
}
16892
169-
### 2.1: Complex Task Detection
170-
Determine whether the user query is a complex task. Characteristics of complex tasks:
171-
- Contains multiple technical concepts or functional points
172-
- Requires multiple steps to complete
173-
- Involves multiple chart types or multiple functions
174-
- Has clear workflow or combination requirements
93+
### Phase 2: Topic Extraction & Analysis
17594
176-
### 2.2: Topic Phrase Extraction
177-
- **Source Limitation**: Extract only from user query content, do not add concepts not present in the query
178-
- **CRITICAL: All topics MUST be in English** - Use official AntV English terminology from: ${
179-
libraryContext
180-
? getLibraryKeywords(libraryContext.id)
181-
: 'Use the terminology and components specific to the determined target library'
182-
}
183-
- 翻译和提取时,务必优先使用上方列出的官方组件英文名称,保持与官方文档一致,避免自创或误译,保持技术准确性
184-
- **Quantity Requirement**: Maximum ${maxTopics} items, can be fewer than this number
185-
- **Format Requirements**:
186-
- Extract meaningful phrase combinations (1-4 words)
187-
- Avoid single words or overly long sentences
188-
- Ensure diversity between terms, avoid repetition
189-
- **MANDATORY**: Output only English technical terms for documentation search
190-
- **Components, Concepts, Terminology**: ${libraryTerminology}
191-
- **Priority**:
192-
1. ${librarySpecificPriority}
193-
2. Chart types and visualization concepts
194-
3. Interaction, animation effects, data processing and configuration
95+
**Extract up to ${maxTopics} key technical topics covering ALL aspects mentioned:**
96+
- Extract only from user query content, no additional concepts
97+
- Use official AntV English terminology${libraryContext ? `: ${libraryContext.keywords}` : ''}
98+
- Format as meaningful phrases (1-4 words), output in English only
99+
- **Cover these technical aspects in priority order**:
100+
1. Chart types and core components
101+
2. Visual styling (colors, thickness, backgrounds, opacity)
102+
3. Interactions (hover, click, tooltip, zoom)
103+
4. Configurations (data processing, scales, axis, animations)
195104
196-
### 2.3: User Intent Recognition
105+
**Determine User Intent:**
197106
Based on the tone and content of the query, select the most matching intent:
198107
- **learn**: Learning and understanding (e.g., what is, how to understand, introduce)
199108
- **implement**: Implementing functionality (e.g., how to create, how to implement, code examples)
200109
- **solve**: Solving problems (e.g., errors, not working, fixing issues)
201110
202-
### 2.4: Complex Task Decomposition
203-
If determined to be a complex task, decompose into 2-4 subtasks, each subtask should:
111+
**Assess Task Complexity:**
112+
Determine if the query is complex based on:
113+
- Extracted topics exceed 5
114+
- Involves more than 2 components or features
115+
- Other cases where the query appears complex based on overall assessment (e.g., multi-step processes, combinations of features)
116+
117+
118+
If complex, decompose into 2-4 subtasks, each subtask should:
204119
- Focus on a specific technical point or functionality
205120
- Be able to independently obtain answers through documentation queries
206121
- Be arranged in logical order (basic → advanced)
207122
- Subtask topics must be clear, concise, and follow the format requirements above
208123
209-
**Note**: For complex tasks, provide the decomposed subtask list to the query_antv_document tool for one-time processing.`;
210-
}
124+
### Phase 3: Output Format
211125
212-
function generateOutputFormatSection(): string {
213-
return `### Simple Task Output Format:
126+
**For Simple Tasks:**
214127
\`\`\`json
215128
{
216-
"topic": "actually extracted topic1, topic2, topic3",
129+
"library": "detected_or_specified_library",
130+
"topic": "topic1, topic2, topic3",
217131
"intent": "learn|implement|solve",
218-
"library": "the target library (either specified or determined)",
219132
"isComplexTask": false
220133
}
221134
\`\`\`
222135
223-
### Complex Task Output Format:
136+
**For Complex Tasks:**
224137
\`\`\`json
225138
{
226-
"topic": "summary of all related topics",
227-
"intent": "overall intent",
228-
"library": "the target library (either specified or determined)",
139+
"library": "detected_or_specified_library",
140+
"topic": "overall_topic_summary",
141+
"intent": "overall_intent",
229142
"isComplexTask": true,
230143
"subTasks": [
231144
{
232-
"query": "specific question for subtask 1",
233-
"topic": "topic for subtask 1",
234-
"intent": "intent for subtask 1"
145+
"query": "specific_subtask_question_1",
146+
"topic": "subtask_topic_1"
235147
},
236148
{
237-
"query": "specific question for subtask 2",
238-
"topic": "topic for subtask 2",
239-
"intent": "intent for subtask 2"
149+
"query": "specific_subtask_question_2",
150+
"topic": "subtask_topic_2"
240151
}
241152
]
242153
}
243-
\`\`\``;
244-
}
245-
246-
function generateExamplesSection(): string {
247-
return `**Example 1 - Simple Task (English Query)**
248-
Query: "What is G2?"
249-
Output:
250-
\`\`\`json
251-
{
252-
"topic": "G2 introduction",
253-
"intent": "learn",
254-
"library": "g2",
255-
"isComplexTask": false
256-
}
257154
\`\`\`
258155
259-
**Example 2 - Simple Task (Chinese Query)**
260-
Query: "如何修改G2图表的颜色?"
261-
Output:
262-
\`\`\`json
263-
{
264-
"topic": "chart color, styling",
265-
"intent": "implement",
266-
"library": "g2",
267-
"isComplexTask": false
268-
}
269-
\`\`\`
156+
**Analyze the query and provide the structured output above.**
270157
271-
**Example 3 - Complex Task**
272-
Query: "How to create an animated bar chart with hover interaction in G2?"
273-
Output:
274-
\`\`\`json
275-
{
276-
"topic": "animated bar chart, chart animation, hover interaction, mouse events",
277-
"intent": "implement",
278-
"library": "g2",
279-
"isComplexTask": true,
280-
"subTasks": [
281-
{
282-
"query": "How to create a basic bar chart in G2?",
283-
"topic": "bar chart, chart creation",
284-
"intent": "implement"
285-
},
286-
{
287-
"query": "How to add animation effects to G2 charts?",
288-
"topic": "chart animation, animation effects",
289-
"intent": "implement"
290-
},
291-
{
292-
"query": "How to add hover interaction to G2 charts?",
293-
"topic": "hover interaction, mouse events",
294-
"intent": "implement"
295-
}
296-
]
297-
}
298-
\`\`\``;
158+
## Important Notice
159+
**MANDATORY NEXT STEP**: After completing this task, immediately call the \`query_antv_document\` tool with the extracted parameters.
160+
`;
299161
}
300162

301163
export const ExtractAntVTopicTool = {
@@ -321,8 +183,8 @@ Key features:
321183
const startTime = Date.now();
322184
try {
323185
const extractionPrompt = generateExtractionPrompt(args);
324-
const maxTopics = args.maxTopics;
325186
const processingTime = Date.now() - startTime;
187+
326188
return {
327189
content: [
328190
{
@@ -333,8 +195,8 @@ Key features:
333195
_meta: {
334196
topic: '', // Will be filled by LLM
335197
intent: '', // Will be filled by LLM
336-
library: args.library || 'g2',
337-
maxTopics,
198+
library: args.library || 'auto-detect',
199+
maxTopics: args.maxTopics,
338200
promptGenerated: true,
339201
next_tools: ['query_antv_document'],
340202
isComplexTask: false, // Will be determined and filled by LLM
@@ -344,18 +206,8 @@ Key features:
344206
};
345207
} catch (error) {
346208
logger.error('Failed to generate extraction prompt:', error);
347-
// Use safe fallbacks since validation might have failed
348-
const fallbackLibrary =
349-
args.library && Object.keys(ANTV_LIBRARY_META).includes(args.library)
350-
? args.library
351-
: 'g2';
352-
const fallbackMaxTopics =
353-
typeof args.maxTopics === 'number' &&
354-
args.maxTopics >= 3 &&
355-
args.maxTopics <= 8
356-
? args.maxTopics
357-
: 5;
358209
const processingTime = Date.now() - startTime;
210+
359211
return {
360212
content: [
361213
{
@@ -369,8 +221,8 @@ Key features:
369221
_meta: {
370222
topic: '',
371223
intent: '',
372-
library: fallbackLibrary,
373-
maxTopics: fallbackMaxTopics,
224+
library: args.library || 'auto-detect',
225+
maxTopics: args.maxTopics,
374226
promptGenerated: false,
375227
next_tools: ['query_antv_document'],
376228
isComplexTask: false,

0 commit comments

Comments
 (0)