发布于 2026-01-06 0 阅读
0

使用 MongoDB Chatbot Framework 构建可用于生产环境的智能聊天机器人

使用 MongoDB Chatbot Framework 构建可用于生产环境的智能聊天机器人

在过去的几个月里,由 ChatGPT 等大型语言模型 (LLM) 驱动的聊天机器人已成为科技界关注的焦点。

有很多工具和模板可以帮助你快速上手这项令人兴奋的新技术。构建原型既快捷又简单,甚至充满乐趣。事实上,MongoDB 已经提供了一个教程,教你如何使用 Atlas Vector Search 和 LangChain 基于你的数据构建聊天机器人

然而,将聊天机器人原型投入生产环境并非易事。除了如何持久化数据和保障应用安全等标准应用开发问题外,现在还出现了一系列与生成式人工智能相关的新问题,例如提示工程、检索增强生成(RAG)以及回复的定性评估。

为了帮助您将智能聊天机器人从原型转化为生产版本,我们创建了MongoDB 聊天机器人框架

什么是 MongoDB Chatbot Framework?

MongoDB Chatbot Framework 是一套库,可用于使用 TypeScript、Express.js 和 React 构建生产就绪的全栈聊天机器人应用程序。该框架为使用Atlas Vector Search 的检索增强生成提供了一流的支持。它还包含用于使用 OpenAI ChatGPT 和 Embeddings API 的模块。此外,它还集成了 LangChain,因此您可以轻松引入其他模型提供商,例如 Amazon Bedrock 或 Google Vertex AI。该框架具有可扩展性,因此您也可以引入自己的 AI 模型。

MongoDB Chatbot Framework 完全使用 TypeScript 构建,这使其与 LLM 应用开发生态系统中的许多 Python 库区别开来。使用 TypeScript 为该框架带来了诸多优势:

  • 你可以使用单一语言开发整个应用程序栈。
  • TypeScript 强大的类型系统为框架提供了可扩展的接口,您可以利用这些接口安全地实现自定义应用程序逻辑并及早发现错误。
  • TypeScript 与 JavaScript 生态系统的兼容性使其能够与各种现有库和工具无缝集成。
  • 服务器端逻辑编译为 Node.js,Node.js 性能优异,并且经过实战检验,适用于异步数据处理。

请继续阅读,了解更多关于 MongoDB Chatbot Framework 的信息以及您应该使用它的原因。您也可以阅读其文档来进一步了解该框架。

为什么要使用 MongoDB 聊天机器人框架?

MongoDB聊天机器人框架可助您高效地从原型过渡到生产环境。该框架提供各种接口,您可以使用这些接口,结合最新、最有效的聊天机器人开发技术,构建智能聊天机器人。

我们借鉴了自身构建MongoDB 文档聊天机器人的经验,构建了这个框架。MongoDB 文档聊天机器人允许用户与 MongoDB 文档进行对话。我们将随着 MongoDB 文档聊天机器人功能的不断完善,持续为 MongoDB 聊天机器人框架添加新功能。

MongoDB聊天机器人框架负责处理诸如以下通用应用程序样板代码:

  • 在 MongoDB Atlas 中持久化对话。
  • 错误和特殊情况处理。
  • 实时响应。
  • 提供可扩展的接口,用于定制和保护应用程序逻辑。

简化应用程序样板后,您可以专注于为用户构建最佳的生成式 AI 体验。

根据我们构建 Docs 聊天机器人的经验,智能聊天机器人开发过程中最困难的环节之一就是确定开发重点。鉴于生成式人工智能领域的新兴性和快速发展,仅仅跟上最新技术就已经让人感觉像是一份全职工作,更不用说将它们应用到聊天机器人中了。

通过使用 MongoDB Chatbot Framework,您可以将智能聊天机器人的开发工作交给我们全职负责,这样您就不必为此操心了。

该框架包含构建智能聊天机器人最重要方面的模块和接口,包括:

  • 迅速的工程设计。
  • 使用 RAG 方法使聊天机器人的答案与外部知识相匹配。
  • 上下文窗口管理。
  • 高效地摄取数据以供 RAG 使用。

请参阅文档,了解有关 MongoDB Chatbot Framework 的更多信息

框架核心模块

