LLM智能体开发指南

除非你一直生活在岩石下,否则你一定听说过像 Auto-GPT 和 MetaGPT 这样的项目。 这些是社区为使 GPT-4 完全自治而做出的尝试。在其最原始的形式中,代理基本上是文本到任务。你输入一个任务描述,比如“给我做一个贪吃蛇游戏”,并使用LLM作为它的大脑和一些围绕它构建的工具,你就得到了自己的贪吃蛇游戏! 看,连我也做了一个!

image.png

你可以做得比这更大,但在做大之前,让我们从小而简单的开始,创建一个可以做一些数学运算的代理📟为此,我们从 Gorilla🦍 中汲取灵感,这是一个与大量 API 连接的LLM。

首先,我们选择LLM并创建一个数据集。

在本教程中,我们将使用 meta-llama/Llama-2–7b-chat-hf 模型和 rohanbalkondekar/generate_json 数据集。代码可以从这里访问。

是的,有一种更好的数学方法,例如通过使用 py-expression-eval 使用 JavaScript 的 eval 函数来进行数学表达式,但我将使用这种类似于 API 调用中的有效负载的格式,尽管如此,它只是简单的 add( a,b) 函数或在本例中为 add(8945, 1352) :

{ "function_name": "add", "parameter_1": "8945", "parameter_2": "1352" }

微调就像对现有项目进行更改,而不是从头开始开发所有内容。 这就是为什么我们使用 Llama-2-7b-chat 模型而不仅仅是预先训练的模型 Llama-2–7b,这会让我们的事情变得更容易。 如果我们使用 Llama-2-chat,我们必须使用以下提示格式:

<s>[INST] <<SYS>>
{{ system_prompt }}
<</SYS>>{{ user_message }} [/INST]

你还可以使用较小的模型(例如 microsoft/phi-1.5)来执行简单任务,或者像我一样 GPU 不足。

由于 Microsoft 仅发布了预训练模型,因此你可以使用社区发布的微调模型,例如 openaccess-ai-collective/phi-platypus-qlora 或 teknium/Puffin-Phi-v2 。

对于 teknium/Puffin-Phi-v2,提示模板为:

USER: <prompt>
ASSISTANT:

现在,我们遇到了一个问题,有如此多的模型,如 llama、phi、mistral、falcon 等,你不能只将模型名称更改为 model_path = "microsoft/phi-1.5" 并期望一切正常。

如果有一个工具可以做到这一点是不是很棒?这就是 axolotl !

###Installationgit clone https://github.com/OpenAccess-AI-Collective/axolotl
cd axolotlpip3 install packaging
pip3 install -e '.[flash-attn,deepspeed]'
pip3 install -U git+https://github.com/huggingface/peft.git

有时安装axolotl可能会很棘手。确保

  • CUDA > 11.7
  • Python >=3.9
  • Pytorch >=2.0
  • PyTorch 版本与 Cuda 版本匹配
  • 创建新的虚拟环境或docker

这里我们使用以下数据集:rohanbalkondekar/maths_function_calls

下载或创建名为“maths_function_calls.jsonl”的文件,然后复制并粘贴上述链接中的内容。

然后从示例文件夹中复制现有模型的 .yml 文件,并根据需要更改参数。

或者创建一个全新的 .yml 文件,例如 phi-finetune.yml,其配置如下:

