0%

Skills 2.0——OpenAI最新函数调用技术深度解析

最近研究OpenAI的新功能,发现Skills 2.0函数调用简直是AI编程的一大突破。就像给AI装上了“遥控器”,让它可以精确操控外部工具和API…

介绍

  OpenAI最新推出的Skills 2.0函数调用技术标志着AI编程的一个重要里程碑。这项技术不仅改进了原有的函数调用机制,还引入了更智能的工具选择、更精细的参数验证和更强大的错误处理能力。本文将深入探讨Skills 2.0的核心特性、实现方式及其在实际开发中的应用。

Skills 2.0核心特性

智能工具选择机制

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
// Skills 2.0智能工具选择示例
class Skills2FunctionCaller {
constructor(model, apiKey) {
this.model = model;
this.apiKey = apiKey;
this.tools = new Map();
this.history = [];
}

// 注册工具
registerTool(name, definition, handler) {
this.tools.set(name, {
definition: {
type: 'function',
function: {
name: name,
description: definition.description,
parameters: definition.parameters
}
},
handler: handler,
metadata: definition.metadata || {}
});
}

// 智能调用工具
async callTools(userQuery, context = {}) {
const toolDefinitions = Array.from(this.tools.values()).map(t => t.definition);

const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
model: this.model,
messages: [
{
role: 'system',
content: `你是一个智能工具调用助手。根据用户需求选择合适的工具并生成正确的参数。`
},
{
role: 'user',
content: userQuery
},
...this.buildContextMessages(context)
],
tools: toolDefinitions,
tool_choice: 'auto', // 自动选择工具
temperature: 0.1
})
});

const result = await response.json();

if (result.choices && result.choices[0].message.tool_calls) {
const toolCalls = result.choices[0].message.tool_calls;
const toolResponses = [];

for (const toolCall of toolCalls) {
const toolName = toolCall.function.name;
const toolArgs = JSON.parse(toolCall.function.arguments);

const tool = this.tools.get(toolName);
if (tool) {
try {
const response = await tool.handler(toolArgs);
toolResponses.push({
tool_call_id: toolCall.id,
role: 'tool',
name: toolName,
content: JSON.stringify(response)
});
} catch (error) {
toolResponses.push({
tool_call_id: toolCall.id,
role: 'tool',
name: toolName,
content: JSON.stringify({ error: error.message })
});
}
}
}

// 继续对话
const finalResponse = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
model: this.model,
messages: [
{
role: 'user',
content: userQuery
},
...toolCalls.map(tc => ({
role: 'assistant',
content: null,
tool_calls: [tc]
})),
...toolResponses
],
temperature: 0.7
})
});

return await finalResponse.json();
}

return result;
}

// 构建上下文消息
buildContextMessages(context) {
const messages = [];

if (context.userProfile) {
messages.push({
role: 'system',
content: `用户偏好: ${JSON.stringify(context.userProfile)}`
});
}

if (context.location) {
messages.push({
role: 'system',
content: `用户位置: ${context.location}`
});
}

if (context.time) {
messages.push({
role: 'system',
content: `当前时间: ${new Date(context.time).toISOString()}`
});
}

return messages;
}
}

// 使用示例
const skillsCaller = new Skills2FunctionCaller('gpt-4-turbo', 'your-api-key');

// 注册天气查询工具
skillsCaller.registerTool('get_weather', {
description: '获取指定城市的天气信息',
parameters: {
type: 'object',
properties: {
city: {
type: 'string',
description: '城市名称'
},
units: {
type: 'string',
enum: ['metric', 'imperial'],
default: 'metric',
description: '温度单位'
}
},
required: ['city']
}
}, async (args) => {
// 模拟天气API调用
const weatherData = {
city: args.city,
temperature: Math.floor(Math.random() * 30) + 10,
condition: ['sunny', 'cloudy', 'rainy'][Math.floor(Math.random() * 3)]);
return weatherData;
});

// 注册数据库查询工具
skillsCaller.registerTool('query_database', {
description: '查询数据库获取用户信息',
parameters: {
type: 'object',
properties: {
query_type: {
type: 'string',
enum: ['user_info', 'order_history', 'analytics'],
description: '查询类型'
},
user_id: {
type: 'string',
description: '用户ID'
},
limit: {
type: 'number',
default: 10,
description: '返回结果数量限制'
}
},
required: ['query_type']
}
}, async (args) => {
// 模拟数据库查询
return {
results: [{ id: 1, name: 'John Doe', email: 'john@example.com' }],
count: 1
};
});

