当前位置:首页>java>80行代码手写AI Agent,支持记忆和工具调用

80行代码手写AI Agent,支持记忆和工具调用

  • 2026-10-14 15:34:01
80行代码手写AI Agent,支持记忆和工具调用

拒绝空谈,只讲落地的AI实战技巧。今天带你用LangChain TS手写一个具备记忆、工具调用能力的AI Agent。

一、为什么企业需要自建Agent?

现在Claude Code、ChatGPT等AI助手已经很强大了,为什么企业还需要自己开发Agent?

核心原因:企业私有知识库的定制化需求。

通用AI工具面对的是大众场景,但企业内部需要:

  • 接入公司产品的知识库(做客服AI)
  • 定制化的工作流程(自动化审批、数据分析)
  • 符合企业规范的数据安全(私有化部署)

举个例子:你要做一个公司产品的智能客服,需要把产品的所有文档、FAQ、历史工单都喂给大模型,这时就需要**RAG(检索增强生成)**技术。

LangChain就是解决这些问题的神器——它之于AI应用,就像Spring之于Java,已是AI Agent开发的事实标准。


二、先看效果:80行代码实现什么功能?

用80行代码,我们实现了一个具备以下能力的AI Agent:

✅ 长期记忆:多轮对话记住上下文(像Claude Code一样)✅ 工具调用:能自动决策何时调用指定的工具✅ JSON输出:结构化数据返回,便于程序处理✅ 自定义模型:支持OpenAI、通义千问、智谱等任何兼容OpenAI协议的模型


三、完整代码实现(可直接复制使用)

import { createAgent, tool, type ToolRuntime } from"langchain";import { ChatOpenAI } from'@langchain/openai'import { MemorySaver } from"@langchain/langgraph";import * as z from"zod";// 系统提示词const systemPrompt = `You are an expert weather forecaster, who speaks in puns.You have access to two tools:- get_weather_for_location: use this to get the weather for a specific location- get_user_location: use this to get the user's locationIf a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location.`;// 定义工具1:查询天气const getWeather = tool(    ({ city }) =>`It's always sunny in ${city}!`,  {    name: "get_weather_for_location",    description: "Get the weather for a given city",    schema: z.object({    city: z.string(),    }),  });// 定义工具2:获取用户位置(可接入数据库)type AgentRuntime = ToolRuntime<unknown, { user_id: string }>;const getUserLocation = tool(    (_, config: AgentRuntime) => {    const { user_id } = config.context;    // 实际项目中这里可以查询数据库    return user_id === "1" ? "长沙" : "北京";  },  {    name: "get_user_location",    description: "Retrieve user information based on user ID",    schema: z.object({}),  });// 配置模型(支持任何OpenAI兼容的API)const model = await new ChatOpenAI({    modelName: "glm-4.7-flash",  // 可换成 gpt-4、qwen-plus 等    maxRetries: 0,    timeout: 60000,    configuration: {        baseURL: "https://open.bigmodel.cn/api/paas/v4/"// 自定义API地址  },    apiKey: "your-api-key",    temperature: 0});// 定义返回数据的JSON结构const responseFormat = z.object({    punny_response: z.string(),    weather_conditions: z.string().optional(),});// 初始化记忆组件(多轮对话的关键)const checkpointer = new MemorySaver();// 组装Agentconst agent = createAgent({  model,  systemPrompt,  responseFormat,  checkpointer,  tools: [getUserLocation, getWeather],});// 配置:thread_id用于记忆管理,context用于传递业务参数const config = {    configurable: { thread_id: "1" },    context: { user_id: "1" },};// 第一轮对话console.log('第一轮对话...')const response = await agent.invoke(  { messages: [{ role: "user", content: "what is the weather outside?" }] },  config);console.log(response.structuredResponse);// 第二轮对话(Agent记得上下文)const thankYouResponse = await agent.invoke(  { messages: [{ role: "user", content: "thank you!" }] },  config);console.log(thankYouResponse.structuredResponse);

四、如何运行这个Demo?

前置要求:Node.js v20+

# 1. 安装依赖npm install -g pnpmpnpm install# 2. 运行代码tsx src/quickstart.ts

五、获取完整项目

关注公众号**「静远AI实战」,后台回复「Agent」**领取:

  • 完整Demo代码

实战小贴士:开发Agent时,先用简单的Prompt测试流程,再逐步接入工具和数据库。从"能用"到"好用",中间需要大量的Prompt调优。


.cls-1{fill:#001e36;}.cls-2{fill:#31a8ff;}
.cls-1{fill:#001e36;}.cls-2{fill:#31a8ff;}
.cls-1{fill:#001e36;}.cls-2{fill:#31a8ff;}
.cls-1{fill:#001e36;}.cls-2{fill:#31a8ff;}
.cls-1{fill:#001e36;}.cls-2{fill:#31a8ff;}
.cls-1{fill:#001e36;}.cls-2{fill:#31a8ff;}

最新文章

随机文章