跳转到主要内容

llama.cpp LLM 框架与 Haystack 的集成

项目描述

llama-cpp-haystack

PyPI - Version PyPI - Python Version


为使用 Llama.cpp LLM 框架运行 LLM 的 Haystack (2.x) 自定义组件。此实现利用了 llama.cpp 的 Python 绑定

目录

安装

pip install llama-cpp-haystack

默认安装行为是在 Linux 和 Windows 上仅构建 llama.cpp 用于 CPU,并在 MacOS 上使用 Metal。

要使用其他后端安装,首先使用它们 安装文档 上的说明安装 llama-cpp-python,然后安装 llama-cpp-haystack

例如,要使用 cuBLAS 后端安装 llama-cpp-haystack

export LLAMA_CUBLAS=1
CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama-cpp-python
pip install llama-cpp-haystack

用法

您可以使用 LlamaCppGenerator 加载使用 llama.cpp (GGUF) 量化的模型,用于文本生成。

有关支持的模型和模型参数的信息可以在 llama.cpp 文档 中找到。

流行模型的 GGUF 版本可以从 HuggingFace 下载。

传递额外的模型参数

为了方便,已公开了 model_pathn_ctxn_batch 参数,可以在初始化 Generator 时直接作为关键字参数传递。

可以使用 model_kwargs 参数在初始化模型时传递额外的参数。如果存在重复,这些参数将覆盖 model_pathn_ctxn_batch 初始化参数。

有关可用模型参数的更多信息,请参阅 Llama.cpp 的 模型文档

例如,在初始化时将模型卸载到 GPU

from haystack_integrations.components.generators.llama_cpp import LlamaCppGenerator

generator = LlamaCppGenerator(
    model_path="/content/openchat-3.5-1210.Q3_K_S.gguf", 
    n_ctx=512,
    n_batch=128,
    model_kwargs={"n_gpu_layers": -1}
)
generator.warm_up()

input = "Who is the best American actor?"
prompt = f"GPT4 Correct User: {input} <|end_of_turn|> GPT4 Correct Assistant:"

result = generator.run(prompt, generation_kwargs={"max_tokens": 128})
generated_text = result["replies"][0]

print(generated_text)

传递生成参数

可以使用 generation_kwargs 参数在推理过程中将额外的生成参数(如 max_tokenstemperaturetop_ktop_p 等)传递给模型。

有关可用生成参数的更多信息,请参阅 Llama.cpp 的 create_completion 文档

例如,设置 max_tokenstemperature

from haystack_integrations.components.generators.llama_cpp import LlamaCppGenerator

generator = LlamaCppGenerator(
    model_path="/content/openchat-3.5-1210.Q3_K_S.gguf",
    n_ctx=512,
    n_batch=128,
    generation_kwargs={"max_tokens": 128, "temperature": 0.1},
)
generator.warm_up()

input = "Who is the best American actor?"
prompt = f"GPT4 Correct User: {input} <|end_of_turn|> GPT4 Correct Assistant:"

result = generator.run(prompt)
generated_text = result["replies"][0]

print(generated_text)

可以直接将 generation_kwargs 传递给生成器的 run 方法

from haystack_integrations.components.generators.llama_cpp import LlamaCppGenerator

generator = LlamaCppGenerator(
    model_path="/content/openchat-3.5-1210.Q3_K_S.gguf",
    n_ctx=512,
    n_batch=128,
)
generator.warm_up()

input = "Who is the best American actor?"
prompt = f"GPT4 Correct User: {input} <|end_of_turn|> GPT4 Correct Assistant:"

result = generator.run(
    prompt,
    generation_kwargs={"max_tokens": 128, "temperature": 0.1},
)
generated_text = result["replies"][0]

print(generated_text)

示例

以下是一个使用 HuggingFace 的 Simple Wikipedia 数据集的示例检索增强生成 (RAG) 管道。您可以在 示例文件夹 中找到更多示例。

加载数据集

