EN ▾
Get API key

LLM Chain in LangChain with a Custom Endpoint

An LLM chain in LangChain is a prompt, a model and an output parser piped together, and pointing it at a custom endpoint takes two changed arguments. This article shows the working code for Python and Node, with streaming, tool calling and JSON mode.

Updated

Three linked glowing blocks forming a chain that streams output into a terminal, representing a LangChain pipeline

Key points

  • Use ChatOpenAI with a custom base URL, the key as api_key and the model ID uncensored.
  • Compose chains with the pipe operator: prompt | llm | parser. The old LLMChain class is deprecated.
  • Streaming, tool calling and JSON mode all pass through the OpenAI-compatible API.
  • Keep batch concurrency at or below 8 and handle HTTP 429 with a retry.

What a chain is now

In older tutorials, an LLM chain meant the LLMChain class: a prompt template and a model wrapped in one object. That class is deprecated. Current LangChain code builds the same thing with the LangChain Expression Language (LCEL), where each step is a runnable and you join them with |.

The minimal chain has three parts:

  1. A prompt template that turns your input variables into messages.
  2. A chat model that sends those messages to an API.
  3. An output parser that turns the model reply into a plain string or an object.

Because the model step only needs an OpenAI-style chat endpoint, you can aim it at any compatible server. The service in this article exposes POST /v1/chat/completions and GET /v1/models at https://api.nsfwllm.top/v1, with one model ID, uncensored. It is an open-weight model run by an independent provider, tuned to answer without content refusals for lawful adult use. It is not an official API of any model vendor.

Install and configure

Install the packages. The OpenAI integration lives in its own package, separate from langchain-core.

pip install langchain-openai langchain-core
export NSFWLLM_API_KEY="sk-your-key"

Get a key from the API key page. New accounts can claim $0.50 of trial credit there, which is plenty for everything in this article. The trial key allows 2 concurrent requests and 60 requests per minute, so keep the examples sequential until you top up.

Now create the model object. The two arguments that matter are base_url and api_key; the key is sent as Authorization: Bearer by the underlying SDK.

import os
from langchain_openai import ChatOpenAI

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

print(llm.invoke("Reply with the single word: ready").content)

If that prints a reply, the connection works. If you see a 401, the key is wrong or has a stray space. If you see a connection error, check that the base URL ends in /v1 and has no trailing path.

Build the chain

Here is a complete chain that rewrites a paragraph in a requested tone. Note that the prompt has two input variables, and the chain accepts a dict with those keys.

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

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are an editor. Rewrite the text in a {tone} tone. Return only the rewritten text."),
    ("human", "{text}"),
])

chain = prompt | llm | StrOutputParser()

result = chain.invoke({
    "tone": "dry and understated",
    "text": "The meeting ran long and nobody got what they wanted.",
})
print(result)

Every runnable in the chain shares the same methods: invoke, stream and batch, plus async versions. That is the main gain over the old class. You can add a step, such as a second prompt that critiques the first answer, by piping another prompt and model on the end.

Chaining two calls

A common pattern is to feed the first answer into a second prompt. Wrap the first chain in a dict so its output lands in a named variable.

critic_prompt = ChatPromptTemplate.from_template(
    "List three weaknesses of this draft, one per line:\n\n{draft}"
)

two_step = {"draft": chain} | critic_prompt | llm | StrOutputParser()
print(two_step.invoke({"tone": "formal", "text": "We shipped late again."}))

Each model step is a separate billed request. At $0.15 per 1M input tokens and $0.50 per 1M output tokens, a two-step chain with 400 input and 150 output tokens in each step costs 2 x (400 x $0.15 + 150 x $0.50) / 1M, which is $0.00027. Prices are listed on the pricing page.

Streaming

The endpoint streams over server-sent events when stream is true, and LangChain turns that into an iterator. You do not set the flag yourself; call stream on the chain.

for piece in chain.stream({"tone": "warm", "text": "Your order is delayed."}):
    print(piece, end="", flush=True)
print()

Because the parser is a string parser, each item is a plain text fragment. Usage is reported at the end of the stream, and one detail matters for load: a streamed request holds its concurrency slot until the stream finishes. If your UI opens many streams and users abandon them without closing, you can run into the concurrency limit sooner than the request rate would suggest.

Tool calling and JSON mode

Both features pass through the compatible API, so the standard LangChain helpers work. For tools, define a function with the @tool decorator and bind it to the model.

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")

for call in msg.tool_calls:
    print(call["name"], call["args"])
    print(word_count.invoke(call["args"]))

The model returns the tool call, your code runs the function, and you send the result back as a tool message. Open-weight models follow tool schemas less reliably than the largest hosted ones, so keep schemas small, give each argument a clear description and validate arguments before you run anything with side effects.

For structured output, JSON mode is the simplest route. Pass the response format as a bound argument and mention JSON in the prompt.

import json

json_llm = llm.bind(response_format={"type": "json_object"})

json_prompt = ChatPromptTemplate.from_messages([
    ("system", "Return a JSON object with keys title and tags (a list of strings)."),
    ("human", "{text}"),
])