base_model: teknium/Puffin-Phi-v2
base_model_config: teknium/Puffin-Phi-v2
model_type: AutoModelForCausalLM
tokenizer_type: AutoTokenizer
is_llama_derived_model: false
trust_remote_code: trueload_in_8bit: false
load_in_4bit: true
strict: falsedatasets:- path: maths_function_calls.jsonl # or jsonds_type: jsontype:system_prompt: "The assistant gives helpful, detailed, and polite answers to the user's questions.\n"no_input_format: |-USER: {instruction}<|endoftext|>ASSISTANT:format: |-USER: {instruction}{input}<|endoftext|>ASSISTANT:dataset_prepared_path: last_run_prepared
val_set_size: 0.05
output_dir: ./phi-finetunedsequence_len: 1024
sample_packing: false  # not CURRENTLY compatible with LoRAs
pad_to_sequence_len:adapter: qlora
lora_model_dir:
lora_r: 64
lora_alpha: 32
lora_dropout: 0.05
lora_target_linear: true
lora_fan_in_fan_out:wandb_project:
wandb_entity:
wandb_watch:
wandb_run_id:
wandb_log_model:gradient_accumulation_steps: 1
micro_batch_size: 1
num_epochs: 50
optimizer: adamw_torch
adam_beta2: 0.95
adam_epsilon: 0.00001
max_grad_norm: 1.0
lr_scheduler: cosine
learning_rate: 0.000003train_on_inputs: false
group_by_length: true
bf16: true
fp16: false
tf32: truegradient_checkpointing:
early_stopping_patience:
resume_from_checkpoint:
local_rank:
logging_steps: 1
xformers_attention:
flash_attention:warmup_steps: 100
eval_steps: 0.05
save_steps:
debug:
deepspeed:
weight_decay: 0.1
fsdp:
fsdp_config:
resize_token_embeddings_to_32x: true
special_tokens:bos_token: "<|endoftext|>"eos_token: "<|endoftext|>"unk_token: "<|endoftext|>"pad_token: "<|endoftext|>"

使用以下命令开始微调:

accelerate launch -m axolotl.cli.train phi-finetune.yml

你将开始收到这样的日志,这意味着微调正在进行中。

{'loss': 0.0029, 'learning_rate': 1.7445271850805345e-07, 'epoch': 20.44}                                      85%|███████████████████████████████████████████████████████████▌          | 1942/2280 [06:13<01:14,  4.51it/s]`attention_mask` is not supported during training. Using it might lead to unexpected results.

微调完成后,会得到一个新目录 phi-finetuned。现在,使用以下命令开始推断微调模型。

accelerate launch -m axolotl.cli.inference phi-ft.yml --lora_model_dir="./phi-finetuned"

现在,按照自定义提示模板,如果输入:

The assistant gives helpful, detailed, and polite answers to the user's questions.
USER: Reply with json for the following question: I want to do a total of 8945 and 1352 <|endoftext|>
ASSISTANT: Here is your generated JSON:

你应该收到以下输出:

The assistant gives helpful, detailed, and polite answers to the user's questions.
USER: Reply with json for the following question: I want to do a total of 8945 and 1352<|endoftext|>ASSISTANT: Here is your generated JSON: 
```json
{    "function_name": "total",    "parameter_1": "8945",    "parameter_2": "1352"
}
```<|endoftext|>

现在,你可以轻松地从输出中提取 json,并可以进行函数调用来显示计算的输出。 (微调 llama2 的示例:链接)

这是开始推断微调模型的基本代码:

import torch
from transformers import AutoModelForCausalLM, AutoTokenizermodel_path = "phi-finetuned"  #or "mistralai/Mistral-7B-Instruct-v0.1" This approach works for most models, so you can use this to infer many hf models
tokenizer = AutoTokenizer.from_pretrained(model_path)model = AutoModelForCausalLM.from_pretrained(model_path,torch_dtype=torch.float16,load_in_4bit=True,  trust_remote_code=True,device_map="auto", 
)while True:prompt = input("Enter Prompt: ")input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to("cuda")gen_tokens = model.generate(input_ids, do_sample=True, max_length=100)generated_text = tokenizer.batch_decode(gen_tokens)[0]print(generated_text)

下面的代码格式化输入并提取 JSON:

