GPT实战系列-ChatGLM3管理外部借力工具
用ChatGLM的工具可以实现很多查询接口和执行命令,外部工具该如何配置使用?如何联合它们实现大模型查询助手功能?例如调用工具实现股票信息查询,网络天气查询等助手功能。
LLM大模型相关文章:
GPT实战系列-ChatGLM3本地部署CUDA11+1080Ti+显卡24G实战方案
GPT实战系列-LangChain + ChatGLM3构建天气查询助手
GPT实战系列-大模型为我所用之借用ChatGLM3构建查询助手
配置tools信息
            
            
              python
              
              
            
          
          tools = [
	{'name': 'querystock', 
     'description': '查询指定股票的实时价格', 
     'parameters': 
     	{'type': 'object', 
         'properties': 
         	{
               'symbol': {'description': '需要查询的股票代码'}
            }, 
         'required': []
        }
    }, 
]参数解释:
"name":为配置tool工具名;
"description":对工具的描述;
"parameters":
        "type":数据类型默认为"object";
    
        "properties":在此定义工具的属性以及对属性值的描述;
    
        "required": 需要返回的属性;系统描述接口调用
            
            
              python
              
              
            
          
          system_item = {"role": "system",
               "content": "Answer the following questions as best as you can. You have access to the following tools:",
               "tools": tools}程序中调用语句以便实现工具调用
            
            
              python
              
              
            
          
          tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH, trust_remote_code=True)
model = AutoModel.from_pretrained(MODEL_PATH, trust_remote_code=True, device_map="auto").eval()
past_key_values, history = None, [system_item]调用模型时,当对话query和tool相关时,模型会自动调用tool并反馈:
            
            
              python
              
              
            
          
          query = "帮我查询股票sz000001的价格"
response, history = model.chat(tokenizer, query, history=history)
print(response)期望调用工具得到输出为:
            
            
              json
              
              
            
          
          {"name": "querystock", "parameters": {"symbol": "sz000001"}}这表示模型需要调用工具 querystock,并且需要传入参数 symbol。
调用工具,生成回复
此时需要自行实现调用工具的逻辑。假设已经得到返回结果,将结果以 json 格式返回给模型并得到回复。
            
            
              python
              
              
            
          
          result = json.dumps({"price": 9.270}, ensure_ascii=False)
response, history = model.chat(tokenizer, result, history=history, role="observation")
print(response)这里 role="observation" 表示输入的是工具调用的返回值而不是用户输入,不能省略。
经LLM整理信息后,期望得到的输出为
根据您的查询,经过API的调用,股票 sz000001 的价格是 9.270。表示本次工具调用已经结束,模型根据返回结果生成回复。
可以根据返回的 response 是 str 还是 dict 来判断返回的是生成的回复还是工具调用请求。
觉得有用 收藏 收藏 收藏
点个赞 点个赞 点个赞
End
GPT专栏文章:
GPT实战系列-ChatGLM3本地部署CUDA11+1080Ti+显卡24G实战方案
GPT实战系列-LangChain + ChatGLM3构建天气查询助手
GPT实战系列-大模型为我所用之借用ChatGLM3构建查询助手
GPT实战系列-P-Tuning本地化训练ChatGLM2等LLM模型,到底做了什么?(二)
GPT实战系列-P-Tuning本地化训练ChatGLM2等LLM模型,到底做了什么?(一)
GPT实战系列-ChatGLM2部署Ubuntu+Cuda11+显存24G实战方案