参数验证与类型检查

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
// Skills 2.0参数验证系统
class ParameterValidator {
constructor() {
this.validators = new Map();
this.setupDefaultValidators();
}

// 设置默认验证器
setupDefaultValidators() {
this.validators.set('string', this.validateString.bind(this));
this.validators.set('number', this.validateNumber.bind(this));
this.validators.set('integer', this.validateInteger.bind(this));
this.validators.set('boolean', this.validateBoolean.bind(this));
this.validators.set('array', this.validateArray.bind(this));
this.validators.set('object', this.validateObject.bind(this));
}

// 验证参数
validate(parameters, schema) {
const errors = [];

// 检查必需参数
if (schema.required) {
for (const requiredParam of schema.required) {
if (!(requiredParam in parameters)) {
errors.push(`Required parameter '${requiredParam}' is missing`);
}
}
}

// 验证每个参数
for (const [paramName, paramValue] of Object.entries(parameters)) {
if (schema.properties && schema.properties[paramName]) {
const paramSchema = schema.properties[paramName];
const error = this.validateParameter(paramValue, paramSchema, paramName);
if (error) {
errors.push(error);
}
}
}

return {
isValid: errors.length === 0,
errors: errors
};
}

// 验证单个参数
validateParameter(value, schema, paramName) {
const type = schema.type;
const validator = this.validators.get(type);

if (!validator) {
return `Unsupported parameter type: ${type} for ${paramName}`;
}

const result = validator(value, schema, paramName);
return result;
}

// 验证字符串
validateString(value, schema, paramName) {
if (typeof value !== 'string') {
return `Parameter '${paramName}' must be a string`;
}

if (schema.minLength && value.length < schema.minLength) {
return `Parameter '${paramName}' must be at least ${schema.minLength} characters long`;
}

if (schema.maxLength && value.length > schema.maxLength) {
return `Parameter '${paramName}' must be at most ${schema.maxLength} characters long`;
}

if (schema.pattern && !new RegExp(schema.pattern).test(value)) {
return `Parameter '${paramName}' does not match required pattern`;
}

if (schema.enum && !schema.enum.includes(value)) {
return `Parameter '${paramName}' must be one of: ${schema.enum.join(', ')}`;
}

return null;
}

// 验证数字
validateNumber(value, schema, paramName) {
if (typeof value !== 'number') {
return `Parameter '${paramName}' must be a number`;
}

if (schema.minimum !== undefined && value < schema.minimum) {
return `Parameter '${paramName}' must be greater than or equal to ${schema.minimum}`;
}

if (schema.maximum !== undefined && value > schema.maximum) {
return `Parameter '${paramName}' must be less than or equal to ${schema.maximum}`;
}

if (schema.exclusiveMinimum && value <= schema.exclusiveMinimum) {
return `Parameter '${paramName}' must be greater than ${schema.exclusiveMinimum}`;
}

if (schema.exclusiveMaximum && value >= schema.exclusiveMaximum) {
return `Parameter '${paramName}' must be less than ${schema.exclusiveMaximum}`;
}

return null;
}

// 验证整数
validateInteger(value, schema, paramName) {
if (!Number.isInteger(value)) {
return `Parameter '${paramName}' must be an integer`;
}

return this.validateNumber(value, schema, paramName);
}

// 验证布尔值
validateBoolean(value, schema, paramName) {
if (typeof value !== 'boolean') {
return `Parameter '${paramName}' must be a boolean`;
}

return null;
}

// 验证数组
validateArray(value, schema, paramName) {
if (!Array.isArray(value)) {
return `Parameter '${paramName}' must be an array`;
}

if (schema.minItems !== undefined && value.length < schema.minItems) {
return `Parameter '${paramName}' must have at least ${schema.minItems} items`;
}

if (schema.maxItems !== undefined && value.length > schema.maxItems) {
return `Parameter '${paramName}' must have at most ${schema.maxItems} items`;
}

if (schema.items) {
for (let i = 0; i < value.length; i++) {
const itemError = this.validateParameter(value[i], schema.items, `${paramName}[${i}]`);
if (itemError) {
return itemError;
}
}
}

return null;
}

// 验证对象
validateObject(value, schema, paramName) {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
return `Parameter '${paramName}' must be an object`;
}

if (schema.properties) {
for (const [propName, propSchema] of Object.entries(schema.properties)) {
if (value[propName] !== undefined) {
const error = this.validateParameter(value[propName], propSchema, `${paramName}.${propName}`);
if (error) {
return error;
}
}
}
}

return null;
}
}

