---
title: "使用 Langchain 和開源 Llama AI 在 Next.js 打造 AI Bot API Part 2 - 打造 AI 具有記憶功能的 AI Agent"
description: "示範如何用 Langchain AgentExecutor 搭配自訂工具與 SerpAPI，並整合 Redis 賦予 AI Agent 記憶功能，實現具狀態的對話式 Bot。"
canonical_url: "https://blog.markkulab.net/post/ai-bot-api-parts-2"
author: "Mark Ku"
author_url: "https://blog.markkulab.net/author/mark-ku"
site: "Mark Ku's Blog"
date_published: "2024-10-13 01:01:35 +0800"
category: "AI"
tags: ["llama", "ai", "langchain", "redis", "node", "nextjs"]
language: "zh-TW"
license: "CC BY 4.0"
license_url: "https://creativecommons.org/licenses/by/4.0/"
attribution: "轉載或引用請註明作者並附上原文連結"
---

# 使用 Langchain 和開源 Llama AI 在 Next.js 打造 AI Bot API Part 2 -  打造 AI 具有記憶功能的 AI Agent

## 前言
[先前有試著將 Python Langchain 換成 Node 版](https://blog.markkulab.net/ai-bot-api-parts-1/)，但 Langchain node 版的文件真的有點少，因此，轉換起來有點辛苦，因為常常就算有文件，還是漏了參數，程式就炸了，最後還是得對照Python 版本。

## 預先準備
* Redis server
* Ollama
* NextJS 專案

## 代理組件
首先，我們來看代理組件(AgentExecutor)，代理組件在Langchain 框架中蠻核心的組件，代理能根據用戶輸入的內容，由AI 動態決定要使用那個工具，並給出最終的答案。

### 初始化代理組件
```
// 初化模式
const llm = new ChatOllama({
            model: 'llama3.2',
            temperature: 0,
            maxRetries: 2,
            baseUrl: 'http://localhost:11434',
        });

const tools = []; // 工具清單

// 初始化聊天範本
const prompt = ChatPromptTemplate.fromMessages([
            ['system', 'You are a helpful assistant'], // default role
            ['placeholder', '{chat_history}'], // default role
            ['human', '{input}'],
            ['placeholder', '{agent_scratchpad}'],
        ]);

const agent = createToolCallingAgent({
            llm,
            tools,
            prompt,
        });  
        
const result = await agentExecutor.invoke({ input: 'your question ' });        
```

## 工具 ( 動態路由 )
前面提到，當代理組件，接收使用者問題 > 會依據工具的描述，並讓 AI 決定使用那個工具 > 執行工具 > 最終回應結果給用戶。

### 客製化工具
```
import { tool } from '@langchain/core/tools';
...
 const greetingTool = tool(
            async ({ input }: { input: string }) => {
                return input + ' ==';
            },
            {
                name: 'greetingTool',
                description: 'if some one say hello',
                schema: z.object({
                    input: z.string(),
                })                
            }
        );
...        
```
參數說明
* name：工具的名稱。
* description：描述該工具的功能，供 AI 會依據描述，決定使用那個工具。
* func：該工具的核心功能，這裡是異步函數，根據輸入值返回
* schema：使用 zod 定義工具輸入的參數格式。

### 使用第三方工具 - SerpAPI
SerpAPI 是一個專門設計用來與搜尋引擎互動的 API，特別是 Google 搜尋，SerpAPI 自動化了網頁抓取的過程，讓開發者無需自行管理搜尋引擎的網頁解析和資料提取，簡化了搜尋結果的獲取過程。

```
import { SerpAPI } from '@langchain/community/tools/serpapi';

 let serpApiTool = new SerpAPI('your key ', {
           location: 'Austin,Texas,United States', // ，代表你要模擬的搜尋位置。在這裡，它指定了搜索應基於美國德州奧斯汀的位置，這可以影響搜尋結果的區域相關性。
           hl: 'en', //  語言參數，代表要以哪種語言來顯示搜尋結果。'en' 表示結果會以英文顯示。
           gl: 'us', // 國家/地區代碼，用來設定你希望搜尋結果的區域依據。'us' 表示結果會根據美國的地區來產生。
           }),
```

## 擴充 AI Agent 的記憶功能  
大型語言模型，本身是不具備記憶功能，之所謂能讀懂上下文的問題，因為每次將討論的過程，再傳遞給大型語言模型，去詢問。

Langchain 的momory ，也是透過這個機制，因此將每次用戶問的問題存在 Redis ，讓AI Bot 也具備記憶功能。

### 安裝相關的套件 - [參考文件](https://js.langchain.com/docs/integrations/vectorstores/redis/)
```
npm i @langchain/redis @langchain/core redis @langchain/openai --save
```
### 使用 redis memory 

```
import { RedisChatMessageHistory } from '@langchain/community/stores/message/ioredis';
import { BufferMemory } from 'langchain/memory';
...
 const client = new Redis('redis://localhost:30001');

        const memory = new BufferMemory({
            chatHistory: new RedisChatMessageHistory({
                sessionId: 'sessionId:' + new Date().toISOString(),
                sessionTTL: 300,
                client,
            }),
            aiPrefix: 'ollama',
            outputKey: 'output', // 沒有會爆錯
            memoryKey: 'chat_history', // 沒有會爆錯
            inputKey: 'input', // 沒有會爆錯
            returnMessages: true,
            
            
const agentExecutor = new AgentExecutor({
            agent,
            tools,
            verbose: true, // enable debug
            handleParsingErrors: true,
            memory, // redis 記憶功能
            returnIntermediateSteps: true,
        });
...
```

## 完整的程式碼 ( Next.JS API)

```
import { RedisChatMessageHistory } from '@langchain/community/stores/message/ioredis';
import { Calculator } from '@langchain/community/tools/calculator';
import { SerpAPI } from '@langchain/community/tools/serpapi';
import { ChatPromptTemplate } from '@langchain/core/prompts';
import { tool } from '@langchain/core/tools';
import { ChatOllama } from '@langchain/ollama';
import Redis from 'ioredis';
import { AgentExecutor, createToolCallingAgent } from 'langchain/agents';
import { BufferMemory } from 'langchain/memory';
import { NextApiRequest, NextApiResponse } from 'next/types';
import { z } from 'zod';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (req.method !== 'GET') {
        return res.status(405).json({ message: 'Only GET requests are allowed' });
    }

    try {
        const magicTool = tool(
            async ({ input }: { input: number }) => {
                return `${input + 2}`;
            },
            {
                name: 'magic_function',
                description: 'Applies a magic function to an input.',
                schema: z.object({
                    input: z.number(),
                }),
            }
        );

        const llm = new ChatOllama({
            model: 'llama3.2',
            temperature: 0,
            maxRetries: 2,
            baseUrl: 'http://localhost:11434',
            // other params...
        });

        const tools = [
            magicTool, // custom tool
            new Calculator(),
            new SerpAPI('your serp key', {
                location: 'Austin,Texas,United States',
                hl: 'en',
                gl: 'us',
            }),
        ];

        const prompt = ChatPromptTemplate.fromMessages([
            ['system', 'You are a helpful assistant'], // default role
            ['placeholder', '{chat_history}'], // default role
            ['human', '{input}'],
            ['placeholder', '{agent_scratchpad}'],
        ]);

        const agent = createToolCallingAgent({
            llm,
            tools,
            prompt,
        });

        const client = new Redis('redis://localhost:30001');

        const memory = new BufferMemory({
            chatHistory: new RedisChatMessageHistory({
                sessionId: 'sessionId:' + new Date().toISOString(),
                sessionTTL: 300,
                client,
            }),
            aiPrefix: 'ollama',
            outputKey: 'output', // 沒有會爆錯
            memoryKey: 'chat_history', // 沒有會爆錯
            inputKey: 'input', // 沒有會爆錯
            returnMessages: true,
        });

        const agentExecutor = new AgentExecutor({
            agent,
            tools,
            verbose: true, // enable debug
            handleParsingErrors: true,
            memory, // redis 記憶功能
            returnIntermediateSteps: true,
        });

        const result = await agentExecutor.invoke({ input: 'what is the value of magic_function(3)?' });
        const serpResult2 = await agentExecutor.invoke({ input: 'what is the Pokomon?' });
        const result3 = await agentExecutor.invoke({ input: 'what is 5 + 2 *5 =' });
        const result4 = await agentExecutor.invoke({ input: 'hello', outputKey: 'key1' });
        const result5 = await agentExecutor.invoke({ input: '幫我推薦電腦' });

        return res.status(200).json({ result, serpResult2, result3, result4, result5 });
    } catch (error) {
        return res.status(500).json({ message: 'Internal server error' });
    }
}

```

## 參考資料
* [官方文件](https://js.langchain.com/docs/how_to/migrate_agent/#basic-usage)
* [官方程式文件](https://v03.api.js.langchain.com/hierarchy.html#@langchain/community.tools/serpapi.SerpAPI)
* [Building AI Solutions with LangChain and Node.js: A Comprehensive Guide](https://medium.com/widle-studio/building-ai-solutions-with-langchain-and-node-js-a-comprehensive-guide-widle-studio-4812753aedff)

## 此系列相關文章
* [使用 Langchain 和開源 Llama AI 在 Next.js 打造 AI Bot API Part 1 - 從了解 lanchain 開始](https://blog.markkulab.net/ai-bot-api-parts-1/)
* [使用 Langchain 和開源 Llama AI 在 Next.js 打造 AI Bot API Part 2 - 打造 AI 具有記憶功能的 AI Agent](https://blog.markkulab.net/ai-bot-api-parts-2/)
* [使用 Langchain 和開源 Llama AI 在 Next.js 打造 AI Bot API Part 3 - 加入向量資料庫，讓AI擁有額外的腦袋](https://blog.markkulab.net/ai-bot-api-parts-3/)
* [使用 Langchain 和開源 Llama AI 在 Next.js 打造 AI Bot API Part 4 - AI產品推薦 API](https://blog.markkulab.net/ai-bot-api-parts-4/)

---

## 關於本文與作者

本文出自 [Mark Ku's Blog](https://blog.markkulab.net/post/ai-bot-api-parts-2)

授權條款： [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) — 轉載或引用請註明作者並附上原文連結

### 關於作者

**[Mark Ku](https://blog.markkulab.net/author/mark-ku)** — Software Solution Provider

- 10+ 年資深軟體工程師，現為 AI 應用 Builder
- 專注大型平台架構設計，從北美電商到AI SaaS訂閱收費系統
- 結合 AI Agent 與自動化，打造高效可演進的產品技術基礎

### 作者開發的免費工具

以下工具皆可免費使用：

- [免費 PDF 簽名工具](https://blog.markkulab.net/tools/pdf-sign): 線上 PDF 簽名工具，瀏覽器內完成手繪、打字、上傳簽名，可拖曳放置、縮放、下載。所有處理都在你的裝置完成，檔案不會上傳。
- [VS Code Refactory](https://blog.markkulab.net/tools/refactory): Refactory 是一款 VS Code 重構擴充套件：34 個重構動作、37 條 code smell 檢查、Code Health 儀表板、18 種語言、534 支測試。懂你的專案慣例：介面放哪、DI 註冊寫在哪、'use client' 該不該加；還會用 git 修改頻率 × 複雜度排出「該先修哪個檔案」，並一鍵把壞味道交給你自己電腦上的 Claude Code 修。免費使用，原始碼不離開你的機器。
- [DB-Kit 資料庫管理工具](https://blog.markkulab.net/tools/db-kit): DB-Kit 是一個用 Tauri + Rust + React 打造的輕量跨平台資料庫管理工具，用單一一致的介面同時管理 MySQL、MariaDB、PostgreSQL、SQL Server、Oracle、SQLite、MongoDB、Redis、Kafka、Elasticsearch 與 RabbitMQ 十一種資料來源：連線密碼以 OS keychain 加密、SSH Tunnel、完整 CRUD、視覺化查詢建構器、多結果集同時顯示、跨連線資料傳輸與比對同步、Excel / CSV 匯入匯出、執行計畫視覺化、ER 圖、排程備份、SQL 壓力測試（p50～p99 延遲百分位）、15 條規則的 SQL 審查、Kafka 訊息瀏覽與監控告警；繁中 / 英文雙語介面，內建 AI 助手（自然語言生成 SQL、AI 審查與調校建議）與命令列工具 dbk。免費開源（MIT），提供 Windows / macOS / Linux 安裝檔。
- [VS Code Super Mermaid](https://blog.markkulab.net/tools/super-mermaid): Super Mermaid 是一款 VS Code 擴充套件：開箱即用的漂亮 Mermaid 圖表，自動上色、即時預覽、滑鼠平移縮放、PNG / SVG 高解析匯出，內建 21 種範本與多種主題。免費開源（MIT）。
- [React Super Mermaid](https://blog.markkulab.net/tools/react-super-mermaid): react-super-mermaid 是一個開源 React 元件庫：一行 <MermaidViewer> 即可渲染漂亮的 Mermaid 圖表，內建 colorful / sketch 主題、平移縮放、圖內搜尋、SVG / PNG 高解析匯出。輕量、SSR 安全、完整 TypeScript 型別。免費開源（MIT）。
- [Jira / Confluence Super Mermaid](https://blog.markkulab.net/tools/jira-super-mermaid): Atlassian Forge app：在 Jira issue 與 Confluence 內文直接寫 Mermaid 語法，畫流程圖、時序圖、狀態機與甘特圖。11 種圖表、SVG / PNG 匯出、明暗主題、完整中日韓文字支援。取得 Runs on Atlassian 資格：圖表存在你自己的站台，app 不呼叫任何第三方服務。免費，即將上架 Atlassian Marketplace。
- [Mermaid 線上預覽](https://blog.markkulab.net/tools/mermaid-preview): 在瀏覽器裡寫 Mermaid、即時看圖，整張圖表壓進網址就能分享。免註冊、不上傳伺服器，相容 mermaid.live 的分享連結。
- [React Intl Phone Number](https://blog.markkulab.net/tools/react-intl-phone-number): react-intl-phone-number 是一個開源 React 元件：framework-agnostic、不依賴 antd，提供 E.164 進出、可搜尋國旗 / 國碼下拉、可配置驗證等級（strict / mobile-strict / loose）、可主題化 CSS 與 i18n，電話邏輯由 google-libphonenumber 驅動。輕量、完整 TypeScript 型別。免費開源（MIT）。
- [Uptime Kuma Cluster](https://blog.markkulab.net/tools/uptime-kuma-cluster): 把單機版 Uptime Kuma 改造成高可用叢集：OpenResty + Lua 智慧負載平衡、MariaDB 共享狀態、健康檢查與自動 Failover，附叢集管理 REST API，一行 Docker Compose 啟動。免費開源（MIT）。
- [特教專案](https://blog.markkulab.net/education): 為特殊教育學生製作的學習教材

### 每日 Podcast

- [科技新鮮事](https://blog.markkulab.net/category/tech-news): 每日精選 AI 與科技趨勢，透過語音摘要快速掌握最新技術動態，涵蓋 AI 應用、軟體架構、DevOps 與工程實戰。 — RSS: https://blog.markkulab.net/feed.xml
- [AI股市蝦聊](https://blog.markkulab.net/category/ai-stock-chat): 每個交易日用 AI 分析台股盤勢，以雙人對話聊當天的盤中觀察與隔日預測。 — RSS: https://blog.markkulab.net/ai-stock-chat/feed.xml

### 電子報

[訂閱電子報](https://blog.markkulab.net/subscribe) — 第一時間收到新文章通知，無垃圾信、隨時可取消訂閱。