import re
import math
import json
import torch
from transformers import (AutoModelForCausalLM,AutoTokenizer,
)# Path to saved model
model_path = "phi-ft-5"
tokenizer = AutoTokenizer.from_pretrained(model_path)# Load model
model = AutoModelForCausalLM.from_pretrained(model_path,torch_dtype=torch.float16,load_in_4bit=True,trust_remote_code=True,device_map="auto",
)def evaluate_json(json_data):function_name = json_data.get("function_name")parameter_1 = float(json_data.get("parameter_1", 0))parameter_2 = float(json_data.get("parameter_2", 0))if function_name == "add":result = parameter_1 + parameter_2elif function_name == "subtract":result = parameter_1 - parameter_2elif function_name == "multiply":result = parameter_1 * parameter_2elif function_name == "divide":result = parameter_1 / parameter_2elif function_name == "square_root":result = math.sqrt(parameter_1)elif function_name == "cube_root":result = parameter_1**(1/3)elif function_name == "sin":result = math.sin(math.radians(parameter_1))elif function_name == "cos":result = math.cos(math.radians(parameter_1))elif function_name == "tan":result = math.tan(math.radians(parameter_1))elif function_name == "log_base_2":result = math.log2(parameter_1)elif function_name == "ln":result = math.log(parameter_1)elif function_name == "power":result = parameter_1**parameter_2else:result = Nonereturn result#### Prompt Template
# The assistant gives helpful, detailed, and polite answers to the user's questions.
# USER: Reply with json for the following question: what is 3 time 67? <|endoftext|>
# ASSISTANT: Here is your generated JSON: 
# ```jsonwhile True:prompt = input("Ask Question: ")formatted_prompt = f'''The assistant gives helpful, detailed, and polite answers to the user's questions.
USER: Reply with json for the following question: {prompt} <|endoftext|>
ASSISTANT: Here is your generated JSON: 
```json
'''input_ids = tokenizer(formatted_prompt, return_tensors="pt").input_ids.to("cuda")gen_tokens = model.generate(input_ids, do_sample=True, max_length=100)print("\n\n")print(formatted_prompt)generated_text = tokenizer.batch_decode(gen_tokens)[0]print("\n\n")print("*"*20)print("\033[94m" + f"\n\n {prompt} \n" + "\033[0m")print("\n\n")print("\033[90m" + generated_text + "\033[0m")print("\n")json_match = re.search(r'json\s*({.+?})\s*', generated_text, re.DOTALL)if json_match:json_string = json_match.group(1)try:json_data = json.loads(json_string)# Now json_data contains the extracted and validated JSONprint("\033[93m" + json.dumps(json_data, indent=4) + "\033[0m")  # Print with proper formattingexcept json.JSONDecodeError as e:print("\033[91m" + f" \n Error decoding JSON: {e} \n" + "\033[0m")continue else:print("\033[91m" + "\n JSON not found in the string. \n" + "\033[0m")continue result = evaluate_json(json_data)print(f"\n\n \033[92mThe result is: {result} \033[0m \n\n")print("*"*20)print("\n\n")

如果一切顺利,你应该得到如下所示的输出:

Ask Question:  what it cube root of 8?Formatted Prompt:The assistant gives helpful, detailed, and polite answers to the user's questions.
USER: Reply with json for the following question:  what it cube root of 8? <|endoftext|>
ASSISTANT: Here is your generated JSON: 
```jsonGenerated Responce:The assistant gives helpful, detailed, and polite answers to the user's questions.
USER: Reply with json for the following question:  what it cube root of 8? <|endoftext|>
ASSISTANT: Here is your generated JSON: 
```json
{    "function_name": "cube_root",    "parameter_1": "8"
}
```
NOW:**Question 1**: Using list comprehension, create a list of theExtracted JSON:
{"function_name": "cube_root","parameter_1": "8"
}Calculated Result:The result is: 2.0  ********************

潜在的陷阱:在这里,我们使用一个较小的模型“phi”,只有 100 行的微调数据根本不足以让这种大小的模型泛化,因此我们得到了太多的幻觉。 请注意,这只是举例,为了获得更好的结果,请使用更大的模型、更好的数据以及更多数据的更多纪元

模型有时可能会产生幻觉,为了缓解这种情况,只需增加训练数据,以便模型可以泛化,并确保只使用高质量的数据进行训练。 或者增加纪元数 num_epoches 您也可以尝试更大的模型,例如 llama-2–7B 或 mistra-7B-Instruct