// 增强版工具注册系统
class EnhancedSkills2Manager {
constructor(apiKey, model = 'gpt-4-turbo') {
this.apiKey = apiKey;
this.model = model;
this.tools = new Map();
this.validator = new ParameterValidator();
}

// 注册增强工具
registerEnhancedTool(name, definition, handler) {
// 验证定义格式
if (!this.isValidDefinition(definition)) {
throw new Error(`Invalid tool definition for ${name}`);
}

// 添加验证
this.tools.set(name, {
definition: {
type: 'function',
function: {
name: name,
description: definition.description,
parameters: definition.parameters
}
},
handler: handler,
metadata: {
...definition.metadata,
validated: true,
lastUpdated: Date.now()
}
});
}

// 验证定义格式
isValidDefinition(definition) {
return definition &&
definition.description &&
definition.parameters &&
typeof definition.parameters === 'object';
}

// 调用工具(带参数验证)
async callToolWithValidation(toolName, parameters) {
const tool = this.tools.get(toolName);
if (!tool) {
throw new Error(`Tool not found: ${toolName}`);
}

// 验证参数
const validation = this.validator.validate(parameters, tool.definition.function.parameters);
if (!validation.isValid) {
throw new Error(`Parameter validation failed: ${validation.errors.join(', ')}`);
}

try {
return await tool.handler(parameters);
} catch (error) {
console.error(`Tool execution error for ${toolName}:`, error);
throw error;
}
}
}

错误处理与重试机制

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
// Skills 2.0错误处理系统
class Skills2ErrorHandler {
constructor(options = {}) {
this.options = {
maxRetries: options.maxRetries || 3,
retryDelay: options.retryDelay || 1000,
exponentialBackoff: options.exponentialBackoff !== false,
retryableErrors: options.retryableErrors || [
'rate_limit_exceeded',
'network_error',
'timeout',
'temporarily_unavailable'
]
};
}

// 执行带重试的操作
async executeWithRetry(operation, context = {}) {
let lastError;
let retryCount = 0;

while (retryCount <= this.options.maxRetries) {
try {
const result = await operation(retryCount);

// 记录成功调用
this.logSuccess(context, result, retryCount);

return result;
} catch (error) {
lastError = error;
const shouldRetry = this.shouldRetry(error, retryCount);

if (!shouldRetry) {
break;
}

const delay = this.calculateDelay(retryCount);
console.log(`Retry attempt ${retryCount + 1}/${this.options.maxRetries} after ${delay}ms:`, error.message);

await this.sleep(delay);
retryCount++;
}
}

// 记录最终失败
this.logFailure(context, lastError, retryCount);

throw lastError;
}

// 判断是否应该重试
shouldRetry(error, retryCount) {
if (retryCount >= this.options.maxRetries) {
return false;
}

const errorType = this.getErrorType(error);
return this.options.retryableErrors.includes(errorType);
}

// 获取错误类型
getErrorType(error) {
if (error.type) {
return error.type;
}

if (error.message) {
const message = error.message.toLowerCase();

if (message.includes('rate limit')) {
return 'rate_limit_exceeded';
}

if (message.includes('timeout') || message.includes('timed out')) {
return 'timeout';
}

if (message.includes('network error') || message.includes('fetch failed')) {
return 'network_error';
}

if (message.includes('503') || message.includes('service unavailable')) {
return 'temporarily_unavailable';
}
}

return 'unknown';
}

// 计算延迟时间
calculateDelay(retryCount) {
if (this.options.exponentialBackoff) {
return this.options.retryDelay * Math.pow(2, retryCount);
}

return this.options.retryDelay;
}

// 睡眠函数
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

// 记录成功
logSuccess(context, result, retries) {
console.log('✅ Skills 2.0 operation succeeded', {
tool: context.toolName,
retries: retries,
timestamp: new Date().toISOString()
});
}

// 记录失败
logFailure(context, error, retries) {
console.error('❌ Skills 2.0 operation failed', {
tool: context.toolName,
error: error.message,
retries: retries,
timestamp: new Date().toISOString()
});
}
}