# Install HuggingFace Datasets using "pip install datasets"
from datasets import load_dataset
from haystack import Document, Pipeline
from haystack.components.builders.answer_builder import AnswerBuilder
from haystack.components.builders.prompt_builder import PromptBuilder
from haystack.components.embedders import SentenceTransformersDocumentEmbedder, SentenceTransformersTextEmbedder
from haystack.components.retrievers import InMemoryEmbeddingRetriever
from haystack.components.writers import DocumentWriter
from haystack.document_stores import InMemoryDocumentStore

# Import LlamaCppGenerator
from haystack_integrations.components.generators.llama_cpp import LlamaCppGenerator

# Load first 100 rows of the Simple Wikipedia Dataset from HuggingFace
dataset = load_dataset("pszemraj/simple_wikipedia", split="validation[:100]")

docs = [
    Document(
        content=doc["text"],
        meta={
            "title": doc["title"],
            "url": doc["url"],
        },
    )
    for doc in dataset
]

使用 SentenceTransformersDocumentEmbedderDocumentWriter 将文档索引到 InMemoryDocumentStore

doc_store = InMemoryDocumentStore(embedding_similarity_function="cosine")
doc_embedder = SentenceTransformersDocumentEmbedder(model="sentence-transformers/all-MiniLM-L6-v2")

# Indexing Pipeline
indexing_pipeline = Pipeline()
indexing_pipeline.add_component(instance=doc_embedder, name="DocEmbedder")
indexing_pipeline.add_component(instance=DocumentWriter(document_store=doc_store), name="DocWriter")
indexing_pipeline.connect(connect_from="DocEmbedder", connect_to="DocWriter")

indexing_pipeline.run({"DocEmbedder": {"documents": docs}})

创建检索增强生成 (RAG) 管道并将其 LlamaCppGenerator 添加到其中

# Prompt Template for the https://hugging-face.cn/openchat/openchat-3.5-1210 LLM
prompt_template = """GPT4 Correct User: Answer the question using the provided context.
Question: {{question}}
Context:
{% for doc in documents %}
    {{ doc.content }}
{% endfor %}
<|end_of_turn|>
GPT4 Correct Assistant:
"""

rag_pipeline = Pipeline()

text_embedder = SentenceTransformersTextEmbedder(model="sentence-transformers/all-MiniLM-L6-v2")

# Load the LLM using LlamaCppGenerator
model_path = "openchat-3.5-1210.Q3_K_S.gguf"
generator = LlamaCppGenerator(model_path=model_path, n_ctx=4096, n_batch=128)

rag_pipeline.add_component(
    instance=text_embedder,
    name="text_embedder",
)
rag_pipeline.add_component(instance=InMemoryEmbeddingRetriever(document_store=doc_store, top_k=3), name="retriever")
rag_pipeline.add_component(instance=PromptBuilder(template=prompt_template), name="prompt_builder")
rag_pipeline.add_component(instance=generator, name="llm")
rag_pipeline.add_component(instance=AnswerBuilder(), name="answer_builder")

rag_pipeline.connect("text_embedder", "retriever")
rag_pipeline.connect("retriever", "prompt_builder.documents")
rag_pipeline.connect("prompt_builder", "llm")
rag_pipeline.connect("llm.replies", "answer_builder.replies")
rag_pipeline.connect("retriever", "answer_builder.documents")

运行管道

question = "Which year did the Joker movie release?"
result = rag_pipeline.run(
    {
        "text_embedder": {"text": question},
        "prompt_builder": {"question": question},
        "llm": {"generation_kwargs": {"max_tokens": 128, "temperature": 0.1}},
        "answer_builder": {"query": question},
    }
)

generated_answer = result["answer_builder"]["answers"][0]
print(generated_answer.data)
# The Joker movie was released on October 4, 2019.

许可证

llama-cpp-haystack 根据 Apache-2.0 许可证发布。

项目详情


下载文件

下载适合您平台的项目文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分布

llama_cpp_haystack-0.4.1.tar.gz (17.3 kB 查看哈希)

上传时间

构建分布

llama_cpp_haystack-0.4.1-py3-none-any.whl (12.3 kB 查看哈希)

上传时间 Python 3

由以下组织支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面