智能体#
在LlamaIndex中,我们将"agent"定义为一种特定系统,它使用LLM、记忆和工具来处理外部用户的输入。这与术语"agentic"形成对比,后者通常指代智能体的超类,即在流程中包含LLM决策的任何系统。
在LlamaIndex中创建一个智能体,仅需几行代码:
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())
调用此智能体会触发一系列特定的操作循环:
- 智能体获取最新消息 + 聊天历史记录
- 工具架构和聊天记录通过API发送
- The Agent responds either with a direct response, or a list of tool calls
- 每次工具调用都会被执行
- 工具调用结果会被添加到聊天历史记录中
- 智能体会根据更新的历史记录再次被调用,并直接响应或选择更多调用
工具#
工具可以简单地定义为Python函数,或者通过使用FunctionTool
和QueryEngineTool
等类进行进一步定制。LlamaIndex还通过名为Tool Specs
的功能为常见API提供了一系列预定义工具。
你可以在工具指南中了解更多关于配置工具的信息
记忆#
在构建智能体时,内存是一个核心组件。默认情况下,所有LlamaIndex智能体都使用ChatMemoryBuffer作为内存。
要自定义它,您可以在智能体外部声明并传入:
from llama_index.core.memory import ChatMemoryBuffer
memory = ChatMemoryBuffer.from_defaults(token_limit=40000)
response = await agent.run(..., memory=memory)
你可以在内存指南中了解更多关于配置内存的信息
多模态智能体#
一些大型语言模型(LLM)支持多模态输入,例如图像和文本。通过使用包含内容块的聊天消息,我们可以将图像传递给智能体进行推理。
例如,假设您有一张本演示文稿中的幻灯片的截图。
你可以将此图像传递给智能体进行推理,并观察它如何读取图像并相应采取行动。
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.core.llms import ChatMessage, ImageBlock, TextBlock
from llama_index.llms.openai import OpenAI
llm = OpenAI(model="gpt-4o-mini", api_key="sk-...")
def add(a: int, b: int) -> int:
"""Useful for adding two numbers together."""
return a + b
workflow = FunctionAgent(
tools=[add],
llm=llm,
)
msg = ChatMessage(
role="user",
blocks=[
TextBlock(text="Follow what the image says."),
ImageBlock(path="./screenshot.png"),
],
)
response = await workflow.run(msg)
print(str(response))
多智能体系统#
您可以将多个智能体组合成一个多智能体系统,其中每个智能体能够在完成任务的过程中将控制权移交给另一个智能体进行协调。
from llama_index.core.agent.workflow import AgentWorkflow
multi_agent = AgentWorkflow(agents=[FunctionAgent(...), FunctionAgent(...)])
resp = await agent.run("query")
继续阅读以了解更多关于多智能体系统的信息。
手动智能体#
虽然像FunctionAgent
、ReActAgent
、CodeActAgent
和AgentWorkflow
这样的智能体类抽象了很多细节,但有时需要构建自己的底层智能体。
直接使用LLM
对象,您可以快速实现一个基础的智能体循环,同时完全掌控工具调用和错误处理的工作方式。
from llama_index.core.llms import ChatMessage
from llama_index.core.tools import FunctionTool
from llama_index.llms.openai import OpenAI
def select_song(song_name: str) -> str:
"""Useful for selecting a song."""
return f"Song selected: {song_name}"
tools = [FunctionTool.from_defaults(select_song)]
tools_by_name = {t.metadata.name: t for t in [tool]}
# call llm with initial tools + chat history
chat_history = [ChatMessage(role="user", content="Pick a random song for me")]
resp = llm.chat_with_tools([tool], chat_history=chat_history)
# parse tool calls from response
tool_calls = llm.get_tool_calls_from_response(
resp, error_on_no_tool_call=False
)
# loop while there are still more tools to call
while tool_calls:
# add the LLM's response to the chat history
chat_history.append(resp.message)
# call every tool and add its result to chat_history
for tool_call in tool_calls:
tool_name = tool_call.tool_name
tool_kwargs = tool_call.tool_kwargs
print(f"Calling {tool_name} with {tool_kwargs}")
tool_output = tool(**tool_kwargs)
chat_history.append(
ChatMessage(
role="tool",
content=str(tool_output),
# most LLMs like OpenAI need to know the tool call id
additional_kwargs={"tool_call_id": tool_call.tool_id},
)
)
# check if the LLM can write a final response or calls more tools
resp = llm.chat_with_tools([tool], chat_history=chat_history)
tool_calls = llm.get_tool_calls_from_response(
resp, error_on_no_tool_call=False
)
# print the final response
print(resp.message.content)
示例 / 模块指南#
您可以在模块指南页面找到更完整的示例列表和模块指南。