恭喜!你已经微调了第一个 LLM 模型并创建了一个原始代理!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/664873.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

用 Easysearch 帮助大型车企降本增效

最近某头部汽车集团需要针对当前 ES 集群进行优化&#xff0c;背景如下&#xff1a; ES 用于支撑包括核心营销系统、管理支持系统、财务类、IT 基础设施类、研发、自动驾驶等多个重要应用&#xff0c;合计超 50 余套集群&#xff0c;累计数据超 1.5PB 。 本文针对其中一个 ES 集…

升级 FATFS 笔记

最近有朋友希望 AWTK demo 中的 FATFS 能升级到最新版本&#xff0c;在升级的过程中遇到一些小问题&#xff0c;这里做个记录。 1. 升级 FATFS 从官网下载最新代码。更新下面的文件到AWTK项目中&#xff1a; ff.cff.hffsystem.cffunicode.c 下面的文件不需要更新&#xff1…

Compose | UI组件(十二) | Lazy Layout - 列表

文章目录 前言LazyListScope作用域 用来干什么&#xff1f;LazyColumn组件含义&#xff1f;LazyColumn的基本使用LazyColumn Padding设置边距LazyColumn 设置边距 (contentPadding)LazyColumn 为每个子项设置边距 (Arrangement.spacedBy())LazyColumn 根据 rememberLazyListSta…

React从 EMAScript5编程规范到 EMAScript6编程规范过程中的几点改变

在从ECMAScript 5 (ES5)编程规范转换到ECMAScript 6 (ES6)编程规范的过程中&#xff0c;有几个主要的改变&#xff1a; 块级作用域&#xff1a;ES6引入了let和const关键字&#xff0c;允许在块级作用域中声明变量。在ES5中&#xff0c;变量的作用域仅限于函数内部。 箭头函数&…

a-upload——实现上传功能——基础积累

最近在写后台管理系统&#xff0c;遇到了上传功能&#xff0c;之前写过很多次&#xff0c;再次记录一下&#xff1a; <a-upload:file-list"fileList":remove"handleRemove":before-upload"beforeUpload":customRequest"customRequest&qu…

计算机毕业设计 | SSM 旅游网站后台管理系统(附源码)

1&#xff0c;概述 1.1 背景分析 随着人们生活水平的提高和对休闲旅游的日益重视&#xff0c;旅游业已成为全球最大的经济产业之一。越来越多的人选择通过在线方式进行旅行预订&#xff0c;这种趋势为旅游网站提供了巨大的商机。用户体验是决定旅游网站成功与否的关键因素。良…

Flutter 仿抖音 TikTok 上下滑动 播放视频

Flutter 仿抖音 TikTok 上下滑动 播放视频UI框架&#xff0c;视频播放使用 video_player github&#xff1a;GitHub - PangHaHa12138/TiktokVideo: Flutter 仿抖音 TikTok 上下滑动 播放视频UI框架 实现功能&#xff1a; 1.上下滑动自动播放切换视频&#xff0c;loading 封面…

bash脚本学习笔记

一、扫盲 脚本文件是一种文本文件&#xff0c;其中包含了一系列的命令和指令&#xff0c;可以被操作系统解释器直接解释执行。脚本文件通常被用来完成特定的任务或执行重复性的操作。 脚本文件通常以某种编程语言的语法编写&#xff0c;例如 Bash、Python、Perl、Ruby 等等。…

二叉树的层平均值

给定一个非空二叉树的根节点 root , 以数组的形式返回每一层节点的平均值。与实际答案相差 10-5 以内的答案可以被接受。 示例 1&#xff1a; 输入&#xff1a;root [3,9,20,null,null,15,7] 输出&#xff1a;[3.00000,14.50000,11.00000] 解释&#xff1a;第 0 层的平均值为 …

微服务架构风格

1 引言 微服务是一种架构风格&#xff0c;它将应用构建位为一个小型自治服务的集合&#xff0c;以业务领域为模型。通俗地说&#xff0c;就像蜜蜂通过对蜡制的等边六边形单元来构建它们的蜂巢。它们最初从使用材料的小单元开始&#xff0c;一点点的搭建出一个大型蜂巢。这些小单…