MongoDB聊天机器人框架包含以下核心模块:

  • 聊天机器人服务器:一个基于 TypeScript/Express.js 的服务器,用于处理和保存用户与 LLM 之间的对话。
  • 聊天机器人用户界面:可用于构建与聊天机器人服务器通信的聊天机器人前端的 React 组件
  • Ingest CLI:一个命令行应用程序,可用于从数据源提取数据以供 RAG 使用。

在本节的剩余部分,我们将了解 MongoDB Chatbot Framework 的各个组件,并探讨如何使用它们来构建智能聊天机器人。

聊天机器人服务器

聊天机器人服务器是一组 TypeScript 和 Express.js 模块。它负责协调用户、类似 GPT-3.5 的语言模型以及 MongoDB Atlas 中的数据持久化之间的通信。

聊天机器人服务器自带对 OpenAI 低层模型 (LLM) 的支持,并且其接口也可扩展以支持其他低层模型。您可以使用 GPT-3.5 或 GPT-4 等 OpenAI 模型快速启动并运行服务器,然后在开发应用程序的过程中替换模型。

对话数据存储在 MongoDB Atlas 中。Atlas 开发者数据平台具备强大的安全性、可扩展性和数据管理功能。例如,您可以使用聚合框架执行分析查询,或使用Atlas Charts可视化对话数据

聊天机器人服务器利用 Atlas Vector Search 为 RAG 提供一流的支持。这使得聊天机器人能够从外部数据源提取相关信息,从而利用准确且最新的知识丰富其回复。内置的 RAG 模块是可插拔的,因此您可以添加自定义检索逻辑。您可以在与对话数据位于同一 MongoDB 数据库中的集合上使用 Atlas Vector Search,从而在一个统一的平台上管理所有应用程序数据。

该服务器还提供了集成自定义应用程序逻辑的灵活性,包括特定的 LLM 提示、RAG 配置、身份验证机制和部署策略。文档中的代码示例演示了如何无缝集成这些元素。

以下是使用 Atlas 向量搜索执行 RAG 算法的聊天机器人服务器示例实现的代码:



import {
  MongoClient,
  makeMongoDbEmbeddedContentStore,
  makeOpenAiEmbedder,
  makeMongoDbConversationsService,
  AppConfig,
  makeOpenAiChatLlm,
  OpenAiChatMessage,
  SystemPrompt,
  makeDefaultFindContent,
  logger,
  makeApp,
  GenerateUserPromptFunc,
  makeRagGenerateUserPrompt,
  MakeUserMessageFunc,
} from "mongodb-chatbot-server";
import { OpenAIClient, OpenAIKeyCredential } from "@azure/openai";
import path from "path";

const {
  MONGODB_CONNECTION_URI,
  MONGODB_DATABASE_NAME,
  VECTOR_SEARCH_INDEX_NAME,
  OPENAI_API_KEY,
  OPENAI_EMBEDDING_MODEL,
  OPENAI_CHAT_COMPLETION_MODEL,
} = process.env;

// Create the OpenAI client
// for interacting with the OpenAI API (ChatGPT API and Embedding API)
const openAiClient = new OpenAIClient(new OpenAIKeyCredential(OPENAI_API_KEY));

// Chatbot LLM for responding to the user's query.
const llm = makeOpenAiChatLlm({
  openAiClient,
  deployment: OPENAI_CHAT_COMPLETION_MODEL,
  openAiLmmConfigOptions: {
    temperature: 0,
    maxTokens: 500,
  },
});

// MongoDB data source for the content used in RAG.
// Generated with the Ingest CLI.
const embeddedContentStore = makeMongoDbEmbeddedContentStore({
  connectionUri: MONGODB_CONNECTION_URI,
  databaseName: MONGODB_DATABASE_NAME,
});

// Creates vector embeddings for user queries to find matching content
// in the embeddedContentStore using Atlas Vector Search.
const embedder = makeOpenAiEmbedder({
  openAiClient,
  deployment: OPENAI_EMBEDDING_MODEL,
  backoffOptions: {
    numOfAttempts: 3,
    maxDelay: 5000,
  },
});

// Find content in the embeddedContentStore using the vector embeddings
// generated by the embedder.
const findContent = makeDefaultFindContent({
  embedder,
  store: embeddedContentStore,
  findNearestNeighborsOptions: {
    k: 5,
    path: "embedding",
    indexName: VECTOR_SEARCH_INDEX_NAME,
    minScore: 0.9,
  },
});

