跳到主要内容

DeepSeek高级功能与工具调用

探索DeepSeek的高级功能,包括工具调用、多模态交互和函数调用能力,提升AI应用的实用性和扩展性。

🔧 工具调用能力

DeepSeek支持通过API调用外部工具,实现与外部系统的交互。这使得AI能够获取实时信息、执行计算和操作外部资源。

工具定义与注册

首先,需要定义和注册工具:

const { DeepSeekClient } = require('deepseek-sdk');

const client = new DeepSeekClient({
apiKey: '您的DeepSeek API密钥',
model: 'deepseek-chat',
});

// 定义工具
const tools = [
{
name: 'get_weather',
description: '获取指定城市的天气信息',
parameters: {
type: 'object',
properties: {
city: {
type: 'string',
description: '城市名称,如北京、上海'
},
date: {
type: 'string',
description: '日期,格式YYYY-MM-DD,可选,默认为今天'
}
},
required: ['city']
}
},
{
name: 'calculate',
description: '进行数学计算',
parameters: {
type: 'object',
properties: {
expression: {
type: 'string',
description: '数学表达式,如2+2*3/2'
}
},
required: ['expression']
}
}
];

// 注册工具
client.registerTools(tools);

调用工具

使用注册的工具:

// 调用工具函数
async function callTool() {
try {
const result = await client.generate({
prompt: '北京明天的天气怎么样?',
tools: true, // 启用工具调用
maxTokens: 1000
});

if (result.toolCalls) {
// 处理工具调用请求
console.log('工具调用请求:', result.toolCalls);
// 模拟执行工具并获取结果
const toolResults = await executeTools(result.toolCalls);
// 将工具结果发送给模型
const finalResult = await client.generate({
prompt: '北京明天的天气怎么样?',
toolResults,
maxTokens: 1000
});
console.log('最终结果:', finalResult.text);
} else {
console.log('直接回复:', result.text);
}
} catch (error) {
console.error('调用工具失败:', error);
}
}

// 模拟执行工具
async function executeTools(toolCalls) {
const results = [];
for (const call of toolCalls) {
if (call.name === 'get_weather') {
// 模拟调用天气API
const weatherData = {
city: call.parameters.city,
date: call.parameters.date || new Date().toISOString().split('T')[0],
temperature: '25°C',
condition: '晴朗',
wind: '微风'
};
results.push({
id: call.id,
name: call.name,
result: weatherData
});
} else if (call.name === 'calculate') {
// 执行计算
try {
// 注意:实际应用中应使用更安全的计算方式
const result = eval(call.parameters.expression);
results.push({
id: call.id,
name: call.name,
result: { value: result }
});
} catch (e) {
results.push({
id: call.id,
name: call.name,
error: e.message
});
}
}
}
return results;
}

callTool();

🖼️ 多模态交互

DeepSeek支持多模态交互,能够处理文本、图像等多种输入形式。

图像理解

const { DeepSeekClient } = require('deepseek-sdk');
const fs = require('fs');
const path = require('path');

const client = new DeepSeekClient({
apiKey: '您的DeepSeek API密钥',
model: 'deepseek-multimodal', // 使用多模态模型
});

// 图像理解函数
async function understandImage(imagePath) {
try {
// 读取图像文件
const imageData = fs.readFileSync(imagePath);
const base64Image = imageData.toString('base64');

const result = await client.generate({
prompt: '描述这张图片的内容。',
images: [{
type: 'image/jpeg',
data: base64Image
}],
maxTokens: 500
});

console.log('图像描述:', result.text);
return result.text;
} catch (error) {
console.error('图像理解失败:', error);
throw error;
}
}

// 使用示例
understandImage('./sample.jpg');

图文混合生成

// 图文混合生成
async function generateWithImage(prompt, imagePath) {
try {
const imageData = fs.readFileSync(imagePath);
const base64Image = imageData.toString('base64');

const result = await client.generate({
prompt: `${prompt}\n根据图片内容补充细节。`,
images: [{
type: 'image/jpeg',
data: base64Image
}],
maxTokens: 1000
});

console.log('生成结果:', result.text);
return result.text;
} catch (error) {
console.error('图文生成失败:', error);
throw error;
}
}

generateWithImage('写一段关于这幅画的故事。', './painting.jpg');

📊 函数调用与复杂任务处理

DeepSeek支持函数调用,可以将复杂任务分解为多个函数调用步骤。

