赞
踩
目录
ChatGLM3-6B目前有三种使用模式:
函数调用模式示例:
函数调用模式介绍:
进入conda对应的环境
conda activate chatglm
进入composite_demo目录
cd composite_demo
修改为使用本地模型,参考LLM大语言模型(一):ChatGLM3-6B本地部署-CSDN博客
- # 修改client.py
- MODEL_PATH = os.environ.get('MODEL_PATH', '====你的本地模型的绝对路径====')
启动模型
- # 在composite_demo目录下
- streamlit run main.py
然后在页面选择Tool模式即可。
首先我们看下get_weather函数是如何实现的。
在composite_demo目录下有个tool_registry.py文件,里面包含两个已经定义好的函数:
random_number_generator
get_weather
其中get_weather就是上文对话中用到的函数。
- @register_tool
- def get_weather(
- city_name: Annotated[str, 'The name of the city to be queried', True],
- ) -> str:
- """
- Get the current weather for `city_name`
- """
-
- if not isinstance(city_name, str):
- raise TypeError("City name must be a string")
-
- key_selection = {
- "current_condition": ["temp_C", "FeelsLikeC", "humidity", "weatherDesc", "observation_time"],
- }
- import requests
- try:
- resp = requests.get(f"https://wttr.in/{city_name}?format=j1")
- resp.raise_for_status()
- resp = resp.json()
- ret = {k: {_v: resp[k][0][_v] for _v in v} for k, v in key_selection.items()}
- except:
- import traceback
- ret = "Error encountered while fetching weather data!\n" + traceback.format_exc()
-
- return str(ret)
get_weather功能很简洁,最终是从
https://wttr.in/{city_name}?format=j1
获取天气信息(https://wttr.in/%E5%8C%97%E4%BA%AC?format=j1)
register_tool的功能是将自定义的函数,转化为大模型需要的格式。
- def register_tool(func: callable):
- tool_name = func.__name__
- tool_description = inspect.getdoc(func).strip()
- python_params = inspect.signature(func).parameters
- tool_params = []
-
- # 解析param的Annotation
-
- for name, param in python_params.items():
- annotation = param.annotation
- if annotation is inspect.Parameter.empty:
- raise TypeError(f"Parameter `{name}` missing type annotation")
- if get_origin(annotation) != Annotated:
- raise TypeError(f"Annotation type for `{name}` must be typing.Annotated")
-
- typ, (description, required) = annotation.__origin__, annotation.__metadata__
- typ: str = str(typ) if isinstance(typ, GenericAlias) else typ.__name__
- if not isinstance(description, str):
- raise TypeError(f"Description for `{name}` must be a string")
- if not isinstance(required, bool):
- raise TypeError(f"Required for `{name}` must be a bool")
-
- tool_params.append({
- "name": name,
- "description": description,
- "type": typ,
- "required": required
- })
- tool_def = {
- "name": tool_name,
- "description": tool_description,
- "params": tool_params
- }
-
- print("[registered tool] " + pformat(tool_def))
- _TOOL_HOOKS[tool_name] = func
- _TOOL_DESCRIPTIONS[tool_name] = tool_def
-
- return func
register_tool函数实现了装饰器,它将自定义的函数转换为tool_def dict,其中自动生成了name,description,params等信息
- {
- 'name': 'get_weather',
- 'description': 'Get the current weather for `city_name`',
- 'params': [
- {
- 'name': 'city_name',
- 'description': 'The name of the city to be queried',
- 'type': 'str',
- 'required': True
- }
- ]
- }
最终通过get_tools()将自定义的函数都暴露出去。
在上述demo中,其实是demo_tool.py里调用了get_tools()获取到所有的自定义函数。
-
- def get_tools() -> dict:
- return copy.deepcopy(_TOOL_DESCRIPTIONS)
-
- @register_tool
- def kuakuawo(
- name: Annotated[str, 'The name of the user', True],
- ) -> str:
- """
- Generates a awesome praise for user
- """
-
- return f"{name} 你真的太棒了"
看看效果
参考:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。