// 增强的函数调用器
class AdvancedSkills2Caller extends Skills2FunctionCaller {
constructor(model, apiKey, errorHandlerOptions = {}) {
super(model, apiKey);
this.errorHandler = new Skills2ErrorHandler(errorHandlerOptions);
this.metrics = {
totalCalls: 0,
successfulCalls: 0,
failedCalls: 0,
averageLatency: 0
};
}

// 带错误处理的工具调用
async callToolWithErrorHandling(toolName, parameters, context = {}) {
const startTime = Date.now();

return this.errorHandler.executeWithRetry(async (retryAttempt) => {
try {
const tool = this.tools.get(toolName);
if (!tool) {
throw new Error(`Tool not found: ${toolName}`);
}

const result = await tool.handler(parameters);

// 更新指标
this.updateMetrics(true, Date.now() - startTime);

return result;
} catch (error) {
// 更新指标
this.updateMetrics(false, Date.now() - startTime);

// 重新抛出错误以触发重试
throw error;
}
}, {
toolName,
retryAttempt,
startTime
});
}

// 更新调用指标
updateMetrics(success, latency) {
this.metrics.totalCalls++;

if (success) {
this.metrics.successfulCalls++;
} else {
this.metrics.failedCalls++;
}

// 更新平均延迟
this.metrics.averageLatency =
((this.metrics.averageLatency * (this.metrics.totalCalls - 1)) + latency) / this.metrics.totalCalls;
}

// 获取调用统计
getMetrics() {
return {
...this.metrics,
successRate: this.metrics.totalCalls > 0 ?
(this.metrics.successfulCalls / this.metrics.totalCalls) * 100 : 0
};
}

// 批量调用工具
async batchCall(tools) {
const results = [];
const errors = [];

for (const toolCall of tools) {
try {
const result = await this.callToolWithErrorHandling(
toolCall.toolName,
toolCall.parameters,
{ batchIndex: toolCall.index }
);
results.push({ success: true, result, index: toolCall.index });
} catch (error) {
errors.push({ success: false, error: error.message, index: toolCall.index });
}
}

return { results, errors };
}
}

Skills 2.0实战应用