函数定义与调用

// 定义复杂函数
const complexTools = [
{
name: 'fetch_product_data',
description: '获取产品数据',
parameters: {
type: 'object',
properties: {
productId: {
type: 'string',
description: '产品ID'
}
},
required: ['productId']
}
},
{
name: 'analyze_product_sentiment',
description: '分析产品评论情感',
parameters: {
type: 'object',
properties: {
productId: {
type: 'string',
description: '产品ID'
},
reviews: {
type: 'array',
items: {
type: 'string'
},
description: '评论列表'
}
},
required: ['productId', 'reviews']
}
},
{
name: 'generate_report',
description: '生成产品分析报告',
parameters: {
type: 'object',
properties: {
productData: {
type: 'object',
description: '产品数据'
},
sentimentAnalysis: {
type: 'object',
description: '情感分析结果'
}
},
required: ['productData', 'sentimentAnalysis']
}
}
];

// 注册复杂函数
client.registerTools(complexTools);

// 处理复杂任务
async function processComplexTask(productId) {
try {
// 第一步:获取产品数据
let result = await client.generate({
prompt: `分析产品ID为${productId}的产品,生成一份详细报告。`,
tools: true,
maxTokens: 1000
});

// 执行工具调用
let toolResults = [];
if (result.toolCalls) {
toolResults = await executeComplexTools(result.toolCalls);
}

// 第二步:继续生成
result = await client.generate({
prompt: `分析产品ID为${productId}的产品,生成一份详细报告。`,
toolResults,
tools: true,
maxTokens: 1000
});

// 可能需要多次工具调用
if (result.toolCalls) {
toolResults = await executeComplexTools(result.toolCalls);
// 第三步:最终生成
result = await client.generate({
prompt: `分析产品ID为${productId}的产品,生成一份详细报告。`,
toolResults,
maxTokens: 2000
});
}

console.log('最终报告:', result.text);
return result.text;
} catch (error) {
console.error('处理复杂任务失败:', error);
throw error;
}
}

// 模拟执行复杂工具
async function executeComplexTools(toolCalls) {
const results = [];
for (const call of toolCalls) {
if (call.name === 'fetch_product_data') {
// 模拟获取产品数据
const productData = {
id: call.parameters.productId,
name: '智能手表',
price: 1999,
category: '电子产品',
features: ['心率监测', 'GPS定位', '防水']
};
results.push({
id: call.id,
name: call.name,
result: productData
});
} else if (call.name === 'analyze_product_sentiment') {
// 模拟情感分析
const sentimentResult = {
positive: 0.75,
negative: 0.15,
neutral: 0.10,
keyPoints: ['电池续航好', '屏幕清晰', '价格略高']
};
results.push({
id: call.id,
name: call.name,
result: sentimentResult
});
} else if (call.name === 'generate_report') {
// 模拟生成报告
const report = {
product: call.parameters.productData,
sentiment: call.parameters.sentimentAnalysis,
conclusion: '产品整体评价良好,建议优化价格策略。',
recommendations: ['推出优惠套餐', '增加颜色选项', '改进用户手册']
};
results.push({
id: call.id,
name: call.name,
result: report
});
}
}
return results;
}

processComplexTask('P12345');

🔄 流式输出

DeepSeek支持流式输出,可以实时获取生成的内容。

// 流式输出示例
async function streamOutput() {
try {
const stream = await client.generateStream({
prompt: '写一篇关于未来科技的文章,约500字。',
maxTokens: 1000,
temperature: 0.7
});

console.log('开始接收流式输出:');
let fullText = '';

for await (const chunk of stream) {
if (chunk.type === 'content') {
process.stdout.write(chunk.text); // 实时输出到控制台
fullText += chunk.text;
}
}

console.log('\n\n流式输出完成。');
return fullText;
} catch (error) {
console.error('流式输出失败:', error);
throw error;
}
}

streamOutput();

📝 总结

通过本文的学习,您已经掌握了DeepSeek的高级功能,包括:

  • 工具定义、注册和调用
  • 多模态交互(图像理解和图文混合生成)
  • 函数调用与复杂任务处理
  • 流式输出

这些高级功能使得DeepSeek能够与外部系统深度集成,处理复杂任务,提供更丰富的交互体验。在实际应用中,您可以根据需求组合使用这些功能,构建更强大、更智能的AI应用。