当前位置:   article > 正文

LLM - Qwen functioncalling 预测与训练_qwen - function calling

qwen - function calling
微信公众号:NLP万事通

环境准备

  • 本文使用cuda11.8,使用的python包如下
  1. transformers==4.39.0
  2. torch==2.0.1
  3. deepspeed==0.14.4

主要代码

  1. 模型加载
  1. from transformers import AutoModelForCausalLM, AutoTokenizer
  2. from tqdm import tqdm
  3. device = "cuda"
  4. # 加载模型
  5. model = AutoModelForCausalLM.from_pretrained(
  6. "Qwen2-7B-Instruct",
  7. torch_dtype="auto",
  8. device_map="auto"
  9. )
  10. # 加载tokenizer
  11. tokenizer = AutoTokenizer.from_pretrained("Qwen2-7B-Instruct")

2.封装调用qwen2的方法,支持输入user_prompt 或 ReAct模版

  1. def get_model_result(prompt, messages=None):
  2. if 'im' not in prompt:
  3. if messages is None:
  4. messages = [
  5. {"role": "system", "content": "You are a helpful assistant."},
  6. {"role": "user", "content": prompt}
  7. ]
  8. text = tokenizer.apply_chat_template(
  9. messages,
  10. tokenize=False,
  11. add_generation_prompt=True
  12. )
  13. else:
  14. text = prompt
  15. print("text", text)
  16. model_inputs = tokenizer([text], return_tensors="pt").to(device)
  17. generated_ids1 = model.generate(
  18. model_inputs.input_ids,
  19. max_new_tokens=512
  20. )
  21. generated_ids = [
  22. output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids1)
  23. ]
  24. response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
  25. return response

tokenizer.apply_chat_template 方法可以直接生成模版

  1. <|im_start|>system
  2. You are a helpful assistant.<|im_end|>
  3. <|im_start|>user
  4. 介绍下中国<|im_end|>
  5. <|im_start|>assistant

想生成ReAct模版,需要使用openai的接口传入Function,由于vllm部署原因,本文我们自己构建

2.1 测试

response = get_model_result("介绍下中国")

response

  1. 中国,全称为中华人民共和国,是一个位于亚洲东部、太平洋西岸的国家。以下是关于中国的几个重要方面:
  2. 1. **地理**:中国领土面积约为960万平方公里,仅次于俄罗斯和加拿大,是世界上第三大国家。它东临太平洋,与日本、韩国、朝鲜等国隔海相望;北与蒙古接壤,东北与俄罗斯相邻;西北部与哈萨克斯坦、吉尔吉斯斯坦、塔吉克斯坦、阿富汗、巴基斯坦等国为邻;西南部与印度、尼泊尔、不丹、缅甸、老挝、越南等国相邻。中国地形复杂多样,包括高原、平原、山地、丘陵和盆地等多种地貌。
  3. 2. **人口**:截至2023年,中国的人口总数超过14亿,是世界上人口最多的国家。人口分布不均,主要集中在东部沿海地区。
  4. 3. **文化**:中国文化源远流长,拥有超过5000年的历史,深受儒家、道家、佛教等哲学思想的影响。中国有着丰富的文化遗产,包括长城、故宫、兵马俑等世界著名的历史遗迹。此外,中国的文学、艺术、音乐、书法等领域也成就显著,对中国乃至世界文化产生了深远影响。
  5. 4. **经济**:改革开放以来,中国经济实现了快速增长,成为全球第二大经济体。中国是世界上最大的制造业国家之一,同时也是农产品生产大国。近年来,服务业在中国经济中的比重持续上升,成为经济增长的重要驱动力。中国还是世界上最大的出口国之一,并在科技创新、基础设施建设等方面取得了显著成就。
  6. 5. **政治**:中国实行社会主义制度,由共产党领导的多党合作和政治协商制度是中国特色的政治体制。中华人民共和国主席、国务院总理等高级官员由全国人民代表大会选举产生。中国坚持走和平发展道路,致力于维护世界和平、促进共同发展。
  7. 6. **社会**:中国在教育、医疗、科技、环保等领域不断进步,同时也在努力解决贫困问题,推动城乡一体化发展,提高人民生活水平。随着城镇化进程加快,城市化进程显著,但同时也面临诸如环境污染、交通拥堵等问题。
  8. 7. **国际地位**:作为联合国安理会常任理事国之一,中国在国际事务中发挥着重要作用。中国积极参与全球治理,推动构建人类命运共同体,倡导多边主义,促进国际合作与发展。

