乐闻世界logo
搜索文章和话题
如何基于 LangChain 实现 AI Agent

如何基于 LangChain 实现 AI Agent

乐闻的头像
乐闻

2026年01月16日 11:59· 阅读 31

一、前言

在现代 AI 应用开发中,Agent 能够自主决策和执行任务,极大地提升了自动化能力。LangChain JS 是一个专注于 JavaScript/TypeScript 环境下的强大 AI 编排框架,支持多种 LLM(大语言模型)集成。Ollama 则是一个本地化的 LLM 运行平台,支持如 Llama2、Mistral 等主流模型。本文将介绍如何基于 LangChain JS 实现 Agent,并使用 Ollama 提供的模型,实现智能任务处理。


二、背景知识

要顺利学习本教程,建议具备以下知识:

前置知识简要说明
JavaScript/TypeScript熟悉基本语法和 Node.js 环境
LLM 基础理解大语言模型的基本原理和应用场景
API 调用能够进行 HTTP 请求和处理响应
LangChain 基础了解 LangChain 的核心概念,如链(Chain)、工具(Tool)等
Ollama 基础了解 Ollama 的安装、模型管理及 API 调用方式

三、核心内容讲解

1. LangChain JS Agent 概念
  • Agent:一种能根据输入,自主决定调用哪些工具或链,最终完成任务的智能体。
  • 工具(Tool):Agent 可调用的外部功能,如 Web 搜索、数据库查询等。
  • LLM(语言模型):Agent 的“思考核心”,用来理解任务、生成决策。
2. Ollama 模型集成原理
  • Ollama 提供本地 RESTful API,支持多种 LLM。
  • LangChain JS 可通过自定义 LLM Provider 集成 Ollama。
3. 流程图
mermaid
graph TD A[用户输入] --> B[Agent] B --> C[LLM (Ollama)] B --> D[工具/链] C --> B D --> B B --> E[输出结果]

四、实操步骤/案例

步骤 1:环境准备
  1. 安装 Node.js(建议 v18+)
  2. 安装 Ollama 并拉取模型(如 llama2)
bash
# 安装 Ollama brew install ollama # 启动 Ollama 服务 ollama serve # 拉取模型 ollama pull llama2
  1. 初始化项目
bash
mkdir langchain-ollama-agent cd langchain-ollama-agent npm init -y npm install langchain @langchain/community axios
步骤 2:创建 Ollama LLM Provider
js
// ollama-llm.js import { BaseLLM } from "langchain/llms/base"; import axios from "axios"; export class OllamaLLM extends BaseLLM { constructor(model = "llama2") { super(); this.model = model; } async _call(prompt, options) { const response = await axios.post( "http://localhost:11434/api/generate", { model: this.model, prompt: prompt, } ); return response.data.response; } }
步骤 3:定义 Agent 与工具
js
// agent-demo.js import { OllamaLLM } from "./ollama-llm"; import { initializeAgentExecutorWithOptions } from "@langchain/community/agents"; import { Tool } from "@langchain/community/tools"; // 示例工具:简单计算器 const calculator = new Tool({ name: "calculator", description: "执行简单数学计算", func: async (input) => { try { return eval(input).toString(); } catch { return "输入错误"; } }, }); const llm = new OllamaLLM("llama2"); async function main() { const agent = await initializeAgentExecutorWithOptions( [calculator], // 工具列表 llm, { agentType: "zero-shot-react-description", verbose: true, } ); const result = await agent.call({ input: "请计算 12 * 8,并用中文回答我。", }); console.log(result.output); } main();
步骤 4:运行与测试
bash
node agent-demo.js

输出示例:

shell
12 * 8 = 96

五、常见问题与解决方案

问题解决思路
Ollama 服务未启动确认 ollama serve 已运行,端口为 11434
模型未下载或名称错误使用 ollama list 检查模型,确保名称正确
Agent 无法调用工具检查工具注册与描述,确保 Agent 能识别工具
网络请求失败检查本地防火墙、端口占用或 axios 配置
中文输出不理想尝试在 prompt 中明确要求中文回答

六、结论与拓展阅读

本文介绍了如何基于 LangChain JS 构建 Agent,并集成 Ollama 本地模型,实现智能任务处理。通过自定义 LLM Provider 和工具扩展,可以灵活构建多样化的 AI 应用。

推荐拓展资料:

标签: