LLamaIndex LLM工具调用

在 LlamaIndex 中,代理是由 LLM 提供支持的半自主软件,它被赋予一项任务并执行一系列步骤来解决该任务。它有一组工具,可以是从任意函数到完整的 LlamaIndex 查询引擎的任何内容,它会选择最好的可用工具来完成每个步骤。完成每个步骤后,代理会判断任务现在是否已完成,在这种情况下,它会向用户返回结果,或者是否需要执行另一个步骤,在这种情况下,它会循环回到起点。

拥有适当的工具是在 LlamaIndex 中构建代理系统的核心。定义一组 Tools 类似于定义任何 API 接口,不同之处在于这些工具供代理使用,而不是供人工使用。我们允许用户定义 Tool 和 ToolSpec,其中包含一系列后台功能。

将代理或 LLM 与函数调用一起使用时,所选工具(以及为该工具编写的参数)在很大程度上依赖于工具名称和工具用途和参数的描述。花时间调整这些参数可能会导致 LLM 调用这些工具的方式发生巨大变化。

工具实现了一个非常通用的接口 - 只需定义并返回一些基本元数据(名称、描述、函数模式)。__call__

我们提供几种不同类型的工具:

  • FunctionTool:函数工具允许用户轻松地将任何用户定义的函数转换为工具。它还可以自动推断函数架构,或让您自定义各个方面。
  • QueryEngineTool:包装现有查询引擎的工具。注意:由于我们的 agent 抽象继承自 ,这些工具也可以包装其他 agent。BaseQueryEngine
  • 社区贡献,围绕单个服务(如 Gmail)定义一个或多个工具ToolSpecs
  • 用于包装其他工具以处理从工具返回大量数据的实用工具

注意FunctionAgent需要模型支持function_call

经测试本地模型推理可以使用llm.predict_and_call或者使用ReActAgent

 
# 使用llm和工具调用
from llama_index.core.agent.workflow import ReActAgent, FunctionAgent
from llama_index.core.base.llms.types import MessageRole,ChatMessage
from llama_index.core.tools import FunctionTool
from llama_index.llms.lmstudio import LMStudio






llm = LMStudio(
    model_name="qwen3-8b-instuct",
    base_url="http://localhost:9999/v1",
    temperature=0.7,
)

def generate_song(name: str, artist: str) -> dict[str,str]:
    """根据提供的歌曲名称和歌手生成一首歌曲信息。"""
    print(f"调用generate_song: {name}, artist: {artist}")
    return {
        "name": name,
        "artist": artist,
    }

def multiply(a: float, b: float) -> float:
    """将两个数字相乘并返回乘积。"""
    print(f"调用multiply: {a}, {b}")
    return a * b


def add(a: float, b: float) -> float:
    """将两个数字相加并返回和。"""
    print(f"调用add: {a}, {b}")
    return a + b
def test_llm_with_tool():
    tool = FunctionTool.from_defaults(fn=generate_song)
    response = llm.predict_and_call(
        tools=[tool],
        user_msg=ChatMessage(
                role=MessageRole.USER,
                content="给我一个歌曲的名字和歌手",
        )
    )
    print(str(response))

def test_llm_with_re_act_agent():
    agent = ReActAgent(
        llm=llm,
        tools=[
            FunctionTool.from_defaults(multiply),
            FunctionTool.from_defaults(add)
        ],
        system_prompt="你是一个擅长数学的助手。你可以使用 multiply 和 add 工具来回答问题。"
    )
    async def run_agent(user_msg: str) -> str:
        """Run the agent."""
        response = await agent.run(user_msg=user_msg)
        print( str(response))
    import asyncio
    asyncio.run(run_agent("2*3+4的结果是?"))

def test_llm_with_function_agent():
    agent = FunctionAgent(
        llm=llm,
        tools=[
            multiply,
           add
        ],
        system_prompt="你是一个擅长数学的助手。你可以使用 multiply 和 add 工具来回答问题。"
    )
    async def run_agent(user_msg: str) -> str:
        """Run the agent."""
        response = await agent.run(user_msg=user_msg)
        print( str(response))
    import asyncio
    asyncio.run(run_agent("2*3+4的结果是?"))
if __name__ == "__main__":
    print("_"*100)
    print("测试llm_with_tool")
    test_llm_with_tool()
    print("_"*100)
    print("测试llm_with_re_act_agent")
    test_llm_with_re_act_agent()
    # print("_"*100)
    # print("测试llm_with_function_agent")
    # test_llm_with_function_agent()

输出结果

____________________________________________________________________________________________________
测试llm_with_tool
歌曲名字是《天空》,歌手是五月天。
____________________________________________________________________________________________________
测试llm_with_re_act_agent
调用multiply: 2, 3
调用add: 6, 4
2*3+4的结果是10。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值