Skip to main content
Open In ColabOpen on GitHub

Llama.cpp

llama.cpp python 库是 @ggerganov llama.cpp 的简单 Python 绑定。

该软件包提供:

  • 通过 ctypes 接口低级访问 C API。
  • 用于文本补全的高级 Python API
    • OpenAI 风格的 API
    • LangChain 兼容性
    • LlamaIndex 兼容性
  • OpenAI 兼容的 Web 服务器
    • 本地 Copilot 替代方案
    • 支持函数调用
    • 支持视觉 API
    • 支持多模型

概览

集成细节

Class本地序列化JS支持
ChatLlamaCpplangchain-community

模型特性

工具调用结构化输出JSON 模式图像输入音频输入视频输入Token级流式传输原生异步Token 使用对数概率

设置

要开始并使用下方展示的所有功能,请推荐使用已针对工具调用进行微调的模型。

我们将使用 Hermes-2-Pro-Llama-3-8B-GGUF 来自NousResearch。

Hermes 2 Pro 是 Nous Hermes 2 的升级版,由更新并清理后的 OpenHermes 2.5 数据集以及新开发的内置函数调用和 JSON 模式数据集组成。这款新的 Hermes 版本保持了其出色的通用任务和对话能力 - 同时在函数调用方面也表现出色

见我们的指南深入了解本地模型:

安装

The LangChain LlamaCpp 整合存在于 langchain-communityllama-cpp-python 包中:

%pip install -qU langchain-community llama-cpp-python

Instantiation

现在我们就可以实例化我们的模型对象并生成聊天完成内容:

# Path to your model weights
local_model = "local/path/to/Hermes-2-Pro-Llama-3-8B-Q8_0.gguf"
import multiprocessing

from langchain_community.chat_models import ChatLlamaCpp

llm = ChatLlamaCpp(
temperature=0.5,
model_path=local_model,
n_ctx=10000,
n_gpu_layers=8,
n_batch=300, # Should be between 1 and n_ctx, consider the amount of VRAM in your GPU.
max_tokens=512,
n_threads=multiprocessing.cpu_count() - 1,
repeat_penalty=1.5,
top_p=0.5,
verbose=True,
)
API 参考:ChatLlamaCpp

Invocation

messages = [
(
"system",
"You are a helpful assistant that translates English to French. Translate the user sentence.",
),
("human", "I love programming."),
]

ai_msg = llm.invoke(messages)
ai_msg
print(ai_msg.content)
J'aime programmer. (In France, "programming" is often used in its original sense of scheduling or organizing events.) 

If you meant computer-programming:
Je suis amoureux de la programmation informatique.

(You might also say simply 'programmation', which would be understood as both meanings - depending on context).

链式调用

我们可以通过以下方式将模型与提示模板进行链接

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant that translates {input_language} to {output_language}.",
),
("human", "{input}"),
]
)

chain = prompt | llm
chain.invoke(
{
"input_language": "English",
"output_language": "German",
"input": "I love programming.",
}
)

工具调用

首先,它的工作方式与OpenAI函数调用大多相同。

OpenAI 有一个 称为工具调用的 API(我们在这里交替使用“工具调用”和“函数调用”),该 API 允许你描述工具及其参数,并使模型返回一个包含要调用的工具及其输入的 JSON 对象。工具调用对于构建工具使用的链和代理非常重要,也更广泛地有助于从模型获取结构化输出。

使用 ChatLlamaCpp.bind_tools,我们可以轻松地将 Pydantic 类、字典模式、LangChain 工具或甚至作为工具的函数传递给模型。在幕后,这些会被转换为一个 OpenAI 工具模式,看起来像这样:

{
"name": "...",
"description": "...",
"parameters": {...} # JSONSchema
}

并且在每次模型调用时传入。

然而,它不能自动触发一个函数/工具,我们需要通过指定'tool choice'参数来强制执行。这个参数通常如下面所示进行格式化。

{"type": "function", "function": {"name": <<tool_name>>}}.

from langchain_core.tools import tool
from pydantic import BaseModel, Field


class WeatherInput(BaseModel):
location: str = Field(description="The city and state, e.g. San Francisco, CA")
unit: str = Field(enum=["celsius", "fahrenheit"])


@tool("get_current_weather", args_schema=WeatherInput)
def get_weather(location: str, unit: str):
"""Get the current weather in a given location"""
return f"Now the weather in {location} is 22 {unit}"


llm_with_tools = llm.bind_tools(
tools=[get_weather],
tool_choice={"type": "function", "function": {"name": "get_current_weather"}},
)
API 参考:工具
ai_msg = llm_with_tools.invoke(
"what is the weather like in HCMC in celsius",
)
ai_msg.tool_calls
[{'name': 'get_current_weather',
'args': {'location': 'Ho Chi Minh City', 'unit': 'celsius'},
'id': 'call__0_get_current_weather_cmpl-394d9943-0a1f-425b-8139-d2826c1431f2'}]
class MagicFunctionInput(BaseModel):
magic_function_input: int = Field(description="The input value for magic function")


@tool("get_magic_function", args_schema=MagicFunctionInput)
def magic_function(magic_function_input: int):
"""Get the value of magic function for an input."""
return magic_function_input + 2


llm_with_tools = llm.bind_tools(
tools=[magic_function],
tool_choice={"type": "function", "function": {"name": "get_magic_function"}},
)

ai_msg = llm_with_tools.invoke(
"What is magic function of 3?",
)

ai_msg
ai_msg.tool_calls
[{'name': 'get_magic_function',
'args': {'magic_function_input': 3},
'id': 'call__0_get_magic_function_cmpl-cd83a994-b820-4428-957c-48076c68335a'}]

结构化输出

from langchain_core.utils.function_calling import convert_to_openai_tool
from pydantic import BaseModel


class Joke(BaseModel):
"""A setup to a joke and the punchline."""

setup: str
punchline: str


dict_schema = convert_to_openai_tool(Joke)
structured_llm = llm.with_structured_output(dict_schema)
result = structured_llm.invoke("Tell me a joke about birds")
result
result
{'setup': '- Why did the chicken cross the playground?',
'punchline': '\n\n- To get to its gilded cage on the other side!'}

流式传输

for chunk in llm.stream("what is 25x5"):
print(chunk.content, end="\n", flush=True)

API 参考

详细介绍了所有ChatLlamaCpp功能和配置的文档,请访问API参考:https://python.langchain.com/api_reference/community/chat_models/langchain_community.chat_models.llamacpp.ChatLlamaCpp.html