首页 > 其他分享 >D3-Lagent 智能体工具调用 Demo

D3-Lagent 智能体工具调用 Demo

时间:2024-01-04 22:32:48浏览次数:44  
标签:Demo st state session file action Lagent model D3

现在还是使用 InternStudio 中的 A100(1/4) 机器、InternLM-Chat-7B 模型和 Lagent 框架部署一个智能工具调用 Demo。

Lagent 是一个轻量级、开源的基于大语言模型的智能体(agent)框架,支持用户快速地将一个大语言模型转变为多种类型的智能体,并提供了一些典型工具为大语言模型赋能。通过 Lagent 框架可以更好的发挥 InternLM 的全部性能。

前面的环境准备与模型下载参考

                        https://blog.51cto.com/morcake/9105322

先给出项目结构图,其中包含这两次的内容:

D3-Lagent 智能体工具调用 Demo_Lagent


Lagent 安装

切换路径到 /root/code 克隆 lagent 仓库,并通过 pip install -e . 源码安装 Lagent

cd /root/code
git clone https://gitee.com/internlm/lagent.git
cd /root/code/lagent
git checkout 511b03889010c4811b1701abb153e02b8e94fb5e # 尽量保证和教程commit版本一致

D3-Lagent 智能体工具调用 Demo_Lagent_02

pip install -e . # 源码安装

D3-Lagent 智能体工具调用 Demo_人工智能_03

修改代码

直接将 /root/code/lagent/examples/react_web_demo.py 内容替换为以下代码:

import copy
import os

import streamlit as st
from streamlit.logger import get_logger

from lagent.actions import ActionExecutor, GoogleSearch, PythonInterpreter
from lagent.agents.react import ReAct
from lagent.llms import GPTAPI
from lagent.llms.huggingface import HFTransformerCasualLM


class SessionState:

    def init_state(self):
        """Initialize session state variables."""
        st.session_state['assistant'] = []
        st.session_state['user'] = []

        #action_list = [PythonInterpreter(), GoogleSearch()]
        action_list = [PythonInterpreter()]
        st.session_state['plugin_map'] = {
            action.name: action
            for action in action_list
        }
        st.session_state['model_map'] = {}
        st.session_state['model_selected'] = None
        st.session_state['plugin_actions'] = set()

    def clear_state(self):
        """Clear the existing session state."""
        st.session_state['assistant'] = []
        st.session_state['user'] = []
        st.session_state['model_selected'] = None
        if 'chatbot' in st.session_state:
            st.session_state['chatbot']._session_history = []


class StreamlitUI:

    def __init__(self, session_state: SessionState):
        self.init_streamlit()
        self.session_state = session_state

    def init_streamlit(self):
        """Initialize Streamlit's UI settings."""
        st.set_page_config(
            layout='wide',
            page_title='lagent-web',
            page_icon='./docs/imgs/lagent_icon.png')
        # st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')
        st.sidebar.title('模型控制')

    def setup_sidebar(self):
        """Setup the sidebar for model and plugin selection."""
        model_name = st.sidebar.selectbox(
            '模型选择:', options=['gpt-3.5-turbo','internlm'])
        if model_name != st.session_state['model_selected']:
            model = self.init_model(model_name)
            self.session_state.clear_state()
            st.session_state['model_selected'] = model_name
            if 'chatbot' in st.session_state:
                del st.session_state['chatbot']
        else:
            model = st.session_state['model_map'][model_name]

        plugin_name = st.sidebar.multiselect(
            '插件选择',
            options=list(st.session_state['plugin_map'].keys()),
            default=[list(st.session_state['plugin_map'].keys())[0]],
        )

        plugin_action = [
            st.session_state['plugin_map'][name] for name in plugin_name
        ]
        if 'chatbot' in st.session_state:
            st.session_state['chatbot']._action_executor = ActionExecutor(
                actions=plugin_action)
        if st.sidebar.button('清空对话', key='clear'):
            self.session_state.clear_state()
        uploaded_file = st.sidebar.file_uploader(
            '上传文件', type=['png', 'jpg', 'jpeg', 'mp4', 'mp3', 'wav'])
        return model_name, model, plugin_action, uploaded_file

    def init_model(self, option):
        """Initialize the model based on the selected option."""
        if option not in st.session_state['model_map']:
            if option.startswith('gpt'):
                st.session_state['model_map'][option] = GPTAPI(
                    model_type=option)
            else:
                st.session_state['model_map'][option] = HFTransformerCasualLM(
                    '/root/model/Shanghai_AI_Laboratory/internlm-chat-7b')
        return st.session_state['model_map'][option]

    def initialize_chatbot(self, model, plugin_action):
        """Initialize the chatbot with the given model and plugin actions."""
        return ReAct(
            llm=model, action_executor=ActionExecutor(actions=plugin_action))

    def render_user(self, prompt: str):
        with st.chat_message('user'):
            st.markdown(prompt)

    def render_assistant(self, agent_return):
        with st.chat_message('assistant'):
            for action in agent_return.actions:
                if (action):
                    self.render_action(action)
            st.markdown(agent_return.response)

    def render_action(self, action):
        with st.expander(action.type, expanded=True):
            st.markdown(
                "<p style='text-align: left;display:flex;'> <span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'>插    件</span><span style='width:14px;text-align:left;display:block;'>:</span><span style='flex:1;'>"  # noqa E501
                + action.type + '</span></p>',
                unsafe_allow_html=True)
            st.markdown(
                "<p style='text-align: left;display:flex;'> <span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'>思考步骤</span><span style='width:14px;text-align:left;display:block;'>:</span><span style='flex:1;'>"  # noqa E501
                + action.thought + '</span></p>',
                unsafe_allow_html=True)
            if (isinstance(action.args, dict) and 'text' in action.args):
                st.markdown(
                    "<p style='text-align: left;display:flex;'><span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'> 执行内容</span><span style='width:14px;text-align:left;display:block;'>:</span></p>",  # noqa E501
                    unsafe_allow_html=True)
                st.markdown(action.args['text'])
            self.render_action_results(action)

    def render_action_results(self, action):
        """Render the results of action, including text, images, videos, and
        audios."""
        if (isinstance(action.result, dict)):
            st.markdown(
                "<p style='text-align: left;display:flex;'><span style='font-size:14px;font-weight:600;width:70px;text-align-last: justify;'> 执行结果</span><span style='width:14px;text-align:left;display:block;'>:</span></p>",  # noqa E501
                unsafe_allow_html=True)
            if 'text' in action.result:
                st.markdown(
                    "<p style='text-align: left;'>" + action.result['text'] +
                    '</p>',
                    unsafe_allow_html=True)
            if 'image' in action.result:
                image_path = action.result['image']
                image_data = open(image_path, 'rb').read()
                st.image(image_data, caption='Generated Image')
            if 'video' in action.result:
                video_data = action.result['video']
                video_data = open(video_data, 'rb').read()
                st.video(video_data)
            if 'audio' in action.result:
                audio_data = action.result['audio']
                audio_data = open(audio_data, 'rb').read()
                st.audio(audio_data)


