Lagent 自定义你的 Agent 智能体
任务:使用 Lagent 自定义一个智能体,并使用 Lagent Web Demo 成功部署与调用
复现过程
1、根据教材部署环境。https://github.com/InternLM/Tutorial/blob/camp3/docs/L2/Lagent/readme.md
2、启动Lagent Web Demo 和LMDeploy api_server,注意,Lagent Web Demo的model要填实际的model name。
conda activate agent_camp3
lmdeploy serve api_server /share/new_models/Shanghai_AI_Laboratory/internlm2_5-7b-chat --model-name internlm2_5-7b-chat
cd /root/agent_camp3/lagent
conda activate agent_camp3
streamlit run examples/internlm2_agent_web_demo.py
3、制作新的插件magicmaker和weatherquery
代码如下:
import json
import requests
from lagent.actions.base_action import BaseAction, tool_api
from lagent.actions.parser import BaseParser, JsonParser
from lagent.schema import ActionReturn, ActionStatusCode
class MagicMaker(BaseAction):
styles_option = [
'dongman', # 动漫
'guofeng', # 国风
'xieshi', # 写实
'youhua', # 油画
'manghe', # 盲盒
]
aspect_ratio_options = [
'16:9', '4:3', '3:2', '1:1',
'2:3', '3:4', '9:16'
]
def __init__(self,
style='guofeng',
aspect_ratio='4:3'):
super().__init__()
if style in self.styles_option:
self.style = style
else:
raise ValueError(f'The style must be one of {self.styles_option}')
if aspect_ratio in self.aspect_ratio_options:
self.aspect_ratio = aspect_ratio
else:
raise ValueError(f'The aspect ratio must be one of {aspect_ratio}')
@tool_api
def generate_image(self, keywords: str) -> dict:
"""Run magicmaker and get the generated image according to the keywords.
Args:
keywords (:class:`str`): the keywords to generate image
Returns:
:class:`dict`: the generated image
* image (str): path to the generated image
"""
try:
response = requests.post(
url='https://magicmaker.openxlab.org.cn/gw/edit-anything/api/v1/bff/sd/generate',
data=json.dumps({
"official": True,
"prompt": keywords,
"style": self.style,
"poseT": False,
"aspectRatio": self.aspect_ratio
}),
headers={'content-type': 'application/json'}
)
except Exception as exc:
return ActionReturn(
errmsg=f'MagicMaker exception: {exc}',
state=ActionStatusCode.HTTP_ERROR)
image_url = response.json()['data']['imgUrl']
return {'image': image_url}
import json
import requests
from lagent.actions.base_action import BaseAction, tool_api
from lagent.actions.parser import BaseParser, JsonParser
from lagent.schema import ActionReturn, ActionStatusCode
class WeatherQuery(BaseAction):
adcode = '370102'
def __init__(self, adcode='370102'):
super().__init__()
self.adcode = adcode
@tool_api
def weather_query(self, keywords: str) -> dict:
"""Run weatherquery and get the weather information according to the keywords.
Args:
keywords (:class:`str`): the keywords to query weather information. such as address.
Returns:
:class:`dict`: the generated image
* image (str): path to the generated image
* province: the province of address
* city: the city of address
* adcode: city code of the address
* weather: weather detail information
* temperature: temperature of the address
* winddirection: wind's direction
* windpower: wind's power
* humidity: humidity information
* reporttime: report timestamp, example: 2024-08-15 16:01:03
* temperature_float: temperature informations with float. such as 30.0
* humidity_float: humidity information with float format. such as 63.0
"""
try:
# Use Address info to get adcode
url_get_address = 'https://restapi.amap.com/v3/geocode/geo?key=c7f6ae7c9a1bf1bc4ef72eaa36fc1d83&address=' + keywords
addr_rsp = requests.get(url=url_get_address)
adcode = addr_rsp.json()['geocodes'][0]['adcode']
# Query weather info with adcode
url_weather_query = 'https://restapi.amap.com/v3/weather/weatherInfo?key=c7f6ae7c9a1bf1bc4ef72eaa36fc1d83&city=' + adcode
response = requests.get(
url=url_weather_query
)
except Exception as exc:
return ActionReturn(
errmsg=f'WeatherQuery exception: {exc}',
state=ActionStatusCode.HTTP_ERROR)
result = response.json()['lives'][0]
return {'result': result}
4、然后修改internlm2_agent_web_demo.py,添加红框部分。
5、再启动webdemo后,测试成功