项目简介
本项目是基于Python的llama.cpp绑定库,为Python开发者提供了简单的接口来调用llama.cpp的功能。
项目的主要特性和功能
- 提供简单的Python API,基于llama.cpp的C/C++函数构建,便于Python开发者调用。
- 具备文本生成功能,能根据输入文本生成后续文本,支持回调函数实时输出结果或推理完成后一次性获取结果。
- 支持交互式模式,通过设置回调函数实现与模型的交互对话。
- 可在
Model
类和generate
方法中传入多种参数,灵活控制模型行为。 - 支持GPT4All模型,可直接下载使用,还提供模型转换工具处理旧版本模型。
安装使用步骤
安装
- 使用预构建的轮子:
bash pip install pyllamacpp
- 从源代码构建:由于llama.cpp的编译会考虑目标CPU的架构,可能需要从源代码构建:
shell pip install.
使用
简单文本生成
```python from pyllamacpp.model import Model
def new_text_callback(text: str): print(text, end="", flush=True)
model = Model(ggml_model='./models/gpt4all-model.bin', n_ctx=512)
model.generate("Once upon a time, ", n_predict=55, new_text_callback=new_text_callback, n_threads=8)
若不使用回调函数,可在推理完成后从`generate`方法获取结果:
python
generated_text = model.generate("Once upon a time, ", n_predict=55)
print(generated_text)
```
交互式模式
```python from pyllamacpp.model import Model
def new_text_callback(text: str): print(text, end="", flush=True)
def grab_text_callback(): inpt = input() if inpt == "END": return None return inpt
model = Model(ggml_model='./models/gpt4all-model.bin', n_ctx=512)
prompt = """ Transcript of a dialog, where the User interacts with an Assistant named Bob. Bob is helpful, kind, honest, good at writing, and never fails to answer the User's requests immediately and with precision. To do this, Bob uses a database of information collected from many different sources, including books, journals, online articles, and more.
User: Hello, Bob. Bob: Hello. How may I help you today? User: Please tell me the largest city in Europe. Bob: Sure. The largest city in Europe is Moscow, the capital of Russia. User:"""
model.generate(prompt, n_predict=256, new_text_callback=new_text_callback, grab_text_callback=grab_text_callback, interactive=True, repeat_penalty=1.0, antiprompt=["User:"]) ```
模型支持
GPT4All
从https://the-eye.eu/public/AI/models/nomic-ai/gpt4all/ 下载GPT4All模型,建议下载以ggml.bin
结尾的文件。若下载的是旧版本模型,可在终端运行以下命令进行转换:
shell
pyllamacpp-convert-gpt4all path/to/gpt4all_model.bin path/to/llama_tokenizer path/to/gpt4all-converted.bin
下载地址
点击下载 【提取码: 4003】【解压密码: www.makuang.net】