-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.js
More file actions
283 lines (254 loc) · 8.57 KB
/
agent.js
File metadata and controls
283 lines (254 loc) · 8.57 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
const OpenAI = require('openai');
const fs = require('fs');
// 检查必需的环境变量
const isTestMode = process.env.OPENAI_API_KEY === 'test_key_for_local_development';
if (!process.env.OPENAI_API_KEY && !isTestMode) {
console.error('Error: OPENAI_API_KEY environment variable is required');
process.exit(1);
}
// 初始化OpenAI客户端
const openai = isTestMode
? null
: new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
// 加载产品数据
let productsData, categoriesData;
try {
productsData = JSON.parse(fs.readFileSync('./products.json', 'utf8'));
categoriesData = JSON.parse(fs.readFileSync('./categories.json', 'utf8'));
console.log(`Loaded ${productsData.length} product categories`);
} catch (error) {
console.error('Error loading product data:', error.message);
console.error('Please ensure products.json and categories.json exist');
process.exit(1);
}
// 意图识别函数
async function classifyIntent(userInput) {
// 在测试模式下使用简单的关键词匹配
if (isTestMode) {
const input = userInput.toLowerCase();
if (input.includes('compare') || input.includes('vs') || input.includes('versus')) {
return 'product_comparison';
} else if (input.includes('spec') || input.includes('speed') || input.includes('port')) {
return 'spec_query';
} else if (input.includes('feature') || input.includes('function')) {
return 'feature_query';
} else if (input.includes('recommend') || input.includes('need') || input.includes('looking')) {
return 'product_recommendation';
}
return 'unknown';
}
const prompt = `You are a professional AI assistant for TP-Link's official website, specialized in recommending, comparing, and explaining TP-Link networking products.
Classify the user's intent into one of the following categories:
- product_recommendation: User wants product recommendations based on their needs
- product_comparison: User wants to compare products
- spec_query: User wants to know product specifications
- feature_query: User wants to know about product features
- service_query: User asks about services like HomeShield, Tapo Care
- topic_redirect: User wants to be redirected to specific topics
- unknown: Cannot determine intent
User input: "${userInput}"
Respond with only the intent category.`;
try {
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: prompt }],
max_tokens: 50,
temperature: 0.1
});
return response.choices[0].message.content.trim();
} catch (error) {
console.error('Intent classification error:', error);
return 'unknown';
}
}
// 产品推荐工具
function productRecommendation(query) {
const recommendations = [];
// 简单的关键词匹配逻辑
const keywords = query.toLowerCase().split(' ');
for (const category of productsData) {
for (const product of category.products) {
let score = 0;
// 检查产品名称和描述中的关键词匹配
const productText = `${product.name} ${product.description || ''}`.toLowerCase();
for (const keyword of keywords) {
if (productText.includes(keyword)) {
score += 1;
}
}
if (score > 0) {
recommendations.push({
name: product.name,
category: category.category,
description: product.description,
url: product.url,
score: score
});
}
}
}
// 按匹配度排序,返回前3个推荐
return recommendations
.sort((a, b) => b.score - a.score)
.slice(0, 3);
}
// 产品对比工具
function compareProducts(productNames) {
const products = [];
for (const name of productNames) {
for (const category of productsData) {
const product = category.products.find(p => {
const productName = p.name.toLowerCase();
const searchName = name.toLowerCase();
return productName.includes(searchName) ||
productName.includes('be' + searchName.replace('be', '')) ||
(searchName.includes('be65') && productName.includes('be11000')) ||
(searchName.includes('be95') && productName.includes('be33000'));
});
if (product) {
products.push(product);
break;
}
}
}
if (products.length < 2) {
return { error: 'Need at least 2 products to compare' };
}
// 创建对比表
const comparison = {
products: products.map(p => ({
name: p.name,
category: p.category,
url: p.url,
specs: p.specs || {}
})),
comparison: {}
};
// 对比关键规格
const keySpecs = ['WiFi Speeds', 'WiFi Range', 'Ethernet Ports', 'Working Modes'];
for (const spec of keySpecs) {
comparison.comparison[spec] = {};
for (const product of products) {
comparison.comparison[spec][product.name] = product.specs[spec] || 'N/A';
}
}
return comparison;
}
// 规格查询工具
function querySpec(model, spec) {
for (const category of productsData) {
for (const product of category.products) {
const productName = product.name.toLowerCase();
const searchModel = model.toLowerCase();
if (productName.includes(searchModel) ||
(searchModel.includes('be65') && productName.includes('be11000')) ||
(searchModel.includes('be95') && productName.includes('be33000'))) {
if (spec) {
return {
product: product.name,
spec: spec,
value: product.specs[spec] || 'Not found'
};
} else {
return {
product: product.name,
specs: product.specs
};
}
}
}
}
return { error: 'Product not found' };
}
// 功能查询工具
function queryFeatures(model, feature) {
for (const category of productsData) {
for (const product of category.products) {
const productName = product.name.toLowerCase();
const searchModel = model.toLowerCase();
if (productName.includes(searchModel) ||
(searchModel.includes('be65') && productName.includes('be11000')) ||
(searchModel.includes('be95') && productName.includes('be33000'))) {
if (feature) {
// 检查功能是否在features数组中
const hasFeature = product.features.some(f =>
f.toLowerCase().includes(feature.toLowerCase())
);
return {
product: product.name,
feature: feature,
hasFeature: hasFeature,
features: product.features
};
} else {
return {
product: product.name,
features: product.features
};
}
}
}
}
return { error: 'Product not found' };
}
// 主Agent函数
async function processUserQuery(userInput) {
try {
// 1. 意图识别
const intent = await classifyIntent(userInput);
console.log('Detected intent:', intent);
// 2. 根据意图调用相应工具
let result;
switch (intent) {
case 'product_recommendation':
result = productRecommendation(userInput);
break;
case 'product_comparison':
// 提取产品名称进行对比
const productNames = userInput.match(/BE[0-9]+/g) ||
userInput.match(/Deco\s+[A-Z0-9]+/g) ||
userInput.match(/[A-Z][A-Za-z0-9\s-]+/g) || [];
result = compareProducts(productNames);
break;
case 'spec_query':
// 提取型号和规格
const specMatch = userInput.match(/(BE[0-9]+)/i);
if (specMatch) {
result = querySpec(specMatch[1], 'WiFi Speeds');
} else {
result = { error: 'Please specify product model and specification' };
}
break;
case 'feature_query':
// 简单提取型号和功能
const featureMatch = userInput.match(/([A-Z][A-Za-z0-9\s-]+).*?(feature|function|capability)/i);
if (featureMatch) {
result = queryFeatures(featureMatch[1], featureMatch[2]);
} else {
result = { error: 'Please specify product model and feature' };
}
break;
default:
result = { error: 'I cannot understand your request. Please try rephrasing.' };
}
return {
intent: intent,
result: result
};
} catch (error) {
console.error('Agent processing error:', error);
return {
intent: 'error',
result: { error: 'An error occurred while processing your request.' }
};
}
}
module.exports = {
processUserQuery,
productRecommendation,
compareProducts,
querySpec,
queryFeatures
};