智能体#
在 LlamaIndex 中构建一个智能体可以通过定义一组工具并将其提供给我们的 ReActAgent 或 FunctionAgent 实现来完成。我们在这里将其与 OpenAI 一起使用,但它可以用于任何足够强大的 LLM。
通常,对于其 API 中内置函数调用/工具的 LLM(如 OpenAI、Anthropic、Gemini 等),应优先选择 FunctionAgent。
from llama_index.core.tools import FunctionTool
from llama_index.llms.openai import OpenAI
from llama_index.core.agent.workflow import ReActAgent, FunctionAgent
# define sample Tool
def multiply(a: int, b: int) -> int:
"""Multiply two integers and returns the result integer"""
return a * b
# initialize llm
llm = OpenAI(model="gpt-4o")
# initialize agent
agent = FunctionAgent(
tools=[multiply],
system_prompt="You are an agent that can invoke a tool for multiplication when assisting a user.",
)
这些工具可以是如上所示的 Python 函数,也可以是 LlamaIndex 查询引擎
from llama_index.core.tools import QueryEngineTool
query_engine_tools = [
QueryEngineTool.from_defaults(
query_engine=sql_agent,
name="sql_agent",
description="Agent that can execute SQL queries.",
),
]
agent = FunctionAgent(
tools=query_engine_tools,
system_prompt="You are an agent that can invoke an agent for text-to-SQL execution.",
)