llama-cpp-python快速上手

llama-cpp-python快速上手

搭建环境

项目地址GitHub,有能力的话可以直接阅读原始文档。

首先按照文档,安装llama-cpp-python

1
pip install llama-cpp-python

接下来,你可能缺一些依赖,这一点在文档中没有涉及但是我整理了我缺少的依赖,依次运行即可。

1
2
3
4
5
6
pip install uvicorn
pip install anyio
pip install starlette
pip install fastapi
pip install pydantic_settings
pip install sse_starlette

高级API和低级API

高级API

高级 API 通过Llama类提供简单的托管接口。请将./models/7B/ggml-model.bin 换成你的模型的路径,下同。

1
2
3
4
from llama_cpp import Llama
llm = Llama(model_path="./models/7B/ggml-model.bin")
output = llm("Q: Name the planets in the solar system? A: ", max_tokens=32, stop=["Q:", "\n"], echo=True)
print(output)
返回值如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"id": "cmpl-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"object": "text_completion",
"created": 1679561337,
"model": "./models/7B/ggml-model.bin",
"choices": [
{
"text": "Q: Name the planets in the solar system? A: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune and Pluto.",
"index": 0,
"logprobs": None,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 14,
"completion_tokens": 28,
"total_tokens": 42
}
}

低级API

低级 API 直接ctypes绑定到llama.cpp. 整个低级 API 可以在llama_cpp/llama_cpp.py中找到,并直接镜像llama.h中的 C API 。

1
2
3
4
5
6
7
8
9
10
import llama_cpp
import ctypes
params = llama_cpp.llama_context_default_params()
# use bytes for char * params
ctx = llama_cpp.llama_init_from_file(b"./models/7b/ggml-model.bin", params)
max_tokens = params.n_ctx
# use ctypes arrays for array params
tokens = (llama_cpp.llama_token * int(max_tokens))()
n_tokens = llama_cpp.llama_tokenize(ctx, b"Q: Name the planets in the solar system? A: ", tokens, max_tokens, add_bos=llama_cpp.c_bool(True))
llama_cpp.llama_free(ctx)

搭建与openai接口兼容的服务器接口

llama-cpp-python提供一个 Web 服务器,旨在作为 OpenAI API 的直接替代品。

1
python3 -m llama_cpp.server --model models/7B/ggml-model.bin
你可以在上面的命令运行成功后访问文档

文档是全英的,想要对话接口的话我用python写了个示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import requests

url = 'http://localhost:8000/v1/chat/completions'
headers = {
'accept': 'application/json',
'Content-Type': 'application/json'
}
data = {
'messages': [
{
'content': 'You are a helpful assistant.',
'role': 'system'
},
{
'content': 'What is the capital of France?',
'role': 'user'
}
]
}

response = requests.post(url, headers=headers, json=data)
print(response.json())
print(response.json()['choices'][0]['message']['content'])

如果你想自建一个接口,请在遵守相关法律法规的情况下,在自己的服务器上启动相关服务,并反向代理http://localhost:8000 地址。例如你反向代理到了https://example.com,那你的对话地址就是https://example.com/v1/chat/completions。当你想用gpt的时候就不用看openai的脸色了,直接部署一个自己的接口自己请求,或者调用openai库的时候apibase写自己的接口。


llama-cpp-python快速上手
https://studyinglover.com/2023/07/28/llama-cpp-python快速上手/
作者
StudyingLover
发布于
2023年7月28日
许可协议