凡科网做网站贵吗,网站引导页利弊,公司网页设计图,爬虫代理ip购买文章目录 智能体概述智能体的定义智能体组成智能体范式 环境配置Lagent#xff1a;轻量级智能体框架实战Lagent Web Demo用 Lagent 自定义工具 AgentLego#xff1a;组装智能体“乐高”直接使用AgentLego作为智能体工具使用 用 AgentLego 自定义工具 智能体概述
智能体的定义… 文章目录 智能体概述智能体的定义智能体组成智能体范式 环境配置Lagent轻量级智能体框架实战Lagent Web Demo用 Lagent 自定义工具 AgentLego组装智能体“乐高”直接使用AgentLego作为智能体工具使用 用 AgentLego 自定义工具 智能体概述
智能体的定义
智能体的定义包括三点环境感知、动作、理解决策。
可以感知环境中的动态条件能采取动作影响环境能运用推理能力理解信息、解决问题、产生推断、决定动作。
智能体组成
智能体组成包括大脑、感知和动作
大脑作为控制器承担记忆、思考和决策任务。接受来自感知模块的信息并采取相应的动作感知对外部环境的多模态信息进行感知和处理。包括但不限于图像、音频、视频、传感器等动作利用并执行工具以影响环境。工具可能包括文本的检索、调用相关API、操控机械臂等
智能体范式
精典的智能体范式包括AutoGPT、ReWoo、ReAct
AutoGPT ReWoo
环境配置 创建开发机 在创建开发机界面选择镜像为 Cuda12.2-conda并选择 GPU 为30% A100。 创建一个agent的虚拟环境 studio-conda -t agent -o pytorch-2.1.2安装Lagent和AgentLego Lagent 和 AgentLego 都提供了两种安装方法一种是通过 pip 直接进行安装另一种则是从源码进行安装。为了方便使用 Lagent 的 Web Demo 以及 AgentLego 的 WebUI我们选择直接从源码进行安装。 此处附上源码安装的相关帮助文档 cd /root/agent
conda activate agent
git clone https://gitee.com/internlm/lagent.git
cd lagent git checkout 581d9fb pip install -e . cd ..
git clone https://gitee.com/internlm/agentlego.git
cd agentlego git checkout 7769e0d pip install -e . cd ..安装其他依赖 在这一步中我们将会安装其他将要用到的依赖库如 LMDeploy可以执行如下命令 conda activate agent
pip install lmdeploy0.3.0准备Tutorial 由于后续的 Demo 需要用到 tutorial 已经写好的脚本因此我们需要将 tutorial 通过 git clone 的方法准备好以备后续使用 cd /root/agent
git clone -b camp2 https://gitee.com/internlm/Tutorial.gitLagent轻量级智能体框架实战
Lagent Web Demo 使用LMDeploy部署 由于 Lagent 的 Web Demo 需要用到 LMDeploy 所启动的 api_server因此我们首先按照下图指示在 vscode terminal 中执行如下代码使用 LMDeploy 启动一个 api_server。 conda activate agent
lmdeploy serve api_server /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-7b \--server-name 127.0.0.1 \--model-name internlm2-chat-7b \--cache-max-entry-count 0.1启动并使用 Lagent Web Demo 接下来我们按照下图指示新建一个 terminal 以启动 Lagent Web Demo。在新建的 terminal 中执行如下指令 conda activate agent
cd /root/agent/lagent/examples
streamlit run internlm2_agent_web_demo.py --server.address 127.0.0.1 --server.port 7860在本地进行端口映射详细映射过程见书生·浦语大模型InternLM-Chat-1.8B 智能对话 Demo 第二期 的运行Demo ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 rootssh.intern-ai.org.cn -p 你的 ssh 端口号在本地的浏览器页面中打开 http://localhost:7860 以使用 Lagent Web Demo。首先输入模型 IP 为 127.0.0.1:23333在输入完成后按下回车键以确认。并选择插件为 ArxivSearch以让模型获得在 arxiv 上搜索论文的能力。
用 Lagent 自定义工具
在本节中我们将基于 Lagent 自定义一个工具。Lagent 中关于工具部分的介绍文档位于 https://lagent.readthedocs.io/zh-cn/latest/tutorials/action.html 。使用 Lagent 自定义工具主要分为以下几步 1.继承 BaseAction 类 2.实现简单工具的 run 方法或者实现工具包内每个子工具的功能 3.简单工具的 run 方法可选被 tool_api 装饰工具包内每个子工具的功能都需要被 tool_api 装饰 创建工具文件 使用下列命令新建一个工具文件weather.py内容如下 powershelltouch /root/agent/lagent/lagent/actions/weather.pyimport json
import os
import requests
from typing import Optional, Typefrom lagent.actions.base_action import BaseAction, tool_api
from lagent.actions.parser import BaseParser, JsonParser
from lagent.schema import ActionReturn, ActionStatusCodeclass WeatherQuery(BaseAction):Weather plugin for querying weather information.def __init__(self,key: Optional[str] None,description: Optional[dict] None,parser: Type[BaseParser] JsonParser,enable: bool True) - None:super().__init__(description, parser, enable)key os.environ.get(WEATHER_API_KEY, key)if key is None:raise ValueError(Please set Weather API key either in the environment as WEATHER_API_KEY or pass it as key)self.key keyself.location_query_url https://geoapi.qweather.com/v2/city/lookupself.weather_query_url https://devapi.qweather.com/v7/weather/nowtool_apidef run(self, query: str) - ActionReturn:一个天气查询API。可以根据城市名查询天气信息。Args:query (:class:str): The city name to query.tool_return ActionReturn(typeself.name)status_code, response self._search(query)if status_code -1:tool_return.errmsg responsetool_return.state ActionStatusCode.HTTP_ERRORelif status_code 200:parsed_res self._parse_results(response)tool_return.result [dict(typetext, contentstr(parsed_res))]tool_return.state ActionStatusCode.SUCCESSelse:tool_return.errmsg str(status_code)tool_return.state ActionStatusCode.API_ERRORreturn tool_returndef _parse_results(self, results: dict) - str:Parse the weather results from QWeather API.Args:results (dict): The weather content from QWeather APIin json format.Returns:str: The parsed weather results.now results[now]data [f数据观测时间: {now[obsTime]},f温度: {now[temp]}°C,f体感温度: {now[feelsLike]}°C,f天气: {now[text]},f风向: {now[windDir]}角度为 {now[wind360]}°,f风力等级: {now[windScale]}风速为 {now[windSpeed]} km/h,f相对湿度: {now[humidity]},f当前小时累计降水量: {now[precip]} mm,f大气压强: {now[pressure]} 百帕,f能见度: {now[vis]} km,]return \n.join(data)def _search(self, query: str):# get city_codetry:city_code_response requests.get(self.location_query_url,params{key: self.key, location: query})except Exception as e:return -1, str(e)if city_code_response.status_code ! 200:return city_code_response.status_code, city_code_response.json()city_code_response city_code_response.json()if len(city_code_response[location]) 0:return -1, 未查询到城市city_code city_code_response[location][0][id]# get weathertry:weather_response requests.get(self.weather_query_url,params{key: self.key, location: city_code})except Exception as e:return -1, str(e)return weather_response.status_code, weather_response.json()获取 API KEY 获取天气查询服务的 API KEY打开 https://dev.qweather.com/docs/api/ 后点击控制台登入 在首页中我的项目点击创建 输入项目名称选择免费订阅、Web API输入KEY的名称点击创建 创建好后在项目管理中查看 KEY并复制下来 体验自定义工具效果 使用 LMDeploy 启动一个 api_server conda activate agent
lmdeploy serve api_server /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-7b \--server-name 127.0.0.1 \--model-name internlm2-chat-7b \--cache-max-entry-count 0.1新建一个 terminal 以启动 Lagent Web Demo export WEATHER_API_KEY获取的API KEY
# 比如 export WEATHER_API_KEY1234567890abcdef
conda activate agent
cd /root/agent/Tutorial/agent
streamlit run internlm2_weather_web_demo.py --server.address 127.0.0.1 --server.port 7860在本地进行端口映射 ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 rootssh.intern-ai.org.cn -p 你的 ssh 端口号Demo体验如下
AgentLego组装智能体“乐高”
直接使用AgentLego 准备一张图片直接使用下面命令下载 cd /root/agent
wget http://download.openmmlab.com/agentlego/road.jpg安装检测依赖 由于 AgentLego 在安装时并不会安装某个特定工具的依赖因此我们接下来准备安装目标检测工具运行时所需依赖。 AgentLego 所实现的目标检测工具是基于 mmdet (MMDetection) 算法库中的 RTMDet-Large 模型因此我们首先安装 mim然后通过 mim 工具来安装 mmdet。这一步所需时间可能会较长请耐心等待。 conda activate agent
pip install openmim0.3.9
mim install mmdet3.3.0在/root/agent创建一个direct_use.py文件复制一下代码 import reimport cv2
from agentlego.apis import load_tool# load tool
tool load_tool(ObjectDetection, devicecuda)# apply tool
visualization tool(/root/agent/road.jpg)
print(visualization)# visualize
image cv2.imread(/root/agent/road.jpg)preds visualization.split(\n)
pattern r(\w) \((\d), (\d), (\d), (\d)\), score (\d)for pred in preds:name, x1, y1, x2, y2, score re.match(pattern, pred).groups()x1, y1, x2, y2, score int(x1), int(y1), int(x2), int(y2), int(score)cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 1)cv2.putText(image, f{name} {score}, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 1)cv2.imwrite(/root/agent/road_detection_direct.jpg, image)执行 direct_use.py 及可以实现检测
作为智能体工具使用 修改模型配置 由于 AgentLego 算法库默认使用 InternLM2-Chat-20B 模型因此我们首先需要修改 /root/agent/agentlego/webui/modules/agents/lagent_agent.py 文件的第 105行位置将 internlm2-chat-20b 修改为 internlm2-chat-7b即 def llm_internlm2_lmdeploy(cfg):url cfg[url].strip()llm LMDeployClient(
- model_nameinternlm2-chat-20b,model_nameinternlm2-chat-7b,urlurl,meta_templateINTERNLM2_META,top_p0.8,top_k100,temperaturecfg.get(temperature, 0.7),repetition_penalty1.0,stop_words[|im_end|])return llm使用LMDeploy部署 由于 AgentLego 的 WebUI 需要用到 LMDeploy 所启动的 api_server因此我们首先按照下图指示在 vscode terminal 中执行如下代码使用 LMDeploy 启动一个 api_server。 conda activate agent
lmdeploy serve api_server /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-7b \--server-name 127.0.0.1 \--model-name internlm2-chat-7b \--cache-max-entry-count 0.1启动AgentLego WebUI 接下来我们按照下图指示新建一个 terminal 以启动 AgentLego WebUI。在新建的 terminal 中执行如下指令 conda activate agent
cd /root/agent/agentlego/webui
python one_click.py在等待 LMDeploy 的 api_server 与 AgentLego WebUI 完全启动后如下图所示在本地进行端口映射将 LMDeploy api_server 的23333端口以及 AgentLego WebUI 的7860端口映射到本地。可以执行详细步骤见基于InternLM 和 LangChain 搭建你的知识库Demo 的web部署部分 ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 rootssh.intern-ai.org.cn -p 你的 ssh 端口号使用 AgentLego WebUI 配置Agent 在本地的浏览器页面中打开 http://localhost:7860 以使用 AgentLego WebUI。首先来配置 Agent如下图所示 点击上方 Agent 进入 Agent 配置页面。点击 Agent 下方框选择 New Agent。选择 Agent Class 为 lagent.InternLM2Agent。输入模型 URL 为 http://127.0.0.1:23333 。输入 Agent name自定义即可图中输入了 internlm2。点击 save to 以保存配置这样在下次使用时只需在第2步时选择 Agent 为 internlm2 后点击 load 以加载就可以了。点击 load 以加载配置。如⑦所示 配置tool 点击上方 Tools 页面进入工具配置页面。点击 Tools 下方框选择 New Tool 以加载新工具。选择 Tool Class 为 ObjectDetection。点击 save 以保存配置。 选择工具 等待工具加载完成后点击上方 Chat 以进入对话页面。在页面下方选择工具部分只选择 ObjectDetection 工具如下图所示。为了确保调用工具的成功率请在使用时确保仅有这一个工具启用。 结果展示
用 AgentLego 自定义工具 创建工具文件 首先通过 touch /root/agent/agentlego/agentlego/tools/magicmaker_image_generation.py大小写敏感的方法新建工具文件。该文件的内容如下 import json
import requestsimport numpy as npfrom agentlego.types import Annotated, ImageIO, Info
from agentlego.utils import require
from .base import BaseToolclass MagicMakerImageGeneration(BaseTool):default_desc (This tool can call the api of magicmaker to generate an image according to the given keywords.)styles_option [dongman, # 动漫guofeng, # 国风xieshi, # 写实youhua, # 油画manghe, # 盲盒]aspect_ratio_options [16:9, 4:3, 3:2, 1:1,2:3, 3:4, 9:16]require(opencv-python)def __init__(self,styleguofeng,aspect_ratio4:3):super().__init__()if style in self.styles_option:self.style styleelse:raise ValueError(fThe style must be one of {self.styles_option})if aspect_ratio in self.aspect_ratio_options:self.aspect_ratio aspect_ratioelse:raise ValueError(fThe aspect ratio must be one of {aspect_ratio})def apply(self,keywords: Annotated[str,Info(A series of Chinese keywords separated by comma.)]) - ImageIO:import cv2response requests.post(urlhttps://magicmaker.openxlab.org.cn/gw/edit-anything/api/v1/bff/sd/generate,datajson.dumps({official: True,prompt: keywords,style: self.style,poseT: False,aspectRatio: self.aspect_ratio}),headers{content-type: application/json})image_url response.json()[data][imgUrl]image_response requests.get(image_url)image cv2.cvtColor(cv2.imdecode(np.frombuffer(image_response.content, np.uint8), cv2.IMREAD_COLOR),cv2.COLOR_BGR2RGB)return ImageIO(image)注册新工具 接下来修改 /root/agent/agentlego/agentlego/tools/init.py 文件将我们的工具注册在工具列表中。如下所示我们将 MagicMakerImageGeneration 通过 from .magicmaker_image_generation import MagicMakerImageGeneration 导入到了文件中并且将其加入了 all 列表中。 from .base import BaseTool
from .calculator import Calculator
from .func import make_tool
from .image_canny import CannyTextToImage, ImageToCanny
from .image_depth import DepthTextToImage, ImageToDepth
from .image_editing import ImageExpansion, ImageStylization, ObjectRemove, ObjectReplace
from .image_pose import HumanBodyPose, HumanFaceLandmark, PoseToImage
from .image_scribble import ImageToScribble, ScribbleTextToImage
from .image_text import ImageDescription, TextToImage
from .imagebind import AudioImageToImage, AudioTextToImage, AudioToImage, ThermalToImage
from .object_detection import ObjectDetection, TextToBbox
from .ocr import OCR
from .scholar import * # noqa: F401, F403
from .search import BingSearch, GoogleSearch
from .segmentation import SegmentAnything, SegmentObject, SemanticSegmentation
from .speech_text import SpeechToText, TextToSpeech
from .translation import Translation
from .vqa import VQAfrom .magicmaker_image_generation import MagicMakerImageGeneration__all__ [CannyTextToImage, ImageToCanny, DepthTextToImage, ImageToDepth,ImageExpansion, ObjectRemove, ObjectReplace, HumanFaceLandmark,HumanBodyPose, PoseToImage, ImageToScribble, ScribbleTextToImage,ImageDescription, TextToImage, VQA, ObjectDetection, TextToBbox, OCR,SegmentObject, SegmentAnything, SemanticSegmentation, ImageStylization,AudioToImage, ThermalToImage, AudioImageToImage, AudioTextToImage,SpeechToText, TextToSpeech, Translation, GoogleSearch, Calculator,
- BaseTool, make_tool, BingSearchBaseTool, make_tool, BingSearch, MagicMakerImageGeneration
]体验自定义工具效果 与上章节的作为智能体工具使用运行启动步骤是一样的 conda activate agent
lmdeploy serve api_server /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-7b \--server-name 127.0.0.1 \--model-name internlm2-chat-7b \--cache-max-entry-count 0.1conda activate agent
cd /root/agent/agentlego/webui
python one_click.py并在本地执行如下操作以进行端口映射 ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 rootssh.intern-ai.org.cn -p 你的 ssh 端口号运行结果