下载 Llama 3 8B 模型文件
官网地址:https://huggingface.co/QuantFactory/Meta-Llama-3-8B-Instruct-GGUF/tree/main
国内镜像:QuantFactory/Meta-Llama-3-8B-Instruct-GGUF at main
版本号参考:GGML 或GGUF的14种不同量化模式说明-CSDN博客
根据自己需求选择模型版本下载。
创建并激活虚拟环境
conda create -n GGUF python=3.12.2
conda activate GGUF
安装依赖包
pip install llama-cpp-python
pip install openai
pip install uvicorn
pip install starlette
pip install fastapi
pip install sse_starlette
pip install starlette_context
pip install pydantic_settings
安装llama-cpp-python时会报错!
参考我的这篇博客:
pip install llama-cpp-python时报错解决!-CSDN博客
启动大模型
python -m llama_cpp.server --host 0.0.0.0 --model ./Meta-Llama-3-8B-Instruct.Q4_K_M.gguf --n_ctx 2048
启动成功!
编写 Llama 模型对话客户端
from openai import OpenAI
# 注意服务端端口,因为是本地,所以不需要api_key
client = OpenAI(base_url="http://localhost:8000/v1",
api_key="not-needed")
# 对话历史:设定系统角色是一个只能助理,同时提交“自我介绍”问题
history = [
{"role": "system", "content": "你是一个智能助理,你的回答总是正确的、有用的和内容非常精简."},
{"role": "user", "content": "请用中文进行自我介绍,要求不能超过5句话,总字数不超过100个字。"},
]
print("\033[92;1m")
# 首次自我介绍完毕,接下来是等代码我们的提示
while True:
completion = client.chat.completions.create(
model="local-model",
messages=history,
temperature=0.7,
stream=True,
)
new_message = {"role": "assistant", "content": ""}
for chunk in completion:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
new_message["content"] += chunk.choices[0].delta.content
history.append(new_message)
print("\033[91;1m")
userinput = input("> ")
if userinput.lower() in ["bye", "quit", "exit"]: # 我们输入bye/quit/exit等均退出客户端
print("\033[0mBYE BYE!")
break
history.append({"role": "user", "content": userinput})
print("\033[92;1m")
开始对话!
参考:https://www.cnblogs.com/obullxl/p/18187815/NTopic2024051101