跳至内容

入门教程(使用OpenAI)#

本教程将向您展示如何开始使用LlamaIndex构建智能体。我们将从一个基础示例开始,然后演示如何添加RAG(检索增强生成)功能。

提示

请确保您已按照安装步骤进行操作。

提示

想使用本地模型吗? 如果你想仅使用本地模型来完成我们的入门教程,请查看这个教程

设置您的OpenAI API密钥#

LlamaIndex 默认使用 OpenAI 的 gpt-3.5-turbo。请确保通过将其设置为环境变量使您的 API 密钥对代码可用:

# MacOS/Linux
export OPENAI_API_KEY=XXXXX

# Windows
set OPENAI_API_KEY=XXXXX

提示

如果您正在使用与OpenAI兼容的API,可以使用OpenAILike LLM类。更多信息请参阅OpenAILike LLM集成和OpenAILike Embeddings集成。

基础智能体示例#

让我们从一个简单的例子开始,使用一个能够通过调用工具执行基本乘法的智能体。创建一个名为starter.py的文件:

import asyncio
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.openai import OpenAI


# Define a simple calculator tool
def multiply(a: float, b: float) -> float:
    """Useful for multiplying two numbers."""
    return a * b


# Create an agent workflow with our calculator tool
agent = FunctionAgent(
    tools=[multiply],
    llm=OpenAI(model="gpt-4o-mini"),
    system_prompt="You are a helpful assistant that can multiply two numbers.",
)


async def main():
    # Run the agent
    response = await agent.run("What is 1234 * 4567?")
    print(str(response))


# Run the agent
if __name__ == "__main__":
    asyncio.run(main())

这将输出类似以下内容:The result of \( 1234 \times 4567 \) is \( 5,678,678 \).

发生的情况是:

  • 智能体被提问:What is 1234 * 4567?
  • 在底层实现中,这个问题连同工具的模式(名称、文档字符串和参数)都被传递给了LLM
  • 智能体选择了multiply工具并写入了工具参数
  • 智能体从工具接收到结果并将其插入到最终响应中

提示

如你所见,我们正在使用async Python函数。许多LLM和模型都支持异步调用,建议使用异步代码来提高应用程序的性能。要了解更多关于异步代码和Python的信息,我们推荐这个关于异步+Python的简短章节

添加聊天历史记录#

AgentWorkflow 还能够记住之前的消息。这些信息包含在 AgentWorkflowContext 中。

如果传入Context参数,智能体将使用它来继续对话。

from llama_index.core.workflow import Context

# create context
ctx = Context(agent)

# run agent with context
response = await agent.run("My name is Logan", ctx=ctx)
response = await agent.run("What is my name?", ctx=ctx)

添加RAG功能#

现在让我们通过添加文档搜索功能来增强我们的智能体。首先,使用终端获取一些示例数据:

mkdir data
wget https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt -O data/paul_graham_essay.txt

您的目录结构现在应该如下所示:

├── starter.py
└── data
    └── paul_graham_essay.txt

现在我们可以创建一个使用LlamaIndex搜索文档的工具。默认情况下,我们的VectorStoreIndex将使用OpenAI的text-embedding-ada-002嵌入模型来嵌入和检索文本。

我们修改后的 starter.py 应该如下所示:

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.openai import OpenAI
import asyncio
import os

# Create a RAG tool using LlamaIndex
documents = SimpleDirectoryReader("data").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()


def multiply(a: float, b: float) -> float:
    """Useful for multiplying two numbers."""
    return a * b


async def search_documents(query: str) -> str:
    """Useful for answering natural language questions about an personal essay written by Paul Graham."""
    response = await query_engine.aquery(query)
    return str(response)


# Create an enhanced workflow with both tools
agent = FunctionAgent(
    tools=[multiply, search_documents],
    llm=OpenAI(model="gpt-4o-mini"),
    system_prompt="""You are a helpful assistant that can perform calculations
    and search through documents to answer questions.""",
)


# Now we can ask questions about the documents or do calculations
async def main():
    response = await agent.run(
        "What did the author do in college? Also, what's 7 * 8?"
    )
    print(response)


# Run the agent
if __name__ == "__main__":
    asyncio.run(main())

该智能体现在可以无缝切换使用计算器和搜索文档来回答问题。

存储RAG索引#

为了避免每次重新处理文档,你可以将索引持久化到磁盘:

# Save the index
index.storage_context.persist("storage")

# Later, load the index
from llama_index.core import StorageContext, load_index_from_storage

storage_context = StorageContext.from_defaults(persist_dir="storage")
index = load_index_from_storage(storage_context)
query_engine = index.as_query_engine()

提示

如果你使用了除默认之外的向量存储集成,很可能你可以直接从向量存储重新加载:

index = VectorStoreIndex.from_vector_store(vector_store)

下一步是什么?#

这只是您可以使用LlamaIndex智能体实现功能的开始!您可以:

  • 为您的智能体添加更多工具
  • 使用不同的LLMs
  • 使用系统提示自定义智能体的行为
  • 添加流式处理能力
  • 实现人机协作的工作流程
  • 使用多个智能体协作完成任务

一些可能有用的后续链接:

优云智算