3.定义两个function,查询和操作数据库

  1. """
  2. 用JSON格式模拟数据库
  3. """
  4. class CourseDatabase:
  5. def __init__(self):
  6. self.database = {
  7. "大模型技术实战":{
  8. "课时": 200,
  9. "每周更新次数": 3,
  10. "每次更新小时": 2
  11. },
  12. "机器学习实战":{
  13. "课时": 230,
  14. "每周更新次数": 2,
  15. "每次更新小时": 1.5
  16. },
  17. "深度学习实战":{
  18. "课时": 150,
  19. "每周更新次数": 1,
  20. "每次更新小时": 3
  21. },
  22. "AI数据分析":{
  23. "课时": 10,
  24. "每周更新次数": 1,
  25. "每次更新小时": 1
  26. },
  27. }
  28. def course_query(self, course_name):
  29. return self.database.get(course_name, "目前没有该课程信息")
  30. """
  31. 定义数据库操作工具
  32. """
  33. class CourseOperations:
  34. def __init__(self):
  35. self.db = CourseDatabase()
  36. def add_hours_to_course(self, param):
  37. course_name = param.get("course_name", "None")
  38. additional_hours = int(param.get("additional_hours", "None"))
  39. if course_name in self.db.database:
  40. self.db.database[course_name]['课时'] += additional_hours
  41. return f"课程 {course_name} 的课时已增加{additional_hours}小时。"
  42. else:
  43. return "课程不存在,无法添加课时"

3.1 function测试

  1. course_ops = CourseOperations()
  2. # 给某个课程增加课时
  3. course_insert_test = course_ops.add_hours_to_course({"course_name": "大模型技术实战", "additional_hours":20 })

course_insert_test

课程 大模型技术实战 的课时已增加20小时。

3.2 定义大模型需要调用的工具库

  • 这是Qwen风格的function格式,需要严格按照此格式,否则后续容易报错
  1. TOOLS = [
  2. {
  3. 'name_for_human': '课程信息数据库',
  4. 'name_for_model': 'CourseDatabase',
  5. 'description_for_model': '课程信息数据库存储有各课程的详细信息,包括目前的上线课时,每周更新次数以及每次更新的小时数。通过输入课程名称,可以返回该课程的详细信息。',
  6. 'parameters': [{
  7. 'name': 'course_query',
  8. 'description': '课程名称,所需查询信息的课程名称',
  9. 'required': True,
  10. 'schema': {
  11. 'type': 'string'
  12. },
  13. }],
  14. },
  15. {
  16. 'name_for_human': '课程操作工具',
  17. 'name_for_model': 'CourseOperations',
  18. 'description_for_model': '课程操作工具提供了对课程信息的添加操作,可以添加课程的详细信息,如每周更新次数,更新课时',
  19. 'parameters': [{
  20. 'name': 'add_hours_to_course',
  21. 'description': '给指定的课程增加课时,需要课程名称和增加的课时数',
  22. 'required': True,
  23. 'schema': {
  24. 'type': 'string',
  25. 'properties': {
  26. 'course_name': {'type': 'string'},
  27. 'additional_hours': {'type': 'string'}
  28. },
  29. 'required': ['course_name', 'additional_hours']
  30. },
  31. }],
  32. },
  33. # 其他工具的定义可以在这里继续添加
  34. ]

