EN ▾
Get API key

llama.cpp OpenAI API in Python vs a Hosted Endpoint

To use the llama cpp openai api python route, you start llama.cpp's built-in server and point the official openai package at it. The same script can then target a hosted endpoint by changing the base URL, which makes the two options easy to compare.

Updated

A local terminal cube and a cloud server joined by one ribbon of light, one Python client for two endpoints
Coin, GPU card and server cube illustrating the cost of free local models versus a hosted API

Key points

  • llama-server exposes an OpenAI-style /v1/chat/completions route on your own machine.
  • The openai Python package works against it with a dummy key and a custom base_url.
  • Switching to a hosted endpoint is a three-value change: URL, key and model name.
  • Local fits privacy and experiments; hosted fits shared apps, long context and no hardware.

Start the llama.cpp server

llama.cpp ships a server binary called llama-server. It loads a GGUF model file and serves HTTP, including routes that follow the OpenAI chat format. Build or install llama.cpp following its README, download a GGUF file for the model you want, then start the server:

llama-server -m ./model.gguf -c 8192 -ngl 99 --host 127.0.0.1 --port 8080

The flags: -m is the model file, -c the context length in tokens, -ngl the number of layers offloaded to the GPU, --host the address to listen on and --port the port. Keep the host on 127.0.0.1 unless you really want other machines to connect, since the server has no login by default.

A larger -c needs more memory for the cache, so size it to your real prompts. If you see out-of-memory errors at startup, lower -c, offload fewer layers or use a smaller quantization.

The Python bindings, llama-cpp-python, include a similar server module. The code below works with either, since both follow the same API shape.

Call it from Python with the openai package

Install the client with pip install openai. The package does not care that the server is not OpenAI. It builds the request, sends it to base_url and parses the reply. The script below keeps both targets in one place so you can flip between them:

from openai import OpenAI

TARGETS = {
    "local":  {"base_url": "http://127.0.0.1:8080/v1", "api_key": "local", "model": "model"},
    "hosted": {"base_url": "https://api.llamauncensored.cc/v1", "api_key": "YOUR_KEY", "model": "uncensored"},
}

def make_client(name):
    t = TARGETS[name]
    return OpenAI(base_url=t["base_url"], api_key=t["api_key"]), t["model"]

client, model = make_client("local")

resp = client.chat.completions.create(
    model=model,
    messages=[
        {"role": "system", "content": "Answer in two sentences."},
        {"role": "user", "content": "What does the -ngl flag do in llama.cpp?"},
    ],
    temperature=0.7,
)
print(resp.choices[0].message.content)
print(resp.usage)

llama-server uses the model it loaded and does not need a real model name, so any string works there, while the hosted endpoint expects uncensored. The key for a local server can be any non-empty string.

Streaming and usage

Streaming works the same way on both targets. Set stream=True and iterate over the chunks:

client, model = make_client("hosted")

stream = client.chat.completions.create(
    model=model,
    messages=[{"role": "user", "content": "List three uses of a GGUF file."}],
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print("\n", chunk.usage)

The hosted endpoint sends usage at the end of the stream, so the final chunk reports token counts you can log. Local server versions differ in how they report usage while streaming, so check what yours returns before building billing or logging around it.

One difference to plan for: on the hosted API a streamed request holds one of your concurrency slots until the stream finishes. A full key allows 8 at a time, so a worker pool larger than 8 will see 429 responses with the code concurrency. Your local server has its own limit, which you set with its slot options.

Differences that matter in practice

Topicllama.cpp serverHosted endpoint
CostHardware and power$0.15 per 1M input, $0.50 per 1M output tokens
ContextWhatever you set with -c, within memory100,000 tokens, prompt plus completion
ConcurrencyYour slots and your GPU8 for a full key, 2 for a trial key
ModelAny GGUF you loadOne model, ID uncensored
Tool callingDepends on version and chat templateSupported with tools and tool_choice
Uptime workYou restart and monitorProvider operates it

Tool calling on llama.cpp has improved across versions, but it depends on the model's chat template and the flags you pass, so read the project's documentation for your release and test with your actual model. On the hosted API, tools, tool_choice, streamed tool_calls and results sent back as role: "tool" follow the OpenAI shape. JSON mode is available with response_format set to {"type":"json_object"}.

When local is the better choice

Be honest about the cases where llama.cpp wins. If you work offline, if prompts must never leave your computer, if you want to test a particular fine-tune or quantization, or if you already own a strong GPU and run high continuous volume, local costs less and gives you more control. It is also the better place to learn how sampling and context settings behave, since you see every flag.

The price is your time. You maintain the build, pick files, tune memory and handle restarts. For a hobby script that is fine. For a service other people depend on, it adds up.

When a hosted endpoint is the better choice

Choose hosted when you do not want to own a GPU, when you need more context than your memory allows, or when several people or servers must reach the model. Hosted requires no build step, and the model in question here is tuned to answer without content refusals for lawful adult use. To be accurate about what that means: it is one open-weight model run by an independent provider, not Llama from Meta and not a router across vendors, and it handles text only.

A typical request of 4,000 input tokens and 600 output tokens costs 4,000 x $0.15 / 1,000,000 + 600 x $0.50 / 1,000,000 = $0.0006 + $0.0003 = $0.0009. For 10,000 such requests a month, that is $9. Failed or refused requests are not charged.

To try it, claim the $0.50 trial credit on the API key page (one click after sign-up, no card, 7 days), then run the script above with make_client("hosted"). The documentation lists all endpoints and the pricing page explains top-ups, which start at $20. More background on moving existing Llama code over is in the Llama API integration guide.

Common mistakes when switching targets

  • Forgetting /v1. The openai package appends /chat/completions to the base URL, so the base should end in /v1 for both targets.
  • Sending the local key to the hosted API. A dummy key gets a 401. Use your real key for the hosted target.
  • Keeping a local model name. The hosted target needs uncensored.
  • Assuming equal context. A prompt that fits the hosted window may overflow a local one set to 8192.
  • Ignoring 429s. Retry after the delay in the Retry-After header when it is present.

Questions and answers

Does llama.cpp have an OpenAI-compatible API?

Yes. llama-server provides routes such as /v1/chat/completions that accept OpenAI-style requests, so the openai Python package can talk to it.

What API key do I use for a local llama.cpp server?

Any non-empty string, since a default local server does not check it. The SDK just requires a value.

Can I switch between local and hosted without rewriting code?

Yes. Change base_url, api_key and model. Everything else, including streaming and message formats, stays the same.

Is the hosted model the same as the one I run in llama.cpp?

Not necessarily. It is a separate open-weight model run by a provider, so test your prompts against it before relying on matching output.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Start with trial credit

Email and password, key on screen right away.