【正文】 随着大型语言模型(LLM)的普及,AI智能体(Agent)成为将模型能力与外部工具、数据源结合的关键范式。Google近期推出的TypeScript Agent Development Kit(ADK)为开发者提供了一套轻量、可组合的框架,用于在TypeScript生态中快速构建、调试和部署AI智能体。本文将带你了解ADK的核心概念,并演示如何用不到50行代码创建一个能调用计算器工具的多步推理智能体。
ADK是一个基于TypeScript的库,围绕“智能体=模型+工具+指令”的核心理念设计。它封装了LLM对话管理、工具注册与执行、状态跟踪等常见模式,让开发者专注于业务逻辑。与LangChain等重型框架不同,ADK强调极简API和类型安全——所有工具函数都通过TypeScript类型自动推导,减少运行时错误。
首先,在项目中安装ADK及其依赖模型SDK(例如Google Generative AI):
bash
npm install @google/adk @google/generative-ai dotenv
在环境变量中设置API密钥(以Gemini为例):
GEMINI_API_KEY=your_key_here
ADK的核心概念是`Agent`类。以下代码创建一个简单的天气查询智能体(假设已有天气API工具):
typescript
import { Agent, Tool } from '@google/adk';
import { GoogleGenerativeAI } from '@google/generative-ai';
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY); const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' });
// 定义一个工具函数(使用ADK的Tool装饰器) const getWeather = Tool.create({ name: 'get_weather', description: '获取指定城市的当前天气', parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'], }, execute: async ({ city }: { city: string }) => { // 这里替换为真实的API调用 return `天气晴朗,气温28°C,城市:${city}`; }, });
const agent = new Agent({ name: 'weather-assistant', model, tools: [getWeather], instructions: '你是一个天气助手。当用户询问天气时,使用get_weather工具查询。', });
// 运行智能体 const response = await agent.run('北京今天天气怎么样?'); console.log(response); // 输出:天气晴朗,气温28°C,城市:北京 ```
ADK自动处理多轮工具调用。例如,用户连续问“上海呢?”——智能体会记住上下文,再次调用工具。你还可以通过`memory`参数集成外部存储(如Redis)实现长期记忆:
typescript
import { InMemoryMemory } from '@google/adk';
const agentWithMemory = new Agent({ ...config, memory: new InMemoryMemory(), maxToolCalls: 5, // 限制单次交互工具调用上限 }); ```
ADK内置日志中间件,可输出每个步骤的思考链:
typescript
agent.on('step', (event) => {
console.log(`[步骤] ${event.type}: ${event.content}`);
});
TypeScript ADK凭借简洁的API和强大的类型系统,降低了AI智能体的开发门槛。特别适合Node.js全栈开发者快速原型验证。目前ADK已支持Gemini、Claude等主流模型,并计划集成OpenAI。如果你正在构建客服机器人、自动化工作流或复杂决策系统,不妨尝试这个轻量级工具包。
——
出处:Building AI Agents with the TypeScript Agent Development Kit (ADK)
——
一个热爱技术的程序员,喜欢分享前沿AI知识和开发经验。