-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathextract_antv_topic.ts
More file actions
236 lines (207 loc) Β· 8.07 KB
/
Copy pathextract_antv_topic.ts
File metadata and controls
236 lines (207 loc) Β· 8.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/**
* AntV Topic Extraction Tool - Preprocesses user queries for AntV libraries
*/
import { z } from 'zod';
import type { AntVLibrary } from '../types';
import { logger } from '../utils';
import {
getLibraryConfig,
getLibraryKeywords,
ANTV_LIBRARY_META,
} from '../constant';
const ExtractAntVTopicInputSchema = z.object({
query: z
.string()
.min(1, 'Query content cannot be empty')
.trim()
.refine((val) => val.length > 0, {
message: 'Query content cannot be empty after trimming',
})
.describe('User specific question or requirement description'),
library: z
.enum(Object.keys(ANTV_LIBRARY_META) as [AntVLibrary, ...AntVLibrary[]], {
errorMap: () => ({
message: `Unsupported library. Must be one of: ${Object.keys(ANTV_LIBRARY_META).join(', ')}`,
}),
})
.optional()
.describe(
'AntV library name (optional) - If not specified, tool will automatically detect project dependencies and intelligently recommend',
),
maxTopics: z
.number()
.int('MaxTopics must be an integer')
.min(3, 'MaxTopics must be at least 3')
.max(8, 'MaxTopics cannot exceed 8')
.default(5)
.describe(
'Maximum number of extracted topic keywords, default 5, can be increased appropriately for complex tasks',
),
});
interface ExtractAntVTopicArgs {
query: string;
library?: AntVLibrary;
maxTopics: number;
}
function generateExtractionPrompt(args: ExtractAntVTopicArgs): string {
const { query, library, maxTopics } = args;
// Generate library mappings
const libraryMappings = Object.values(ANTV_LIBRARY_META)
.map((lib) => ` - **${lib.name} (${lib.id})**: ${lib.description}`)
.join('\n');
// Get library-specific context if specified
const libraryContext = library
? {
name: getLibraryConfig(library).name,
keywords: getLibraryKeywords(library),
}
: null;
const libraryTerminology = libraryContext
? libraryContext.keywords
: 'Use the terminology and components specific to the determined target library';
return `# AntV Query Analysis & Topic Extraction
## User Query
**Query**: ${query}
**Max Topics**: ${maxTopics}
${library ? `**Specified Library**: ${getLibraryConfig(library).name} (${library})` : '**Library**: Auto-detect'}
## Task Instructions
### Phase 1: Library Detection ${library ? '(Skipped - Library Specified)' : ''}
${
library
? `Using specified library: **${getLibraryConfig(library).name} (${library})**`
: `**Determine the most suitable AntV library:**
Available Libraries:
${libraryMappings}
**Selection Priority:**
1. Match query intent with library purpose
2. Check for existing project dependencies
3. Consider common use cases for the query type`
}
### Phase 2: Topic Extraction & Analysis
**Extract up to ${maxTopics} key technical topics covering ALL aspects mentioned:**
- Extract only from user query content, no additional concepts
- Use official AntV English terminology${libraryContext ? `: ${libraryContext.keywords}` : ''}
- Format as meaningful phrases (1-4 words), output in English only
- **Cover these technical aspects in priority order**:
1. Chart types and core components
2. Visual styling (colors, thickness, backgrounds, opacity)
3. Interactions (hover, click, tooltip, zoom)
4. Configurations (data processing, scales, axis, animations)
**Determine User Intent:**
Based on the tone and content of the query, select the most matching intent:
- **learn**: Learning and understanding (e.g., what is, how to understand, introduce)
- **implement**: Implementing functionality (e.g., how to create, how to implement, code examples)
- **solve**: Solving problems (e.g., errors, not working, fixing issues)
**Assess Task Complexity:**
Determine if the query is complex based on:
- Extracted topics exceed 5
- Involves more than 2 components or features
- Other cases where the query appears complex based on overall assessment (e.g., multi-step processes, combinations of features)
If complex, decompose into 2-4 subtasks, each subtask should:
- Focus on a specific technical point or functionality
- Be able to independently obtain answers through documentation queries
- Be arranged in logical order (basic β advanced)
- Subtask topics must be clear, concise, and follow the format requirements above
### Phase 3: Output Format
**For Simple Tasks:**
\`\`\`json
{
"library": "detected_or_specified_library",
"topic": "topic1, topic2, topic3",
"intent": "learn|implement|solve",
"isComplexTask": false
}
\`\`\`
**For Complex Tasks:**
\`\`\`json
{
"library": "detected_or_specified_library",
"topic": "overall_topic_summary",
"intent": "overall_intent",
"isComplexTask": true,
"subTasks": [
{
"query": "specific_subtask_question_1",
"topic": "subtask_topic_1"
},
{
"query": "specific_subtask_question_2",
"topic": "subtask_topic_2"
}
]
}
\`\`\`
**Analyze the query and provide the structured output above.**
## Important Notice
**MANDATORY NEXT STEP**: After completing this task, immediately call the \`query_antv_document\` tool with the extracted parameters.
`;
}
export const ExtractAntVTopicTool = {
name: 'extract_antv_topic',
description: `AntV Intelligent Assistant Preprocessing Tool - Specifically designed to handle any user queries related to AntV visualization libraries.
This tool is the first step in processing AntV technology stack issues, responsible for intelligently identifying, parsing, and structuring user visualization requirements.
**MANDATORY: Must be called for ANY new AntV-related queries, including simple questions. Always precedes query_antv_document tool.**
When to use this tool:
- **AntV-related queries**: Questions about ${Object.keys(ANTV_LIBRARY_META).join('/')} libraries.
- **Visualization tasks**: Creating charts, graphs, maps, or other visualizations.
- **Problem solving**: Debugging errors, performance issues, or compatibility problems.
- **Learning & implementation**: Understanding concepts or requesting code examples.
Key features:
- **Smart Library Detection**: Scans installed AntV libraries and recommends the best fit based on query and project dependencies.
- **Topic & Intent Extraction**: Intelligently extracts technical topics and determines user intent (learn/implement/solve).
- **Task Complexity Handling**: Detects complex tasks and decomposes them into manageable subtasks.
- **Seamless Integration**: Prepares structured data for the query_antv_document tool to provide precise solutions.`,
inputSchema: ExtractAntVTopicInputSchema,
async run(args: ExtractAntVTopicArgs) {
const startTime = Date.now();
try {
const extractionPrompt = generateExtractionPrompt(args);
const processingTime = Date.now() - startTime;
return {
content: [
{
type: 'text',
text: extractionPrompt,
},
],
_meta: {
topic: '', // Will be filled by LLM
intent: '', // Will be filled by LLM
library: args.library || 'auto-detect',
maxTopics: args.maxTopics,
promptGenerated: true,
next_tools: ['query_antv_document'],
isComplexTask: false, // Will be determined and filled by LLM
subTasks: [], // If complex task, will be filled with subtasks by LLM
processingTime,
},
};
} catch (error) {
logger.error('Failed to generate extraction prompt:', error);
const processingTime = Date.now() - startTime;
return {
content: [
{
type: 'text',
text: `β Failed to generate extraction task: ${
error instanceof Error ? error.message : 'Unknown error'
}`,
},
],
isError: true,
_meta: {
topic: '',
intent: '',
library: args.library || 'auto-detect',
maxTopics: args.maxTopics,
promptGenerated: false,
next_tools: ['query_antv_document'],
isComplexTask: false,
subTasks: [],
processingTime,
error: error instanceof Error ? error.message : 'Unknown error',
},
};
}
},
};