def main():
    logger = get_logger(__name__)
    # Initialize Streamlit UI and setup sidebar
    if 'ui' not in st.session_state:
        session_state = SessionState()
        session_state.init_state()
        st.session_state['ui'] = StreamlitUI(session_state)

    else:
        st.set_page_config(
            layout='wide',
            page_title='lagent-web',
            page_icon='./docs/imgs/lagent_icon.png')
        # st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')
    model_name, model, plugin_action, uploaded_file = st.session_state[
        'ui'].setup_sidebar()

    # Initialize chatbot if it is not already initialized
    # or if the model has changed
    if 'chatbot' not in st.session_state or model != st.session_state[
            'chatbot']._llm:
        st.session_state['chatbot'] = st.session_state[
            'ui'].initialize_chatbot(model, plugin_action)

    for prompt, agent_return in zip(st.session_state['user'],
                                    st.session_state['assistant']):
        st.session_state['ui'].render_user(prompt)
        st.session_state['ui'].render_assistant(agent_return)
    # User input form at the bottom (this part will be at the bottom)
    # with st.form(key='my_form', clear_on_submit=True):

    if user_input := st.chat_input(''):
        st.session_state['ui'].render_user(user_input)
        st.session_state['user'].append(user_input)
        # Add file uploader to sidebar
        if uploaded_file:
            file_bytes = uploaded_file.read()
            file_type = uploaded_file.type
            if 'image' in file_type:
                st.image(file_bytes, caption='Uploaded Image')
            elif 'video' in file_type:
                st.video(file_bytes, caption='Uploaded Video')
            elif 'audio' in file_type:
                st.audio(file_bytes, caption='Uploaded Audio')
            # Save the file to a temporary location and get the path
            file_path = os.path.join(root_dir, uploaded_file.name)
            with open(file_path, 'wb') as tmpfile:
                tmpfile.write(file_bytes)
            st.write(f'File saved at: {file_path}')
            user_input = '我上传了一个图像,路径为: {file_path}. {user_input}'.format(
                file_path=file_path, user_input=user_input)
        agent_return = st.session_state['chatbot'].chat(user_input)
        st.session_state['assistant'].append(copy.deepcopy(agent_return))
        logger.info(agent_return.inner_steps)
        st.session_state['ui'].render_assistant(agent_return)


if __name__ == '__main__':
    root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    root_dir = os.path.join(root_dir, 'tmp_dir')
    os.makedirs(root_dir, exist_ok=True)
    main()

Demo运行

D3-Lagent 智能体工具调用 Demo_开源_04

