宣布 LlamaCloud 全面上市(以及我们的 1900 万美元 A 轮融资)!
LlamaIndex

伊曼纽尔·费雷拉 (Emanuel Ferreira) 2024-02-08

如何使用 LlamaIndex.TS 在 TypeScript 中构建 LLM 智能体

智能体是自主系统,无需过多或少量指令即可执行端到端任务。这些智能体能够解决问答、使用工具实现所需行为甚至规划任务等相关任务。

在本文中,我们将探索 LlamaIndex.TS 内置智能体的部分功能来实现一系列目标。我们有两个部分:

  1. 构建一个用于计算的简单智能体。
  2. 使用智能体处理您的个人/私有数据来回答问题。

所有完整的代码示例将在文章末尾提供。

设置

首先,您需要在 Node 环境设置中安装 llamaindex 包,并拥有一个 OpenAI 密钥。

安装包:

npm install llamaindex 

要设置 OpenAI 密钥,您可以设置环境变量:

export OPENAI_API_KEY=sk-***************

用于计算的智能体

第一个智能体将负责获取用户输入的数字,并根据这些数字选择正确的工具来完成任务。

导入类:

import { FunctionTool, OpenAIAgent } from "llamaindex";

函数工具

第一步是创建智能体可以访问的工具,我们将创建 add 函数和 multiply 函数。

OpenAI 提供了函数调用 API,我们可以发送函数参数并获得响应。

我们首先创建两个函数:

// Define a function to sum two numbers
function sum({ a, b }: { a: number; b: number }): number {
  return a + b;
}

// Define a function to multiply two numbers
function multiply({ a, b }: { a: number; b: number }): number {
  return a * b;
}

现在我们可以设置将提供给智能体的 FunctionTool 类,该类需要函数的属性和工具的元数据,帮助大型语言模型 (LLMs) 识别 LLM 应该使用哪个工具及其参数。

// Sum properties to give to the LLM
const sumJSON = {
  type: "object",
  properties: {
    a: {
      type: "number",
      description: "The first number",
    },
    b: {
      type: "number",
      description: "The second number",
    },
  },
  required: ["a", "b"],
};

// Multiply properties to give to the LLM
const multiplyJSON = {
  type: "object",
  properties: {
    a: {
      type: "number",
      description: "The number to multiply",
    },
    b: {
      type: "number",
      description: "The multiplier",
    },
  },
  required: ["a", "b"],
};

// Create sum function tool
const sumFunctionTool = new FunctionTool(sum, {
  name: "sum",
  description: "Use this function to sum two numbers",
  parameters: sumJSON,
});

// Creat multiply function tool
const multiplyFunctionTool = new FunctionTool(multiply, {
  name: "multiply",
  description: "Use this function to multiply two numbers",
  parameters: multiplyJSON,
});

与智能体对话

现在我们有了提供给智能体的工具,我们可以设置智能体了。

// Setup the agent with the respective tools
const agent = new OpenAIAgent({
  tools: [sumFunctionTool, multiplyFunctionTool],
  verbose: true,
});

然后提问:

// Chat with LLM
const response = await agent.chat({
  message: "How much is 5 + 5? then multiply by 2",
});

// Agent output
console.log(String(response));

现在,智能体将选择正确的工具,使用您提供的函数来完成所需任务。然后您应该会看到如下输出:

=== Calling Function ===
Calling function: sum with args: {
  "a": 5,
  "b": 5
}
Got output 10
==========================
=== Calling Function ===
Calling function: multiply with args: {
  "a": 10,
  "b": 2
}
Got output 20
==========================
The result of adding 5 and 5 is 10. When you multiply 10 by 2, the result is 20.

使用智能体处理您的文档

第二个智能体将负责浏览 Dan Abramov 的一系列文章,并根据可用数据回答问题。

首先,我们将导入必要的类和函数:

导入类和函数:

import {
  OpenAIAgent,
  SimpleDirectoryReader,
  VectorStoreIndex,
  SummaryIndex,
  QueryEngineTool,
} from "llamaindex";

加载文档

现在我们将加载文档并将其插入到本地向量存储索引中,该索引将负责存储文档并允许智能体查询最相关的任务数据,以及一个摘要向量索引,该索引可以更好地帮助处理摘要相关任务。

// Load the documents
const documents = await new SimpleDirectoryReader().loadData({
  directoryPath: "node_modules/llamaindex/examples",
});

// Create a vector index from the documents
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
const summaryIndex = await SummaryIndex.fromDocuments(documents)

创建查询引擎工具

现在我们将创建允许智能体访问向量索引的工具。

// Create a query engine from the vector index
const abramovQueryEngine = vectorIndex.asQueryEngine();
const abramovSummaryEngine = summaryIndex.asQueryEngine();

// Create a QueryEngineTool with the vector engine
const vectorEngineTool = new QueryEngineTool({
  queryEngine: abramovQueryEngine,
  metadata: {
    name: "abramov_query_engine",
    description: "Use this engine to answer specific questions about Abramov",
  },
});

// Create a QueryEngineTool with the summary engine
const summaryEngineTool = new QueryEngineTool({
  queryEngine: abramovSummaryEngine,
  metadata: {
    name: "abramov_summary_engine",
    description: "Use this engine to generate summaries about Abramov",
  },
});

创建 OpenAI 智能体

现在我们可以创建并为智能体提供必要的工具了。

// Setup the agent 
const agent = new OpenAIAgent({
  tools: [vectorEngineTool, summaryEngineTool],
  verbose: true,
});

与智能体对话

现在您可以与智能体讨论 Dan Abramov,它将选择正确的工具来达成目标。


// Chat with Agent
const response = await agent.chat({
  message: "Where he worked in his 20s?",
});

// Log output
console.log(String(response));

工具输出:

=== Calling Function ===
Calling function: abramov_query_engine with args: {
  "query": "work experience in 20s"
}
Got output The individual had their first job as a software developer in their 20s. They worked for a Russian-American outsourcing company and their salary was $18k/year.
==========================
In his 20s, Abramov worked as a software developer for a Russian-American outsourcing company. His salary during that time was $18,000 per year.

结论

自主智能体在创建可以将您的业务提升到新水平或让您的生活更轻松的工作流程和自动化方面非常强大。

在它们完全自主之前还有很长的路要走,但 LLM 的出现正在为这些推理和决策引擎迈出第一步。

您日常生活中是否已经在使用智能体了?想讨论智能体或寻求帮助吗?可以在 Twitter 上联系我。

参考文献

代码示例:https://github.com/EmanuelCampos/agents-typescript-example

LLamaIndexTS 文档:https://ts.llamaindex.ai/modules/agent/openai

https://llamaindex.org.cn/