【OpenCV学习笔记27】- OpenCV 中的直方图 - 直方图 - 1:查找,绘图,分析

这是对于 OpenCV 官方文档中 图像处理 的学习笔记。学习笔记中会记录官方给出的例子&#xff0c;也会给出自己根据官方的例子完成的更改代码&#xff0c;同样彩蛋的实现也会结合多个知识点一起实现一些小功能&#xff0c;来帮助我们对学会的知识点进行结合应用。 如果有喜欢我笔…

1895_分离进程的能力

1895_分离进程的能力 全部学习汇总&#xff1a; g_unix: UNIX系统学习笔记 (gitee.com) 有些理念可能在控制类的嵌入式系统中不好实施&#xff0c;尤其是没有unix这样的系统搭载的情况下。如果是考虑在RTOS的基础上看是否有一些理念可以做尝试&#xff0c;我觉得还是可以有一定…

快速傅里叶变换 算法与实现

强烈推荐李家同教授 Communications engineering essentials for computer scientists and electrical engineers 一书 该部分关于离散傅里叶变换的讲解是我目前见过最好的 讲得十分清楚&#xff0c;严谨又不过分深入 直觉和物理动机也很明确 对于工程应用完全足够 书籍下载地…

npm 淘宝镜像正式到期,更新使用成功

npm 淘宝镜像原网址&#xff1a;https://registry.npm.taobao.org/ npm 淘宝镜像更新后网址&#xff1a;https://registry.npmmirror.com 过程&#xff1a; 部署 nuxt docker 容器的时候&#xff0c;报以下错&#xff1a; npm ERR! code CERT_HAS_EXPIRED npm ERR! errno CE…

跟着pink老师前端入门教程-day17

2、CSS3 动画 动画&#xff08;animation&#xff09;是CSS3中就要有颠覆性的特征之一&#xff0c;可通过设置多个节点来精确控制一个或一组动画&#xff0c;常用来实现复杂的动画效果 相比较过渡&#xff0c;动画可以实现更多变化&#xff0c;更多控制&#xff0c;连续自动播…

【Simulink系列】——动态系统仿真 之 简单系统

引入 不同的系统具有不同的输入与输出。一般来说&#xff0c;输入输出数目越多&#xff0c;系统越复杂。最简单的系统只要一个输入一个输出&#xff08;SISO&#xff09;&#xff0c;且其任意时刻的输出只与当前时刻的输入有关。 一、简单系统定义 对于满足下列条件的系统&a…

重新配置vue项目时出现的:连接已断开问题

在新机器上配置完node.js、vue-cli&#xff0c;配置了node_modules后&#xff0c;命令行运行vue ui后&#xff0c;出现了如下报错&#xff1a; C:\Users\LEN>vue ui &#x1f680; Starting GUI... &#x1f320; Ready on http://localhost:8000 node:events:496throw e…

揭秘店铺详情API接口:提升顾客信任与购物体验的利器

在电商领域&#xff0c;了解店铺的详细信息对于提升顾客的信任和忠诚度至关重要。为了帮助开发者获取和管理特定店铺的信息&#xff0c;电商平台通常提供店铺详情API接口。本文将指导你如何使用这个API接口来获取店铺的名称、描述、地址、评分等详细信息&#xff0c;并将这些信…

通过 ChatGPT 的 Function Call 查询数据库

用 Function Calling 的方式实现手机流量包智能客服的例子。 def get_sql_completion(messages, model"gpt-3.5-turbo"):response client.chat.completions.create(modelmodel,messagesmessages,temperature0,tools[{ # 摘自 OpenAI 官方示例 https://github.com/…

未定义基类问题解决

基类A, 子类B 原因 出现了超前部署&#xff0c;循环依赖&#xff0c;即A.h中包含了B.h &#xff0c;B.h中包含了A.h从而出现错误。 解决 将基类中的包含头文件#include"B.h"删除即可