使用 llamaIndex 快速实现智能体

AI 智能体就是可以根据当前环境进行推理,并根据处理结果进行下一步的操作。简单来说 AI 智能体可以与外界环境进行交互,并根据结果执行更复杂的操作。本文将通过llamaIndex 实现一个简单的 Agent 实时获取数据,由于大模型是通过静态数据进行训练的,没有实时获取数据的能力,只能通过 FunctionCall 调用外部 API 获取数据并进行处理。

在 llamaIndex 框架中对 FunctionCall 进行了抽象和包装,开发者只需要调用对应的 API 进行模型设置以及 FunctionTool 设置。本例中,模型采用 Ollama Qwen2:7B,通过 API 获取天气,获取摄氏度之后再转为华氏度。运行本例,需要在本地安装 Ollama 并下载 Qwen2:7B 模型。

import json
from typing import Sequence, List

from llama_index.core.llms import ChatMessage
from llama_index.core.tools import BaseTool, FunctionTool
from llama_index.core.agent import ReActAgent
from llama_index.llms.ollama import Ollama
from llama_index.core import Settings
import nest_asyncio
import requests

nest_asyncio.apply()
llm = Ollama(model="qwen2:7b", request_timeout=120.0)
Settings.llm = llm

def celsius_to_fahrenheit(celsius):
    '''将摄氏度装维华氏度,输入摄氏度返回华氏度'''
    return (celsius * 9/5) + 32


def get_weather(city):
    """获取某城市的天气并返回摄氏度"""
    latitude = 39.9042
    longitude = 116.4074

    url = "https://api.open-meteo.com/v1/forecast"
    params = {
        "latitude": latitude,
        "longitude": longitude,
        "current_weather": True
    }
    
    response = requests.get(url, params=params)
    
    if response.status_code == 200:
        data = response.json()
        current_temperature = data["current_weather"]["temperature"]
        return current_temperature
    else:
        return None

weather_tool = FunctionTool.from_defaults(fn=get_weather)
celsius_to_fahrenheit_tool = FunctionTool.from_defaults(fn=celsius_to_fahrenheit)

agent = ReActAgent.from_tools(
    [celsius_to_fahrenheit_tool, weather_tool],
    llm=llm,
    verbose=True,
)

response = agent.chat(" 通过 api 获取北京天气,华氏度和摄氏度? 请列出详细步骤 ")

截图中是运行结果,可以看到 Agent 推理的详细步骤。

在这里插入图片描述

总结

llamaIndex 进行 Agent 开发非常简单,几行代码就可以接入完成,上面的这个例子相对简单,在项目的业务场景中,需要提供更复杂的 API,为了减少幻觉,还需要与 RAG 进行结合,从而达到更好的结果。

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值