The minimal working setup
LangChain does not need a special integration for an OpenAI-compatible server. The langchain-openai package ships ChatOpenAI, which accepts a custom base URL. Install it with pip install langchain-openai, put your key in an environment variable, and run:
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.uncensoredmodel.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
temperature=0.7,
)
reply = llm.invoke("Write a two-line opening for a noir detective story.")
print(reply.content)
That is the whole integration. The service implements POST /v1/chat/completions and GET /v1/models, which is what ChatOpenAI uses. If you do not have a key yet, create an API key; new accounts can claim $0.50 of trial credit with one click, no card needed.
A word on the name. The model is hosted, not run on your machine, so it is not a local model in the strict sense. What makes it feel local to LangChain is that it speaks the same protocol as a self-hosted server like vLLM or llama.cpp's server mode. Code written for one moves to the other by changing three arguments.
Explicit arguments versus environment variables
You may see guides that set OPENAI_API_BASE and OPENAI_API_KEY and then call ChatOpenAI() with no arguments. That works in many versions, but the variable names have changed across releases and some stacks read them in other places, so a call can silently go to the wrong host. Passing base_url and api_key in the constructor removes that doubt.
One more habit to keep: always set model="uncensored". If you leave the default, LangChain sends an OpenAI model name that this server does not know, and you get an error about an unknown model. You can confirm what the server lists with a quick check:
curl https://api.uncensoredmodel.cc/v1/models -H "Authorization: Bearer $UNCENSORED_API_KEY"
The response should include the ID uncensored. If you get 401, the key is missing or mistyped; the header has to read Authorization: Bearer YOUR_KEY, which ChatOpenAI builds from api_key.
Streaming tokens into your app
The server supports streaming over SSE and sends usage at the end. In LangChain you call .stream() and get message chunks as they arrive:
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.uncensoredmodel.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
for chunk in llm.stream("Describe a harbor town at dawn in one paragraph."):
print(chunk.content, end="", flush=True)
There is one operational detail. A streamed request holds one of your concurrency slots until the stream ends. If your UI lets users cancel, close the stream properly, or the slot stays occupied and the next request may come back with a 429 concurrency error.
Prompt templates and chains
Chains built with the pipe syntax need no changes. The model object is one step among others:
import os
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.uncensoredmodel.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a character in an interactive story. Stay in voice."),
("human", "Setting: {setting}\nReader says: {line}"),
])
chain = prompt | llm | StrOutputParser()
print(chain.invoke({"setting": "a lighthouse in a storm", "line": "Who are you?"}))
The system message is where you set the persona. Because this model is tuned to answer without content refusals for lawful adult use, you can write fiction and roleplay prompts without wrapping them in workarounds. Content involving minors is not allowed, and that limit is fixed.
Tool calling with bind_tools
Tool calling follows the OpenAI format: tools, tool_choice, streamed tool_calls, and results returned as messages with role: "tool". LangChain wraps that in bind_tools.
import os
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
@tool
def order_status(order_id: str) -> str:
'''Return the shipping status of an order.'''
return "shipped, arriving Thursday"
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.uncensoredmodel.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
llm_tools = llm.bind_tools([order_status])
messages = [HumanMessage("Where is order 1042?")]
ai = llm_tools.invoke(messages)
messages.append(ai)
for call in ai.tool_calls:
result = order_status.invoke(call["args"])
messages.append(ToolMessage(content=result, tool_call_id=call["id"]))
final = llm_tools.invoke(messages)
print(final.content)
Check ai.tool_calls before you loop, because the model may answer directly without calling anything. For agents that run several rounds, LangGraph's prebuilt agent handles the loop for you and uses the same chat model object. Keep tool descriptions short and specific; vague docstrings are the usual reason a tool is not chosen.
JSON output
JSON mode is available through response_format. In LangChain you can bind it directly or use with_structured_output with the JSON mode method:
import os
from pydantic import BaseModel
from langchain_openai import ChatOpenAI
class Character(BaseModel):
name: str
role: str
secret: str
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.uncensoredmodel.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
structured = llm.with_structured_output(Character, method="json_mode")
out = structured.invoke(
"Return JSON with the keys name, role and secret for a ship's engineer called Mara."
)
print(out)
JSON mode guarantees valid JSON syntax, not your schema. Mention the key names in the prompt as above, and let the Pydantic model reject anything that does not fit. If you do not need a typed object, llm.bind(response_format={"type": "json_object"}) gives you the raw JSON string.
Batching, limits and 429 errors
LangChain's .batch() can fire many requests at once, which collides with the per-key limits. A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60. Past those, the API returns HTTP 429 with rate_limited (requests per minute) or concurrency (too many at once). Under temporary overload it also answers 429 with Retry-After: 5.
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.uncensoredmodel.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
max_retries=4,
timeout=120,
)
questions = [f"Give me one name for tavern number {i}." for i in range(40)]
answers = llm.batch(questions, config={"max_concurrency": 8})
The max_concurrency value of 8 matches a full key; use 2 while you are on the trial. max_retries makes the underlying client back off and try again after a 429. The response headers (X-RateLimit-Limit-Requests, X-RateLimit-Limit-Concurrency, X-Balance-USD) tell you the current limits and your balance, which is handy for a dashboard or a low-credit warning.
On cost: input is $0.15 and output $0.50 per 1M tokens. The batch above sends 40 short prompts of about 20 tokens and receives about 15 tokens each, so it uses roughly 800 input and 600 output tokens: $0.00012 plus $0.0003, about $0.0004 in total. More detail is on the pricing page.
The same thing in JavaScript
LangChain.js uses a nested option for the base URL:
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "uncensored",
apiKey: process.env.UNCENSORED_API_KEY,
configuration: { baseURL: "https://api.uncensoredmodel.cc/v1" },
temperature: 0.7,
});
const res = await llm.invoke("Give me three names for a desert caravan.");
console.log(res.content);
Everything above (stream, bindTools, batch) carries over with the camelCase names.
Keeping chat history under control
Every call carries the full message list, and input tokens are billed on each one. A LangChain chat that appends every turn to memory will cost more and respond slower the longer it runs. The simplest defence is to trim before you call the model. trim_messages from langchain_core.messages keeps the system message and the newest turns up to a token budget:
import os
from langchain_core.messages import trim_messages
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.uncensoredmodel.cc/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
trimmer = trim_messages(
max_tokens=6000,
strategy="last",
token_counter=llm,
include_system=True,
)
chain = trimmer | llm
Token counts for a model that is not from OpenAI are estimates, so leave a margin below your real limit. A 6,000-token budget with a 300-token reply costs, per request, 6,000 x $0.15 / 1M = $0.0009 for input and 300 x $0.50 / 1M = $0.00015 for output, about $0.00105. A budget that size is a choice about cost and memory of the story, not a technical limit; the window itself allows 100,000 tokens.
A short debugging checklist
Most failures when you point LangChain at a custom endpoint come from a few causes, and each one has a quick test.
- 404 or "model not found". The model name is wrong. Set
model="uncensored"and confirm it appears in the/v1/modelsresponse. - 401. The key is empty because an environment variable was not exported in the shell that runs your script. Print
bool(os.environ.get("UNCENSORED_API_KEY")). - Connection goes to the wrong host. A leftover
OPENAI_API_BASEvalue from another project can override your intent. Passbase_urlexplicitly. - 429 with
concurrency. Too many parallel calls or unclosed streams. Lowermax_concurrencyand close streams. - Empty or odd JSON. You asked for JSON mode but the prompt never mentioned JSON or the key names. Add both.
- Request too large. The body limit is 8 MB. Large pasted documents belong in chunks, not one message.
When you report a problem to support, include the X-Request-Id response header. It lets the operator find the exact request. The pricing page and the docs explain billing details, and refused or failed requests are not charged.
What LangChain cannot get from this API
The service is text chat only. It has no embeddings endpoint, so a retrieval pipeline needs a separate embedding model from somewhere else, or a local one, with this model used only for the answering step. It also has no image, audio or video generation and no fine-tuning. The context window is 100,000 tokens for prompt plus completion, which is plenty for retrieved chunks, but long chat histories in a memory class should still be trimmed to keep input costs predictable.
For a comparison with other uncensored options and how this one fits, read our overview of uncensored LLM APIs, and keep the API documentation open for parameters such as stop, seed and the penalties, which pass straight through.
