客户端工具
客户端工具是在浏览器中运行的工具。使用它们与编辑器的内容进行交互。例如:
- 计算文档中的单词数
- 替换文档中某个单词的所有实例
- 格式化文档。
所有 内置工具 都是客户端工具。
本指南展示了如何实现一个工具,将文档中所有出现的某个单词替换为另一个单词。它假设您已经 设置了带有自定义后端的 AI 代理扩展。
Code demo available
本指南包括一个代码演示,以帮助您入门。请参阅 GitHub 仓库。
客户端设置
为您的工具声明一个工具调用处理程序。工具处理程序是应用工具调用的函数。它们必须实现 AiAgentToolHandler 接口。
import { z } from 'zod'
import type { AiAgentToolHandler } from '@tiptap-pro/extension-ai-agent'
import { ToolCallError, invalidArgumentsResponseFormatter } from '@tiptap-pro/extension-ai-agent'
// 验证工具参数的 schema
const replaceAllToolSchema = z.object({
find: z.string().min(1, '查找文本不能为空'),
replace: z.string(),
})
export const replaceAllToolHandler = (): AiAgentToolHandler => ({
// 工具的唯一标识符
name: 'replace_all',
modifiesEditor: true,
handleToolCall: ({ editor, state, toolCall }) => {
// 验证参数
const result = replaceAllToolSchema.safeParse(toolCall.arguments)
if (!result.success) {
// 返回错误信息给 AI
throw new ToolCallError(invalidArgumentsResponseFormatter(result.error))
}
const args = result.data
try {
// 获取当前 HTML 内容
const html = editor.getHTML()
// 将所有查找文本替换为替换文本
const replacedHtml = html.replaceAll(args.find, args.replace)
// 设置编辑器新内容
editor.commands.setContent(replacedHtml)
// 返回成功消息
return `成功将所有 "${args.find}" 替换为 "${args.replace}"。`
} catch (error) {
console.error(error)
throw new ToolCallError(`替换文本失败:${error.message}`)
}
},
})然后,将该工具添加到你的 AI 代理提供者:
import { AiAgentProvider, toolHandlersStarterKit } from '@tiptap-pro/extension-ai-agent'
const provider = new AiAgentProvider({
toolHandlers: [...toolHandlersStarterKit(), replaceAllToolHandler()],
})toolHandlersStarterKit 包含所有内置工具的工具处理器。你可以将自定义工具处理器添加到该数组中。
服务器端设置
在服务器端定义工具。工具定义包含工具的名称、描述和JSON schema。这些数据会发送给大语言模型(LLM),用于生成工具调用。它必须实现 AiAgentTool 接口。
import type { AiAgentTool } from '@tiptap-pro/extension-ai-agent-server'
export const replaceAllTool = (): AiAgentTool => ({
// 工具的唯一标识符,必须与工具处理器中一致
name: 'replace_all',
description: '将文档中所有出现的某个单词替换为另一个单词',
parameters: {
type: 'object',
properties: {
find: {
type: 'string',
},
replace: {
type: 'string',
},
},
required: ['find', 'replace'],
},
})然后,将该工具添加到你的 AI 代理工具包:
import { AiAgentToolkit, toolsStarterKit } from '@tiptap-pro/extension-ai-agent-server'
const toolkit = new AiAgentToolkit({
tools: [...toolsStarterKit(), replaceAllTool()],
})toolsStarterKit 包含所有内置工具的工具定义。你可以将自定义工具定义添加到该数组中。