EN ▾

llama.cpp LangChain: Use a Hosted OpenAI-Compatible API

If your LangChain code already talks to a llama.cpp server, moving to a hosted endpoint is a two-line change. Here is the code, plus the places where the two setups differ.

Updated

Chain of linked blocks joining a local computer and a cloud server, illustrating LangChain with a hosted API

The short version

People who search for llama.cpp langchain usually have one of two goals. Either they run llama.cpp on their own hardware and want LangChain to talk to it, or they tried that and found that local inference is slow or hard to scale. In both cases the glue is the same: llama.cpp ships a server, llama-server, that speaks the OpenAI chat completions protocol, and LangChain's ChatOpenAI class can be pointed at any server that does.

A hosted OpenAI-compatible API plugs into the very same class. You swap the base URL and the key, set the model to uncensored, and the rest of your chain stays as it is. The sections below cover the install, a minimal chain, streaming, tool calling, JSON output and batching, and then the one thing that does not carry over cleanly: embeddings for retrieval.

Everything here uses the official langchain-openai package and no custom wrapper, which keeps your upgrade path simple. When LangChain changes a class name, the fix is one import, not a rewrite of an adapter you maintain.

Local server or hosted API, and what changes

Neither option is better in every case. Pick by what you are building.

QuestionLocal llama-serverHosted endpoint
HardwareYou provide a GPU or a fast CPU and enough memoryNone on your side
Cost modelYour hardware and electricity$0.15 per 1M input tokens, $0.50 per 1M output tokens
Model choiceAny GGUF file you can loadOne model, ID uncensored
Offline useWorks with no networkNeeds internet access
Parallel requestsLimited by your machine8 at once on a full key

If you want to pick your own quantization, run fully offline, or keep every byte on your own disk, stay with llama.cpp. If you want to prototype an agent on a laptop without a GPU, or serve several users at once without managing a box, the hosted route is simpler. Because both speak the same protocol, you can develop against one and switch to the other with an environment variable.

Prompts that worked against a small quantized model on your laptop usually carry over, but a few habits change. Local setups often force you to keep prompts short because context is limited by memory. Here the window is 100,000 tokens, so you can keep a longer system prompt, longer chat history and more retrieved text. That freedom is easy to overspend, so set a budget per call and measure it.

Chat templates are another difference. With llama.cpp you sometimes have to pick a template that matches the model file. A hosted OpenAI-style endpoint applies the right template on the server, so you send plain messages with roles and let it handle the formatting. If you had a hand-written template in your LangChain code to work around a local quirk, delete it and test again.

Finally, sampling settings. temperature, top_p, stop, seed and the repetition penalties are passed through, so your tuned values carry over as parameters. Keep a note of which settings you used for each test, because comparing two runs with different seeds tells you nothing.

Install and connect

You need the LangChain OpenAI integration, which includes the ChatOpenAI class:

pip install langchain-openai langchain-core
export LLAMAAPI_KEY="paste-your-key-here"

Create a key on the API key page if you do not have one yet. New users can claim $0.50 of trial credit there with one click. Then build the model object:

import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.llamaapi.top/v1",
    api_key=os.environ["LLAMAAPI_KEY"],
    temperature=0.7,
)

print(llm.invoke("Write a two-line riddle about a lighthouse.").content)

To compare with a local setup, the only difference is the constructor: a local llama-server would use something like base_url="http://localhost:8080/v1" and a dummy key. Keep the URL in an environment variable and the rest of the code does not care which one it is talking to.

A small chain with streaming

Prompts, parsers and the pipe operator work exactly as with any other chat model. Streaming uses server-sent events under the hood, and the API sends token usage at the end of the stream.

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a concise writing assistant."),
    ("user", "Summarize this in {n} bullet points:\n\n{text}"),
])

chain = prompt | llm | StrOutputParser()

for piece in chain.stream({"n": 3, "text": "Long text goes here."}):
    print(piece, end="", flush=True)

One detail matters for concurrency planning. A streamed request occupies its slot until the stream finishes, so a slow consumer that reads tokens lazily keeps a slot busy for longer than a non-streamed call would.

Tool calling and agents

