概述

工具(Tool)让模型能够与外部世界交互——查询数据库、调用 API、执行计算,从而突破训练数据的局限。

工具是 deepseek-kit 中连接模型与外部世界的桥梁。模型本身只能基于训练数据生成文本,但通过工具,它可以查询实时天气、检索数据库、执行代码——任何你能用 JavaScript 实现的操作,都可以封装为工具交给模型使用。当模型判断需要调用工具时,它会生成工具调用请求;你的代码执行工具并返回结果,模型再基于结果继续推理。

定义工具

使用 tool() 函数定义工具。每个工具由四个核心部分组成:名称描述参数 Schema执行函数

import { tool } from 'deepseek-kit'
import { z } from 'zod'

const weatherTool = tool({
  name: 'getWeather',
  description: '查询指定城市的天气信息',
  schema: z.object({
    city: z.string().describe('城市名称'),
  }),
  execute: async (input) => {
    return `${input.city} 今日天气晴,温度22摄氏度,湿度60%。`
  },
})
  • name — 工具的唯一标识符,模型通过名称来选择调用哪个工具
  • description — 工具的功能描述,帮助模型理解何时应该调用此工具
  • schema — 使用 Zod 定义的参数 Schema,既用于向模型描述参数结构,也用于验证模型生成的参数
  • execute — 异步执行函数,接收经过 Schema 验证的参数,返回工具执行结果

在智能体中使用工具

将工具传递给 createAgent,智能体会根据用户输入自主决定何时调用工具:

import { createAgent, createModel, tool } from 'deepseek-kit'
import { z } from 'zod'

const model = createModel({ model: 'deepseek-v4-flash' })

const weatherTool = tool({
  name: 'getWeather',
  description: '查询指定城市的天气信息',
  schema: z.object({
    city: z.string().describe('城市名称'),
  }),
  execute: async (input) => {
    return `${input.city} 今日天气晴,温度22摄氏度,湿度60%。`
  },
})

const agent = createAgent({
  model,
  tools: [weatherTool],
})

const result = await agent.generate({
  prompt: '北京今天天气怎么样?',
})

console.log(result.text)

你也可以直接在 generateText 中使用工具:

import { createModel, generateText, tool } from 'deepseek-kit'
import { z } from 'zod'

const model = createModel({ model: 'deepseek-v4-flash' })

const result = await generateText({
  model,
  tools: [weatherTool],
  messages: [{ role: 'user', content: '北京今天天气怎么样?' }],
})