littlebot
Published on 2025-04-17 / 2 Visits
0

【源码】基于Python的llama.cpp模型调用系统

项目简介

本项目是基于Python的llama.cpp模型调用系统,借助Pybind11库将C++代码绑定到Python,封装了llama.cpp的接口,为Python提供简单API,使用户能在Python环境中进行文本生成、评估、tokenize等操作。

项目的主要特性和功能

  1. 跨模型支持:支持LLaMA、Alpaca、GPT4All、Chinese LLaMA / Alpaca等多种模型。
  2. 多平台适配:无需依赖,对Apple silicon有优化,支持x86架构的AVX2,支持混合F16 / F32精度和4位量化,可在CPU上运行。
  3. 多种使用方式:提供命令行界面用于快速测试,支持在Python代码中进行交互式对话、为语言模型赋予特定人设等操作。
  4. 高级使用功能:高级用户可直接访问llama.cpp C - API函数实现自定义逻辑。

安装使用步骤

安装

  • 安装预构建包:使用以下命令安装预构建的轮子 bash pip install pyllamacpp
  • 从源代码构建:由于llama.cpp的编译会考虑目标CPU的架构,可能需要从源代码构建 shell
  • 使用旧版本模型:如果要使用旧版本模型,需安装版本2.2.0 bash pip install pyllamacpp==2.2.0

使用

命令行界面

安装完成后,可使用以下命令测试: shell pyllamacpp path/to/model.bin 使用-h参数查看帮助信息: shell pyllamacpp -h

Python代码使用

  • 快速开始 ```python from pyllamacpp.model import Model

model = Model(model_path='/path/to/model.bin') for token in model.generate("Tell me a joke?\n"): print(token, end='', flush=True) - **交互式对话**python from pyllamacpp.model import Model

model = Model(model_path='/path/to/model.bin') while True: try: prompt = input("You: ", flush=True) if prompt == '': continue print(f"AI:", end='') for token in model.generate(prompt): print(f"{token}", end='', flush=True) print() except KeyboardInterrupt: break - **为语言模型赋予人设**python from pyllamacpp.model import Model

prompt_context = """Act as Bob. Bob is helpful, kind, honest, and never fails to answer the User's requests immediately and with precision.

User: Nice to meet you Bob! Bob: Welcome! I'm here to assist you with anything you need. What can I do for you today? """

prompt_prefix = "\nUser:" prompt_suffix = "\nBob:"

model = Model(model_path='/path/to/model.bin', n_ctx=512, prompt_context=prompt_context, prompt_prefix=prompt_prefix, prompt_suffix=prompt_suffix)

while True: try: prompt = input("User: ") if prompt == '': continue print(f"Bob: ", end='') for token in model.generate(prompt, antiprompt='User:', n_threads=6, n_batch=1024, n_predict=256, n_keep=48, repeat_penalty=1.0, ): print(f"{token}", end='', flush=True) print() except KeyboardInterrupt: break ```

下载地址

点击下载 【提取码: 4003】【解压密码: www.makuang.net】