电商场景应用

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
// 电商场景的Skills 2.0实现
class EcommerceSkills2System {
constructor(apiKey) {
this.caller = new AdvancedSkills2Caller('gpt-4-turbo', apiKey);
this.setupEcommerceTools();
}

// 设置电商工具
setupEcommerceTools() {
// 产品搜索工具
this.caller.registerTool('search_products', {
description: '根据关键词搜索产品',
parameters: {
type: 'object',
properties: {
query: {
type: 'string',
description: '搜索关键词'
},
category: {
type: 'string',
description: '产品分类'
},
price_range: {
type: 'object',
properties: {
min: { type: 'number' },
max: { type: 'number' }
}
},
limit: {
type: 'number',
default: 10,
description: '返回结果数量'
}
},
required: ['query']
}
}, async (args) => {
// 模拟产品搜索
const products = [
{ id: 1, name: 'iPhone 15 Pro', price: 999, category: 'electronics' },
{ id: 2, name: 'Samsung Galaxy S24', price: 899, category: 'electronics' },
{ id: 3, name: 'MacBook Air M2', price: 1099, category: 'computers' }
];

return {
products: products.slice(0, args.limit || 10),
total_count: products.length,
search_query: args.query
};
});

// 库存检查工具
this.caller.registerTool('check_inventory', {
description: '检查特定产品的库存情况',
parameters: {
type: 'object',
properties: {
product_ids: {
type: 'array',
items: { type: 'string' },
description: '产品ID列表'
}
},
required: ['product_ids']
}
}, async (args) => {
// 模拟库存检查
const inventory = {};
for (const productId of args.product_ids) {
inventory[productId] = {
stock: Math.floor(Math.random() * 100),
available: Math.random() > 0.2 // 80%概率有货
};
}

return { inventory };
});

// 订单创建工具
this.caller.registerTool('create_order', {
description: '创建新订单',
parameters: {
type: 'object',
properties: {
customer_id: { type: 'string', description: '客户ID' },
items: {
type: 'array',
items: {
type: 'object',
properties: {
product_id: { type: 'string' },
quantity: { type: 'number' },
price: { type: 'number' }
},
required: ['product_id', 'quantity', 'price']
}
},
shipping_address: {
type: 'object',
properties: {
street: { type: 'string' },
city: { type: 'string' },
zip_code: { type: 'string' },
country: { type: 'string' }
},
required: ['street', 'city', 'zip_code', 'country']
},
payment_method: { type: 'string' }
},
required: ['customer_id', 'items', 'shipping_address']
}
}, async (args) => {
// 模拟订单创建
const orderId = `ORD-${Date.now()}-${Math.random().toString(36).substr(2, 6).toUpperCase()}`;

return {
order_id: orderId,
status: 'created',
total_amount: args.items.reduce((sum, item) => sum + (item.price * item.quantity), 0),
estimated_delivery: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString()
};
});

// 支付处理工具
this.caller.registerTool('process_payment', {
description: '处理支付请求',
parameters: {
type: 'object',
properties: {
order_id: { type: 'string', description: '订单ID' },
amount: { type: 'number', description: '支付金额' },
payment_method: {
type: 'object',
properties: {
type: { type: 'string', enum: ['credit_card', 'paypal', 'bank_transfer'] },
details: { type: 'object' }
},
required: ['type', 'details']
},
currency: { type: 'string', default: 'USD' }
},
required: ['order_id', 'amount', 'payment_method']
}
}, async (args) => {
// 模拟支付处理
return {
transaction_id: `TXN-${Date.now()}`,
status: 'approved',
timestamp: new Date().toISOString(),
payment_method: args.payment_method.type
};
});
}

// 处理电商对话
async handleEcommerceQuery(userQuery, customerId = null) {
const context = {
userProfile: { customerId },
time: new Date().toISOString()
};

try {
const result = await this.caller.callTools(userQuery, context);
return result;
} catch (error) {
console.error('Ecommerce query error:', error);
return {
error: error.message,
suggestion: '请稍后重试或联系客服'
};
}
}

// 完整购物流程示例
async processPurchaseFlow(customerId, searchQuery, shippingAddress, paymentMethod) {
const steps = [];

try {
// 步骤1: 搜索产品
steps.push({
step: 'search',
result: await this.caller.callToolWithErrorHandling('search_products', {
query: searchQuery,
limit: 5
})
});

if (!steps[0].result.products || steps[0].result.products.length === 0) {
throw new Error('未找到匹配的产品');
}

const selectedProduct = steps[0].result.products[0];

// 步骤2: 检查库存
steps.push({
step: 'inventory_check',
result: await this.caller.callToolWithErrorHandling('check_inventory', {
product_ids: [selectedProduct.id.toString()]
})
});

if (!steps[1].result.inventory[selectedProduct.id]?.available) {
throw new Error('所选产品暂无库存');
}

// 步骤3: 创建订单
steps.push({
step: 'create_order',
result: await this.caller.callToolWithErrorHandling('create_order', {
customer_id: customerId,
items: [{
product_id: selectedProduct.id,
quantity: 1,
price: selectedProduct.price
}],
shipping_address: shippingAddress,
payment_method: paymentMethod
})
});

const orderId = steps[2].result.order_id;

// 步骤4: 处理支付
steps.push({
step: 'process_payment',
result: await this.caller.callToolWithErrorHandling('process_payment', {
order_id: orderId,
amount: selectedProduct.price,
payment_method: {
type: paymentMethod,
details: {} // 简化示例
}
})
});

return {
success: true,
order_id: orderId,
steps: steps,
total_amount: selectedProduct.price
};

} catch (error) {
return {
success: false,
error: error.message,
completed_steps: steps
};
}
}
}