bash
conda activate internlm-demo  # 首次进入 vscode 会默认是 base 环境,所以首先切换环境
streamlit run /root/code/lagent/examples/react_web_demo.py --server.address 127.0.0.1 --server.port 6006

用同样的方法切换到 VScode 页面,运行成功后,配置本地端口映射,将端口映射到本地。在本地浏览器输入 http://127.0.0.1:6006 。

这里出现了问题:

D3-Lagent 智能体工具调用 Demo_人工智能_05

D3-Lagent 智能体工具调用 Demo_Lagent_06

分析原因,是环境的选择问题,当时使用

pip install -e .

通过源码安装时是 base 环境,而运行时是 internlm-demo 环境。

D3-Lagent 智能体工具调用 Demo_开源_07

D3-Lagent 智能体工具调用 Demo_人工智能_08

进入lagent-web

D3-Lagent 智能体工具调用 Demo_开源_09

在 Web 页面选择 InternLM 模型,等待模型加载完毕后,输入数学问题 已知 2x+5=9,求x ,此时 InternLM-Chat-7B 模型理解题意生成解此题的 Python 代码,Lagent 调度送入 Python 代码解释器求出该问题的解。

D3-Lagent 智能体工具调用 Demo_Lagent_10

D3-Lagent 智能体工具调用 Demo_Lagent_11

D3-Lagent 智能体工具调用 Demo_人工智能_12


标签:Demo,st,state,session,file,action,Lagent,model,D3
From: https://blog.51cto.com/morcake/9105636

相关文章

  • D2-InternLM-Chat-7B 智能对话 Demo
    使用InternStudio中的A100(1/4)机器和InternLM-Chat-7B模型部署一个智能对话Demo。一、环境准备进入 conda 环境:bash#请每次使用jupyterlab打开终端时务必先执行bash命令进入bash中使用以下命令从本地克隆一个已有的 pytorch2.0.1 的环境:condacreate--nameinte......
  • Linux驱动开发笔记(六):用户层与内核层进行数据传递的原理和Demo
    前言  驱动作为桥梁,用户层调用预定义名称的系统函数与系统内核交互,而用户层与系统层不能直接进行数据传递,进行本篇主要就是理解清楚驱动如何让用户编程来实现与内核的数据交互传递。<br>温故知新设备节点是应用层(用户层)与内核层交互;使用预先的结构体进行操作,如系统open函数......
  • 使用CMakeLists.txt创建一个动态库工程Demo给main程序使用
    主要需求是把hello程序编译动态库,再main程序或者第三方程序执行的时候动态加载。工程目录如下:$ls-al*-rw-r--r--1neuti197609352Oct2019:30CMakeLists.txtinclude:total1drwxr-xr-x1neuti1976090Oct2019:30./drwxr-xr-x1neuti1976090Oct201......
  • svelte的一些基础demo
    脚手架Vite:vite是集成了svelte,初始化的时候选择svelte就行了。npminitviteSvelteKit:底层基于vite的更上层框架,类似于nextjs。[email protected]文件结构和vue类似svelte文件是.svelte结尾的文件,比如demo.svelte......
  • 随机点名demo+文字特效
    上代码:一、HTML部分<div><h2>随机点名</h2><spanid="name"></span></div><buttonid="button-text">点一下不要钱</button>二、CSS部分*{margin:0;padd......
  • demo
    importReact,{useState,useEffect}from'react';import{Modal,Button,Form,Checkbox}from'antd';import{useForm}from'antd/lib/form/Form';interfaceResourceSelectProps{form:ReturnType<typeofuseForm>......
  • 003元素定位方式与项目demo创建
    一、环境搭建1、创建项目,添加java-client依赖包             新建maven项目,引入java-client依赖包       2、创建并编写代码 测试运行以上代码,运行前需打开Appnium.Appnium没有打开时,运行会报错:Connectionrefused:connect 二、......
  • gd32f4xx在IAR环境下创建工程后无法正常运行问题排查
        在创建移植工程时,我发现我需要创建一个基础环境,于是就顺手搭建了一个小的工程,简单到只有一个功能,就是运行systick,然后维护一个变量自加。结果发现,这个程序居然怎么都无法正常运行。       中断中的断点无法触发,变量不发生变化,我整个人都无语了,在网上查了很多......
  • openPlant实时数据库使用demo
    相关依赖由于没有com.magus.jdbc.jar依赖,需要手动下载防止lib下进行配置<dependency> <groupId>com.magus</groupId> <artifactId>jdbc</artifactId> <version>3.0</version> <scope>system</scope> <systemPath>${basedir}/lib/c......
  • des加密,url编码,url解码,des解密 DEMO
    des加密,url编码,url解码,des解密DEMOpackagecom.example.core.mydemo.des;importjavax.crypto.Cipher;importjavax.crypto.SecretKey;importjavax.crypto.SecretKeyFactory;importjavax.crypto.spec.DESKeySpec;importjava.net.URLDecoder;importjava.net.URLEncod......