3.3 将一个插件的关键信息拼接成一段文本的模板

  1. TOOL_DESC = """{name_for_model}: Call this tool to interact with the {name_for_human} API. What is the {name_for_human} API useful for? {description_for_model} Parameters:{parameters}
  2. """
  3. PROMPT_REACT = """
  4. <|im_start|>system
  5. You are a helpful assistant.<|im_end|>
  6. <|im_start|>user
  7. Answer the following questions as best you con. You have access to the following
  8. {tool_descs}
  9. Use the following format:
  10. Question: the input question you must answer
  11. Thought: you should always think about what to do
  12. Action: the action to take, should be one of [{tool_names}]
  13. Action Input: the input to the action
  14. Observation: the result of the action
  15. ... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
  16. Thought: I now know the final answer
  17. Final Answer: the final answer to the original input question
  18. Begin!
  19. Question: {query}<|im_end|>
  20. <|im_start|>assistant
  21. """

4 生成function描述的方法

  1. import json
  2. def generate_action_prompt(query):
  3. """
  4. 根据用户查询生成最终的动作提示字符串。
  5. 函数内部直接引用全局变量 TOOLS, TOOL_DESC, 和 PROMPT_REACT.
  6. 参数:
  7. - query: 用户的查询字符串。
  8. 返回:
  9. - action_prompt: 格式化后的动作提示字符串。
  10. """
  11. tool_descs = []
  12. tool_names = []
  13. for info in TOOLS:
  14. tool_descs.append(
  15. TOOL_DESC.format(
  16. name_for_model = info['name_for_model'],
  17. name_for_human = info['name_for_human'],
  18. description_for_model = info['description_for_model'],
  19. parameters = json.dumps(info['parameters'], ensure_ascii=False),
  20. )
  21. )
  22. tool_names.append(info['name_for_model'])
  23. tool_descs_str = '\\n\\n'.join(tool_descs)
  24. tool_names_str = ','.join(tool_names)
  25. action_prompt = PROMPT_REACT.format(tool_descs=tool_descs_str, tool_names=tool_names_str, query=query)
  26. return action_prompt

4.1 测试function描述生成

  1. query = "先帮我查询一下大模型技术实战这个课程目前更新了多少节,今晚我直播了一节新课,请你帮我更新一下"
  2. prompt = generate_action_prompt(query)

prompt

  1. """
  2. <|im_start|>system
  3. You are a helpful assistant.<|im_end|>
  4. <|im_start|>user
  5. Answer the following questions as best you con. You have access to the following
  6. CourseDatabase: Call this tool to interact with the 课程信息数据库 API. What is the 课程信息数据库 API useful for? 课程信息数据库存储有各课程的详细信息,包括目前的上线课时,每周更新次数以及每次更新的小时数。通过输入课程名称,可以返回该课程的详细信息。 Parameters:[{"name": "course_query", "description": "课程名称,所需查询信息的课程名称", "required": true, "schema": {"type": "string"}}]
  7. CourseOperations: Call this tool to interact with the 课程操作工具 API. What is the 课程操作工具 API useful for? 课程操作工具提供了对课程信息的添加操作,可以添加课程的详细信息,如每周更新次数,更新课时 Parameters:[{"name": "add_hours_to_course", "description": "给指定的课程增加课时,需要课程名称和增加的课时数", "required": true, "schema": {"type": "string", "properties": {"course_name": {"type": "string"}, "additional_hours": {"type": "string"}}, "required": ["course_name", "additional_hours"]}}]
  8. Use the following format:
  9. Question: the input question you must answer
  10. Thought: you should always think about what to do
  11. Action: the action to take, should be one of [CourseDatabase,CourseOperations]
  12. Action Input: the input to the action
  13. Observation: the result of the action
  14. ... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
  15. Thought: I now know the final answer
  16. Final Answer: the final answer to the original input question
  17. Begin!
  18. Question: 先帮我查询一下大模型技术实战这个课程目前更新了多少节,今晚我直播了一节新课,请你帮我更新一下<|im_end|>
  19. <|im_start|>assistant
  20. """