金融场景应用

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
// 金融场景的Skills 2.0实现
class FinancialSkills2System {
constructor(apiKey) {
this.caller = new AdvancedSkills2Caller('gpt-4-turbo', apiKey);
this.setupFinancialTools();
}

// 设置金融工具
setupFinancialTools() {
// 账户余额查询
this.caller.registerTool('get_account_balance', {
description: '查询指定账户的余额信息',
parameters: {
type: 'object',
properties: {
account_number: { type: 'string', description: '账户号码' },
account_type: {
type: 'string',
enum: ['checking', 'savings', 'investment'],
description: '账户类型'
}
},
required: ['account_number']
}
}, async (args) => {
// 模拟账户查询
return {
account_number: args.account_number,
balance: parseFloat((Math.random() * 10000).toFixed(2)),
currency: 'USD',
available_balance: parseFloat((Math.random() * 9000).toFixed(2)),
last_updated: new Date().toISOString()
};
});

// 交易历史查询
this.caller.registerTool('get_transaction_history', {
description: '获取账户交易历史',
parameters: {
type: 'object',
properties: {
account_number: { type: 'string', description: '账户号码' },
start_date: { type: 'string', format: 'date', description: '开始日期' },
end_date: { type: 'string', format: 'date', description: '结束日期' },
limit: { type: 'number', default: 10, description: '返回条目数量' }
},
required: ['account_number', 'start_date', 'end_date']
}
}, async (args) => {
// 模拟交易历史
const transactions = [];
for (let i = 0; i < (args.limit || 10); i++) {
transactions.push({
id: `TXN-${Date.now()}-${i}`,
date: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
type: ['deposit', 'withdrawal', 'transfer'][Math.floor(Math.random() * 3)],
amount: parseFloat((Math.random() * 1000).toFixed(2)) * (Math.random() > 0.5 ? 1 : -1),
description: ['Salary', 'Grocery Store', 'Online Purchase', 'ATM Withdrawal'][Math.floor(Math.random() * 4)]
});
}

return {
transactions,
total_count: transactions.length,
account_number: args.account_number
};
});

// 转账操作
this.caller.registerTool('transfer_funds', {
description: '执行资金转账',
parameters: {
type: 'object',
properties: {
from_account: { type: 'string', description: '转出账户' },
to_account: { type: 'string', description: '转入账户' },
amount: { type: 'number', description: '转账金额' },
currency: { type: 'string', default: 'USD' },
description: { type: 'string', description: '转账备注' }
},
required: ['from_account', 'to_account', 'amount']
}
}, async (args) => {
// 模拟转账
const transactionId = `TRANSFER-${Date.now()}-${Math.random().toString(36).substr(2, 8).toUpperCase()}`;

return {
transaction_id: transactionId,
status: 'pending_approval', // 需要人工审核大额转账
from_account: args.from_account,
to_account: args.to_account,
amount: args.amount,
timestamp: new Date().toISOString(),
fees: args.amount > 1000 ? parseFloat((args.amount * 0.001).toFixed(2)) : 0 // 大额转账手续费
};
});

// 投资组合分析
this.caller.registerTool('analyze_portfolio', {
description: '分析投资组合表现',
parameters: {
type: 'object',
properties: {
portfolio_id: { type: 'string', description: '投资组合ID' },
risk_tolerance: {
type: 'string',
enum: ['conservative', 'moderate', 'aggressive'],
description: '风险承受能力'
},
time_horizon: {
type: 'string',
enum: ['short_term', 'medium_term', 'long_term'],
description: '投资期限'
}
},
required: ['portfolio_id']
}
}, async (args) => {
// 模拟投资组合分析
return {
portfolio_id: args.portfolio_id,
current_value: parseFloat((Math.random() * 50000 + 10000).toFixed(2)),
total_return: parseFloat((Math.random() * 20 - 5).toFixed(2)), // -5% to +15%
risk_score: Math.floor(Math.random() * 100),
allocation: {
stocks: parseFloat((Math.random() * 60 + 20).toFixed(2)),
bonds: parseFloat((Math.random() * 30).toFixed(2)),
cash: parseFloat((Math.random() * 10).toFixed(2))
},
recommendations: [
'考虑增加科技股配置',
'债券部分可以适当调整久期',
'现金比例略高,可考虑再投资'
]
};
});
}

// 处理金融查询
async handleFinancialQuery(userQuery, context = {}) {
try {
const result = await this.caller.callTools(userQuery, context);
return result;
} catch (error) {
console.error('Financial query error:', error);
return {
error: '处理金融请求时发生错误,请稍后重试',
code: 'FINANCIAL_ERROR'
};
}
}

// 风险控制检查
async performRiskCheck(userId, action, amount) {
// 这里可以集成更复杂的风控逻辑
const riskFactors = {
high_amount: amount > 10000,
frequency: Math.random() > 0.8, // 模拟高频交易
account_age: Math.random() > 0.7, // 模拟新账户
location_anomaly: Math.random() > 0.9 // 模拟异地登录
};

const riskScore = Object.values(riskFactors).filter(Boolean).length;

return {
risk_level: riskScore > 2 ? 'high' : riskScore > 0 ? 'medium' : 'low',
risk_factors: riskFactors,
proceed: riskScore <= 1, // 低风险或中风险可继续
additional_verification_required: riskScore > 1
};
}
}

