To use the llama.cpp C++ library directly from Python—without relying on the llama-cpp-python package or any other Python wrapper—you need to interface with the compiled C/C++ shared library using Python’s ctypes or cffi modules. This approach allows you to load the model, set up the context, send a prompt, and retrieve the response, all from Python. Below is a thorough, minimal example using ctypes, assuming you have already compiled llama.cpp as a shared library (e.g., libllama.so or llama.dll) and have a GGUF model file.
Key Steps:
- Load the llama.cpp shared library using ctypes.
- Initialize the backend and model.
- Create a context with the model and set parameters.
- Tokenize the prompt and run inference.
- Extract and decode the generated tokens into a Python string.
import ctypes
import os
# Path to the compiled llama.cpp shared library and model
LLAMA_LIB_PATH = "/path/to/libllama.so" # or .dll on Windows
MODEL_PATH = b"/path/to/model.gguf" # must be bytes
# Load the llama.cpp shared library
llama = ctypes.CDLL(LLAMA_LIB_PATH)
# Define necessary types and constants
llama.llama_backend_init.argtypes = [ctypes.c_bool]
llama.llama_backend_init.restype = None
llama.llama_load_model_from_file.argtypes = [ctypes.c_char_p, ctypes.c_void_p]
llama.llama_load_model_from_file.restype = ctypes.c_void_p
llama.llama_context_default_params.restype = ctypes.c_void_p
llama.llama_new_context_with_model.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
llama.llama_new_context_with_model.restype = ctypes.c_void_p
llama.llama_tokenize.argtypes = [
ctypes.c_void_p, ctypes.c_char_p, ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_bool
]
llama.llama_tokenize.restype = ctypes.c_int
llama.llama_eval.argtypes = [
ctypes.c_void_p, ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_int, ctypes.c_int
]
llama.llama_eval.restype = ctypes.c_int
llama.llama_get_logits.argtypes = [ctypes.c_void_p]
llama.llama_get_logits.restype = ctypes.POINTER(ctypes.c_float)
llama.llama_sample_top_p_top_k.argtypes = [
ctypes.c_void_p, ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float
]
llama.llama_sample_top_p_top_k.restype = ctypes.c_int
llama.llama_token_to_str.argtypes = [ctypes.c_void_p, ctypes.c_int]
llama.llama_token_to_str.restype = ctypes.c_char_p
llama.llama_free.argtypes = [ctypes.c_void_p]
llama.llama_free.restype = None
# 1. Initialize llama.cpp backend
llama.llama_backend_init(False)
# 2. Set up model and context parameters
params = llama.llama_context_default_params()
model = llama.llama_load_model_from_file(MODEL_PATH, params)
ctx = llama.llama_new_context_with_model(model, params)
# 3. Tokenize the prompt
prompt = b"Q: Name the planets in the solar system? A: "
max_tokens = 128
tokens = (ctypes.c_int * max_tokens)()
n_tokens = llama.llama_tokenize(ctx, prompt, tokens, max_tokens, True)
# 4. Run inference (generate tokens)
output_tokens = []
n_ctx = 128 # context window
for i in range(32): # generate up to 32 tokens
n_eval = llama.llama_eval(ctx, tokens, n_tokens, i, n_ctx)
if n_eval != 0:
break
logits = llama.llama_get_logits(ctx)
# Sample next token (here, just pick the most probable for simplicity)
next_token = ctypes.c_int(logits[:n_tokens].index(max(logits[:n_tokens])))
output_tokens.append(next_token.value)
tokens = next_token.value
n_tokens = 1
if next_token.value == 2: # EOS token (example)
break
# 5. Decode tokens to string
response = ""
for tok in output_tokens:
s = llama.llama_token_to_str(ctx, tok)
response += s.decode("utf-8")
# 6. Clean up
llama.llama_free(ctx)
# The response variable now contains the generated text
print("Model response:", response)
Notes:
- You must adjust the function signatures and logic to match the exact llama.cpp C API version you compiled.
- The above code is a minimal illustration; for production, handle errors, memory management, and sampling more robustly.
- This approach does not use any Python wrapper library for llama.cpp; it uses ctypes to call the C API directly.
- For more advanced sampling (top-k, top-p, temperature), you must implement or call the relevant llama.cpp functions as needed.
This method gives you full control and keeps your Python code independent of any Python-specific llama.cpp bindings[1][2][7].