The API supports tools, tool_choice, streamed tool_calls, and tool results sent back as messages with role: "tool". In LangChain you declare tools with the @tool decorator and attach them with bind_tools:

from langchain_core.tools import tool

@tool
def word_count(text: str) -> int:
    '''Count the words in a piece of text.'''
    return len(text.split())

llm_tools = llm.bind_tools([word_count])
msg = llm_tools.invoke("How many words are in: the quick brown fox?")
print(msg.tool_calls)

If tool_calls is non-empty, run the matching function and pass the result back as a tool message. Agent helpers such as LangGraph's prebuilt ReAct agent do this loop for you, and they take the same llm object. Whatever helper you use, set a step limit so a confused model cannot loop forever on your balance. Check what the model returned before you trust the arguments: validate them the way you would validate user input.

JSON output

JSON mode is available through response_format. With LangChain, pass it through model_kwargs:

json_llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.llamaapi.top/v1",
    api_key=os.environ["LLAMAAPI_KEY"],
    temperature=0,
    model_kwargs={"response_format": {"type": "json_object"}},
)

out = json_llm.invoke(
    "Return a JSON object with keys name and mood for a grumpy dwarf character."
)
print(out.content)

Say the word JSON in the prompt and describe the keys you expect, then parse the result with json.loads and handle a parse error with a retry. JSON mode guarantees valid syntax in the normal case, not that the keys match your schema, so validate the shape yourself.

Batching, limits and troubleshooting

A full key allows 8 concurrent requests and 300 requests per minute. LangChain's batch runs inputs in parallel, so cap it:

inputs = [{"n": 2, "text": t} for t in documents]
results = chain.batch(inputs, config={"max_concurrency": 6})

Staying at 6 leaves room for a second job on the same key. If a limit is exceeded the API answers HTTP 429. The code rate_limited refers to requests per minute and concurrency to simultaneous requests. A 429 with Retry-After: 5 means temporary overload. The ChatOpenAI class has a max_retries option, which handles occasional 429s without extra code. Trial keys are stricter, with 2 concurrent requests and 60 per minute, so use max_concurrency of 2 while testing. The full numbers and billing are on the pricing page.

Troubleshooting checklist

  • Connection errors on every call. Check that the base URL ends with /v1 and has no trailing path such as /chat/completions; the client adds that itself.
  • Authentication failures. The key must be passed as api_key, and an old OPENAI_API_KEY in your environment can shadow it if you rely on defaults.
  • Unknown model. The only model ID is uncensored. Names such as a vendor's model are not available here.
  • Embedding calls fail. Expected, since there is no embeddings endpoint. Swap in a different embedding class.
  • Intermittent 429. Lower max_concurrency or let max_retries do its work.

If a chain works locally and fails here, print the raw request your code sends. The usual cause is a parameter that only a local server understood. Start your key from the key page and compare against the minimal example above.

The RAG caveat: embeddings

This API serves chat completions only. It has no embeddings endpoint, so OpenAIEmbeddings pointed at this base URL will fail. For retrieval-augmented generation, compute embeddings elsewhere, for example with a local sentence-embedding model, and use this API only for the generation step. The vector store and retriever stay the same either way, because LangChain separates the embedding model from the chat model.

The 100,000-token window is generous for retrieval. You can pass many retrieved chunks, but you pay for every input token at $0.15 per 1M, so sending 20,000 tokens of context costs 20,000 x $0.15 / 1,000,000 = $0.003 per call. Trim chunks to what answers the question. More details on base URL and model settings are in the docs.

Questions and answers

Can LangChain use llama.cpp and a hosted API at the same time?

Yes. Create two ChatOpenAI objects with different base URLs, one for your local llama-server and one for the hosted endpoint, and choose per task.

Which LangChain class should I use for this API?

Use ChatOpenAI from langchain-openai with base_url set to https://api.llamaapi.top/v1 and model set to uncensored.

Does the API provide embeddings for a vector store?

No. It is text chat only, so use a separate embedding model for retrieval.

Is tool calling supported in LangChain?

Yes. Declare tools with the tool decorator, attach them with bind_tools, and return results as tool messages.

Your key is one form away

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