5 todo: 插入stopwords,Qwen会在Observation之后出现幻觉,希望在Observation处停止,去调用call。

  • 用vllm调用可以传入stop_words,但是cuda11.8没有安装成功,这里直接去掉Observation后的内容
  1. custom_stop_words = ["Observation:", "Observation:\\n", "..."]
  2. stop_words_ids = [tokenizer.add_tokens([word]) for word in custom_stop_words]
  3. encoded_word = [tokenizer.encode(word, add_special_tokens=False) for word in custom_stop_words]
  4. encoded_stop_words_ids = sum(encoded_word, [])

encoded_stop_words_ids

[151646, 151647, 1112]

6 加入ReAct的prompt请求Qwen模型

response = get_model_result(prompt)

response

  1. Thought: 需要使用CourseDatabase API查询课程信息,并使用CourseOperations API更新课程信息。
  2. Action: CourseDatabase
  3. Action Input: {"course_query": "大模型技术实战"}
  4. Observation:

6.1 解析模型的ReAct输出文本提取名称及其参数。

  1. def parse_plugin_action(text: str):
  2. """
  3. 解析模型的ReAct输出文本提取名称及其参数。
  4. 参数:
  5. - text: 模型ReAct提示的输出文本
  6. 返回值:
  7. - action_name: 要调用的动作(方法)名称。
  8. - action_arguments: 动作(方法)的参数。
  9. """
  10. # 查找“Action:”和“Action Input:”的最后出现位置
  11. action_index = text.find('\\nAction:')
  12. action_input_index = text.find('\\nAction Input:')
  13. observation_index = text.find('\\nObservation:')
  14. # 如果文本中有“Action:”和“Action Input:”
  15. if 0 <= action_index < action_input_index:
  16. if observation_index < action_input_index:
  17. text = text.rstrip() + '\\nObservation:'
  18. observation_index = text.rfind('\\nObservation:')
  19. # 确保文本中同时存在“Action:”和“Action Input:”
  20. if 0 <= action_index < action_input_index < observation_index:
  21. # 提取“Action:”和“Action Input:”之间的文本为动作名称
  22. action_name = text[action_index + len('\\nAction:'):action_input_index].strip()
  23. # 提取“Action Input:”之后的文本为动作参数
  24. action_arguments = text[action_input_index + len('\\nAction Input:'):observation_index].strip()
  25. return action_name, action_arguments
  26. # 如果没有找到符合条件的文本,返回空字符串
  27. return '', ''

6.2 根据模型的ReAct输出执行相应的插件调用,并返回调用结果。

  1. import json
  2. import ipdb
  3. def execute_plugin_from_react_output(response):
  4. """
  5. 根据模型的ReAct输出执行相应的插件调用,并返回调用结果。
  6. 参数:
  7. - response: 模型的ReAct输出字符串。
  8. 返回:
  9. - result_dict: 包括状态码和插件调用结果的字典。
  10. """
  11. # 从模型的ReAct输出中提取函数名称及函数入参
  12. # ipdb.set_trace()
  13. plugin_configuration = parse_plugin_action(response)
  14. first_config_line = plugin_configuration[1:][0].split('\\n')[0]
  15. config_parameters = json.loads(first_config_line)
  16. result_dict = {"status_code": 200}
  17. for k, v in config_parameters.items():
  18. for TOOL in TOOLS:
  19. if k in TOOL["parameters"][0]['name']:
  20. # 通过eval函数执行存储在字符串中的python表达式,并返回表达式计算结果。其执行过程实质上是实例化类
  21. tool_instance = eval(TOOL["name_for_model"])()
  22. # 然后通过getattr函数传递对象和字符串形式的属性或方法名来动态的访问该属性和方法h
  23. tool_func = getattr(tool_instance, k)
  24. # 这一步实际上执行的过程就是:course_db,course_query('大模型技术实战')
  25. tool_result = tool_func(v)
  26. result_dict["result"] = tool_result
  27. return result_dict
  28. result_dict["status_code"] = 404
  29. result_dict["result"] = "未找到匹配的插件配置"
  30. return result_dict
  31. -------------------------------------------------
  32. 测试:
  33. tool_result = execute_plugin_from_react_output(response)
  34. print(tool_result)
  35. output:
  36. {'status_code': 200, 'result': {'课时': 200, '每周更新次数': 3, '每次更新小时': 2}}