// Constructs the user message sent to the LLM from the initial user message
// and the content found by the findContent function.
const makeUserMessage: MakeUserMessageFunc = async function ({
  content,
  originalUserMessage,
}): Promise<OpenAiChatMessage & { role: "user" }> {
  const chunkSeparator = "~~~~~~";
  const context = content.map((c) => c.text).join(`\n${chunkSeparator}\n`);
  const contentForLlm = `Using the following information, answer the user query.
Different pieces of information are separated by "${chunkSeparator}".

Information:
${context}


User query: ${originalUserMessage}`;
  return { role: "user", content: contentForLlm };
};

// Generates the user prompt for the chatbot using RAG
const generateUserPrompt: GenerateUserPromptFunc = makeRagGenerateUserPrompt({
  findContent,
  makeUserMessage,
});

// System prompt for chatbot
const systemPrompt: SystemPrompt = {
  role: "system",
  content: `You are an assistant to users of the MongoDB Chatbot Framework.
Answer their questions about the framework in a friendly conversational tone.
Format your answers in Markdown.
Be concise in your answers.
If you do not know the answer to the question based on the information provided,
respond: "I'm sorry, I don't know the answer to that question. Please try to rephrase it. Refer to the below information to see if it helps."`,
};

// Create MongoDB collection and service for storing user conversations
// with the chatbot.
const mongodb = new MongoClient(MONGODB_CONNECTION_URI);
const conversations = makeMongoDbConversationsService(
  mongodb.db(MONGODB_DATABASE_NAME),
  systemPrompt
);

// Create the MongoDB Chatbot Server Express.js app configuration
const config: AppConfig = {
  conversationsRouterConfig: {
    llm,
    conversations,
    generateUserPrompt,
  },
  maxRequestTimeoutMs: 30000,
  serveStaticSite: true,
};

// Start the server and clean up resources on SIGINT.
const PORT = process.env.PORT || 3000;
const startServer = async () => {
  logger.info("Starting server...");
  const app = await makeApp(config);
  const server = app.listen(PORT, () => {
    logger.info(`Server listening on port: ${PORT}`);
  });

  process.on("SIGINT", async () => {
    logger.info("SIGINT signal received");
    await mongodb.close();
    await embeddedContentStore.close();
    await new Promise<void>((resolve, reject) => {
      server.close((error: any) => {
        error ? reject(error) : resolve();
      });
    });
    process.exit(1);
  });
};

try {
  startServer();
} catch (e) {
  logger.error(`Fatal error: ${e}`);
  process.exit(1);
}


Enter fullscreen mode Exit fullscreen mode

要了解有关 MongoDB Chatbot 服务器的更多信息,请访问该框架的服务器文档

聊天机器人用户界面

Chatbot UI提供了一系列 React UI 元素,可用于为您的网站添加聊天机器人前端。这些组件均可自定义,因此您可以根据自己的使用场景进行调整。

以下是一个基本的代码示例,展示了如何将聊天机器人 UI 组件添加到您的 React 应用程序中:



import Chatbot, {
  FloatingActionButtonTrigger,
  InputBarTrigger,
  ModalView,
} from "mongodb-chatbot-ui";