data = (json_prompt | json_llm | StrOutputParser()).invoke(
    {"text": "A short story about a lighthouse keeper who collects radio signals."}
)
print(json.loads(data))

JSON mode guarantees well-formed JSON in the normal case, not that the keys match your schema. Check the keys after parsing, and retry once if they are missing.

Node version

The JavaScript package has the same shape. The base URL goes inside the configuration object.

import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";

const llm = new ChatOpenAI({
  model: "uncensored",
  apiKey: process.env.NSFWLLM_API_KEY,
  configuration: { baseURL: "https://api.nsfwllm.top/v1" },
});

const prompt = ChatPromptTemplate.fromMessages([
  ["system", "Summarize the text in one sentence."],
  ["human", "{text}"],
]);

const chain = prompt.pipe(llm).pipe(new StringOutputParser());
console.log(await chain.invoke({ text: "LCEL chains join prompts, models and parsers." }));

Streaming in Node is an async iterator, so the pattern is a plain loop over the chain output. The same advice applies as in Python: close or abort streams you no longer need, because an open stream keeps its concurrency slot.

const stream = await chain.stream({ text: "Streaming returns text fragments as they arrive." });
for await (const piece of stream) {
  process.stdout.write(piece);
}

Tool binding and JSON mode follow the Python shapes: call bindTools on the model for tools, or llm.bind({ response_format: { type: "json_object" } }) for JSON. Package versions move quickly, so if an argument name differs from what you see here, check the release notes of the LangChain version you installed. The wire format to the endpoint stays the standard chat completions request.

Keeping chat history in a chain

A chain has no memory by default; each invoke is independent. For a chat, put a placeholder for past messages in the prompt and pass the history yourself. This is the most transparent approach, and it keeps token use visible.

from langchain_core.prompts import MessagesPlaceholder
from langchain_core.messages import HumanMessage, AIMessage

chat_prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a concise technical assistant."),
    MessagesPlaceholder("history"),
    ("human", "{question}"),
])
chat_chain = chat_prompt | llm | StrOutputParser()

history = []
for q in ["What is a runnable?", "Give a one-line example."]:
    answer = chat_chain.invoke({"history": history, "question": q})
    history += [HumanMessage(q), AIMessage(answer)]
    print(answer)

The whole list is sent on each call, so input tokens grow with each turn. At $0.15 per 1M input tokens, a 10,000-token history adds $0.0015 to every request. That is small, but it adds up in a busy app, so trim the list once it passes a size you choose. The context window is 100,000 tokens, prompt plus completion, so there is a lot of room before you must trim for fit rather than cost.

Debugging a chain that misbehaves

When output looks wrong, find which step is at fault before changing the prompt.

  • Print the rendered prompt. Call prompt.invoke({...}) alone to see the exact messages. Missing variables and stray braces show up here. Literal braces in a template must be doubled.
  • Call the model directly. If llm.invoke works but the chain fails, the problem is in the prompt or the parser.
  • Check the response headers. Each response includes X-Request-Id, which is the value to quote if you contact support, and X-Balance-USD for the remaining credit.
  • Lower the temperature. If a parser breaks on odd formatting, set temperature=0 and use a fixed seed while you debug.
  • Set a stop sequence. If the model keeps writing past the answer, pass stop through llm.bind(stop=[...]).

Limits, batches and errors

A full key allows 8 concurrent requests and 300 requests per minute. The trial key allows 2 and 60. When you call batch on a chain, LangChain runs inputs in parallel, so cap the parallelism to stay under the concurrency limit.

inputs = [{"tone": "plain", "text": t} for t in ["First note.", "Second note.", "Third note."]]
outputs = chain.batch(inputs, config={"max_concurrency": 6})

Going over a limit returns HTTP 429. The error code is rate_limited when you exceed requests per minute and concurrency when too many requests are in flight. Temporary overload also returns 429, with a Retry-After: 5 header. The OpenAI client retries a few times by default, and you can raise it with the max_retries argument on ChatOpenAI. A refused or failed request is not charged, so retries do not cost you for the failed attempts.

For the request format behind all of this, the quickstart lists the parameters that are passed through: temperature, top_p, stop, seed and the penalties. The context window is 100,000 tokens, prompt plus completion, which leaves room for long retrieval contexts in a chain. The model is text only, so no image or embedding steps will work against this endpoint; use a separate embeddings provider if your chain needs retrieval.

Questions and answers

Is LLMChain still the right way to build a chain?

No. LLMChain is deprecated in LangChain. Build chains with the pipe operator, as in prompt | llm | parser, which gives you invoke, stream and batch on the same object.

Which model ID do I pass to ChatOpenAI?

Use uncensored. The base URL is https://api.nsfwllm.top/v1 and the key goes in api_key.

Can I use the same chain with streaming and tools?

Yes. Streaming, tool calling and JSON mode are all supported through the OpenAI-compatible API, so LangChain's stream, bind_tools and response_format work unchanged.

Why do I get 429 errors in a batch?

You are over the concurrency or request limit. Set max_concurrency to 8 or lower on a full key, and lower on a trial key, then retry after the Retry-After delay.

Your key is one form away

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

Get API key