6.2.1 调用function测试

tool_result = execute_plugin_from_react_output(response)

tool_result

{'status_code': 200, 'result': {'课时': 200, '每周更新次数': 3, '每次更新小时': 2}}

6.3 生成新的prompt

  1. response = response + " " + str(tool_result)
  2. prompt = prompt + "\\n" + response

prompt

  1. <|im_start|>system
  2. You are a helpful assistant.<|im_end|>
  3. <|im_start|>user
  4. Answer the following questions as best you con. You have access to the following
  5. CourseDatabase: Call this tool to interact with the 课程信息数据库 API. What is the 课程信息数据库 API useful for? 课程信息数据库存储有各课程的详细信息,包括目前的上线课时,每周更新次数以及每次更新的小时数。通过输入课程名称,可以返回该课程的详细信息。 Parameters:[{"name": "course_query", "description": "课程名称,所需查询信息的课程名称", "required": true, "schema": {"type": "string"}}]
  6. CourseOperations: Call this tool to interact with the 课程操作工具 API. What is the 课程操作工具 API useful for? 课程操作工具提供了对课程信息的添加操作,可以添加课程的详细信息,如每周更新次数,更新课时 Parameters:[{"name": "add_hours_to_course", "description": "给指定的课程增加课时,需要课程名称和增加的课时数", "required": true, "schema": {"type": "string", "properties": {"course_name": {"type": "string"}, "additional_hours": {"type": "string"}}, "required": ["course_name", "additional_hours"]}}]
  7. Use the following format:
  8. Question: the input question you must answer
  9. Thought: you should always think about what to do
  10. Action: the action to take, should be one of [CourseDatabase,CourseOperations]
  11. Action Input: the input to the action
  12. Observation: the result of the action
  13. ... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
  14. Thought: I now know the final answer
  15. Final Answer: the final answer to the original input question
  16. Begin!
  17. Question: 先帮我查询一下大模型技术实战这个课程目前更新了多少节,今晚我直播了一节新课,请你帮我更新一下<|im_end|>
  18. <|im_start|>assistant
  19. Thought: 需要使用 CourseDatabase API 查询课程信息,然后使用 CourseOperations API 更新课程信息。
  20. Action: CourseDatabase
  21. Action Input: {"course_query": "大模型技术实战"}
  22. Observation: {'status_code': 200, 'result': {'课时': 200, '每周更新次数': 3, '每次更新小时': 2}}

6.4 再次请求Qwen

response = get_model_result(prompt)

response

  1. Thought: 课程当前更新了200节,每周更新3次,每次更新2小时。
  2. Action: CourseOperations
  3. Action Input: {"add_hours_to_course": {"course_name": "大模型技术实战", "additional_hours": "1"}}
  4. Observation:

6.5 请求function

tool_result = execute_plugin_from_react_output(response)

tool_result

{'status_code': 200, 'result': '课程 大模型技术实战的课时已增加1小时。'

6.6 再次请求Qwen

  1. response = response + " " + str(tool_result)
  2. prompt = prompt + "\\n" + response
  3. response = get_model_result(prompt)

response

  1. Thought: 已成功更新课程“大模型技术实战”的课时。
  2. Final Answer: 大模型技术实战这个课程目前更新了201节。您今晚直播的新课已经成功更新到课程中。

最后将Final Answer:后面的内容提取出来回复给用户作为输出

结论

      至此,我们已经知道了ReAct的构造方式及function的调度流程。Function的训练数据也同样遵循ReAct模版的构建方式,至于,和chatML模版的配比需要小伙伴自己尝试。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/988879
推荐阅读
相关标签
  

闽ICP备14008679号