function MyApp() {
  const suggestedPrompts = [
    "How do I create a new MongoDB Atlas cluster?",
    "Can MongoDB store lists of data?",
    "How does vector search work?",
  ];
  return (
    <div>
      <Chatbot>
        <InputBarTrigger suggestedPrompts={suggestedPrompts} />
        <FloatingActionButtonTrigger text="My MongoDB AI" />
        <ModalView
          initialMessageText="Welcome to MongoDB AI Assistant. What can I help you with?"
          initialMessageSuggestedPrompts={suggestedPrompts}
        />
      </Chatbot>
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

这将创建一个如下所示的用户界面:

MongoDB聊天机器人框架UI演示

要了解有关 MongoDB 聊天机器人 UI 的更多信息,请访问该框架的 UI 文档

摄取 CLI

Ingest CLI模块是一个工具,您可以使用它来提取数据,以便在 RAG 聊天机器人中使用。

Ingest CLI 执行以下操作:

  • 从数据源提取数据
  • 将文档拆分成多个块,以便在 RAG 中使用。
  • 为分块内容创建矢量嵌入
  • 将数据块及其嵌入存储在使用 Atlas Vector Search 建立索引的 MongoDB 集合中。

Ingest CLI 处理与高性能数据摄取相关的复杂逻辑,例如仅在底层源数据更新或配置更改时才摄取数据。

Ingest CLI 让您可以更专注于数据摄取中与应用程序相关的方面。它提供了一系列接口和配置,您可以根据需要进行接入,以管理 RAG 的数据摄取。

DataSource接口允许您定义如何导入外部数据。您可以使用该DataSource接口从头开始构建自己的数据获取器,或者封装其他常用的数据获取器,例如LangChain.js 文档加载器Unstructured。您可以定义DataSource导入各种数据格式(例如 Markdown、PDF、HTML、JSON 和 CSV)的实现。定义好数据获取方式后,运行 Ingest CLI 即可通过编程方式更新 RAG 中使用的分块数据。

Ingest CLI 还包含一些模块,您可以根据新兴的 RAG 最佳实践,利用这些模块来优化数据摄取,以满足您的应用程序需求。例如,您可以选择 CLI 使用的嵌入模型、生成嵌入之前的数据转换方式以及分块策略。

您可以通过类似于以下内容的配置文件来定义要摄取的内容以及摄取方式:



// ingest.config.ts

import { makeIngestMetaStore, type Config } from "mongodb-rag-ingest";

import {
  makeOpenAiEmbedder,
  OpenAIClient,
  AzureKeyCredential,
  makeMongoDbEmbeddedContentStore,
  makeMongoDbPageStore,
} from "mongodb-rag-core";

import { standardChunkFrontMatterUpdater } from "mongodb-rag-ingest/embed";

import { type DataSource } from "mongodb-rag-ingest/sources";

const {
  MONGODB_DOT_COM_CONNECTION_URI,
  MONGODB_DOT_COM_DB_NAME,
  MONGODB_CONNECTION_URI,
  MONGODB_DATABASE_NAME,
  OPENAI_ENDPOINT,
  OPENAI_API_KEY,
  OPENAI_EMBEDDING_DEPLOYMENT,
} = process.env;

export default {
  embedder: () =>
    makeOpenAiEmbedder({
      openAiClient: new OpenAIClient(
        OPENAI_ENDPOINT,

        new AzureKeyCredential(OPENAI_API_KEY)
      ),

      deployment: OPENAI_EMBEDDING_DEPLOYMENT,

      backoffOptions: {
        numOfAttempts: 25,

        startingDelay: 1000,
      },
    }),
  embeddedContentStore: () =>
    makeMongoDbEmbeddedContentStore({
      connectionUri: MONGODB_CONNECTION_URI,

      databaseName: MONGODB_DATABASE_NAME,
    }),
  pageStore: () =>
    makeMongoDbPageStore({
      connectionUri: MONGODB_CONNECTION_URI,

      databaseName: MONGODB_DATABASE_NAME,
    }),
  ingestMetaStore: () =>
    makeIngestMetaStore({
      connectionUri: MONGODB_CONNECTION_URI,
      databaseName: MONGODB_DATABASE_NAME,
      entryId: "all",
    }),
  chunkOptions: () => ({
    transform: standardChunkFrontMatterUpdater,
  }),
  dataSources: () => [
    // Add your own data sources here.
    {
      name: "my-data-source",
      async fetchPages() {
        const pages: Page[] = await getPagesFromSomeSource();
        return pages;
      },
    },
  ],
} satisfies Config;


Enter fullscreen mode Exit fullscreen mode

编译 TypeScript 并使用 Ingest CLI 运行数据摄取:



tsc --outDir build && ingest all --config build/ingest.config.js


Enter fullscreen mode Exit fullscreen mode

要了解有关 MongoDB Chatbot Ingest CLI 的更多信息,请访问该框架的 Ingest 文档

使用 MongoDB Chatbot Framework 开始构建

如果您想开始使用 MongoDB Chatbot Framework,请查看文档中的快速入门指南。您可以使用快速入门指南搭建一个基于 MongoDB Chatbot Framework 的全栈应用程序,然后根据您的应用程序需求进行自定义。

文章来源:https://dev.to/mongodb/build-a-product-ready-intelligent-chatbot-with-the-mongodb-chatbot-framework-4dd