Skills 2.0最佳实践

性能优化

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
// Skills 2.0性能优化工具
class Skills2PerformanceOptimizer {
constructor() {
this.cache = new Map();
this.cacheExpiry = new Map();
this.budgetManager = new Map();
}

// 带缓存的工具调用
async callToolWithCache(toolName, parameters, ttl = 300000) { // 5分钟默认TTL
const cacheKey = this.generateCacheKey(toolName, parameters);

// 检查缓存
if (this.isCacheValid(cacheKey, ttl)) {
return this.cache.get(cacheKey);
}

// 执行工具调用
const result = await this.executeToolCall(toolName, parameters);

// 存储到缓存
this.cache.set(cacheKey, result);
this.cacheExpiry.set(cacheKey, Date.now() + ttl);

return result;
}

// 生成缓存键
generateCacheKey(toolName, parameters) {
return `${toolName}:${JSON.stringify(parameters)}`;
}

// 检查缓存是否有效
isCacheValid(cacheKey, ttl) {
const expiry = this.cacheExpiry.get(cacheKey);
return expiry && Date.now() < expiry;
}

// 执行工具调用
async executeToolCall(toolName, parameters) {
// 这里应该集成实际的工具调用逻辑
// 模拟工具调用
return {
result: `Mock result for ${toolName}`,
timestamp: Date.now(),
parameters
};
}

// 并行工具调用
async parallelCall(tools) {
const promises = tools.map(tool =>
this.callToolWithCache(tool.name, tool.parameters, tool.ttl || 300000)
);

return Promise.all(promises);
}

// 批量工具调用
async batchCall(tools, batchSize = 5) {
const results = [];

for (let i = 0; i < tools.length; i += batchSize) {
const batch = tools.slice(i, i + batchSize);
const batchResults = await Promise.all(
batch.map(tool => this.callToolWithCache(tool.name, tool.parameters))
);
results.push(...batchResults);
}

return results;
}

// 预热缓存
async warmUpCache(toolCalls) {
const warmUpPromises = toolCalls.map(call =>
this.callToolWithCache(call.name, call.parameters, call.ttl)
);

await Promise.all(warmUpPromises);
}
}

// 限流管理器
class RateLimiter {
constructor(maxRequests = 10, windowMs = 60000) {
this.maxRequests = maxRequests;
this.windowMs = windowMs;
this.requests = new Map();
}

// 检查是否允许请求
async isAllowed(identifier) {
const now = Date.now();
const key = identifier || 'default';

if (!this.requests.has(key)) {
this.requests.set(key, []);
}

const timestamps = this.requests.get(key);

// 清理过期请求
const validRequests = timestamps.filter(ts => ts > now - this.windowMs);

if (validRequests.length >= this.maxRequests) {
return false;
}

// 添加当前请求
validRequests.push(now);
this.requests.set(key, validRequests);

return true;
}

// 获取剩余请求次数
getRemainingRequests(identifier) {
const now = Date.now();
const key = identifier || 'default';

if (!this.requests.has(key)) {
return this.maxRequests;
}

const timestamps = this.requests.get(key);
const validRequests = timestamps.filter(ts => ts > now - this.windowMs);

return Math.max(0, this.maxRequests - validRequests.length);
}
}

总结

  • Skills 2.0显著提升了AI函数调用的智能化水平
  • 智能工具选择机制提高了调用准确性
  • 参数验证确保了数据质量和安全性
  • 错误处理和重试机制增强了系统稳定性
  • 缓存和限流优化了性能表现
  • 电商和金融场景展示了实际应用价值
  • 性能优化技术提升了响应速度

Skills 2.0就像给AI配备了一套精密的”瑞士军刀”,让它能够准确、高效、安全地使用各种外部工具。这种能力的提升不仅体现在技术层面,更重要的是它让AI能够真正融入我们的日常工作流中,成为真正的智能助手。

未来发展

  1. 工具生态系统: 更丰富的预建工具库
  2. AI模型集成: 更深的模型层面集成
  3. 实时协作: 多AI协同工作
  4. 安全保障: 更强的安全和隐私保护
  5. 标准化: 行业标准的制定和完善

扩展阅读

  1. OpenAI Functions Documentation
  2. Skills 2.0 Best Practices
  3. AI Tool Integration Patterns
bulb