NLP - LLM - function calling实现
一、function calling介绍
大型模型如 GPT-4 被设计为能够与外部系统交互,比如通过 API 调用执行某些任务。例如,一个大型模型可能被编程为在需要时调用外部数据库查询函数、调用图像处理服务或执行其他外部功能。
二、chatglm3 function calling实现
import json
import requests
from transformers import AutoTokenizer, AutoModel, AutoConfig
model_path = "/code/ZhipuAI/chatglm3-6b"
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModel.from_pretrained(model_path, trust_remote_code=True).half().to("cuda:0")
def get_weather(loc):
if loc == "北京" or loc == "beijing":
return {"北京": "35"}
else:
return {"other": "25"}
weather_api_spec = [
{
'name': 'get_weather',
'description': '输入城市名称,查询即时天气函数。',
'parameters': {
'type': 'object',
'properties': {
'loc': {
'description': '城市名称,中国城市要用对应城市的英文名称。',
'type': 'string',
'required': True
}
}
}
}
]
# 设定LLM身份
system_info = {
"role": "system",
"content": "尽可能最好地回答以下问题。你可以访问以下工具:",
"tools": weather_api_spec
}
# 第一次调用LLM
prompt = "请问今天北京天气如何"
first_response, his = model.chat(tokenizer, prompt, history=[system_info])
print(first_response)
# 调用api
function_name = first_response.get("name")
parameters = first_response.get("parameters")
api_response = eval(f"{function_name}(**{parameters})")
print(api_response)
# 第二次调用LLM
prompt = {
"role": "observation", # 角色为observation,表示为外部函数发的消息
"name": function_name,
"content": api_response
}
final_response, his = model.chat(tokenizer, str(prompt), history=his)
print(final_response)