Uncensored LLM API With LangChain: ChatOpenAI Setup
LangChain talks to any OpenAI-compatible server through ChatOpenAI, so connecting an uncensored model takes three settings: a base URL, a key and a model name. This page shows the full setup and the parts that usually go wrong.
Updated

No card needed. After sign-up, claim $0.50 of free test credit with one click (once per person).
Get API keyThe short answer
If you came looking for an uncensored llm api langchain can use, the answer is that LangChain does not need a special integration. The ChatOpenAI class from langchain-openai accepts a custom base URL, and our endpoint speaks the OpenAI chat completions protocol. You change the URL, paste your key, and set the model name to uncensored.
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.uncensoredllm.top/v1",
api_key="YOUR_API_KEY",
temperature=0.8,
)
print(llm.invoke("Write a two-sentence villain monologue.").content)
That is the whole connection. Everything else in this article is about using LangChain features on top of it: chains, streaming, tools, structured output and sensible retry behaviour. The model behind the endpoint is one open-weight model, tuned to answer without content refusals for lawful adult use. It is not an official API of any model vendor, and it is text only.
Install and configure
Install the package and keep the key out of your source files:
pip install -U langchain-openai langchain-core
export UNCENSORED_API_KEY="your key here"
Get the key from the API key page after signing in with Google or with email and password. New accounts can claim $0.50 of trial credit with one click on that page. It lasts 7 days, needs no payment method and is limited to one per person, which is plenty to run every snippet below.
Then read the key from the environment in code:
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.uncensoredllm.top/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
Two details trip people up. First, the base URL already ends in /v1, so do not add /chat/completions yourself. Second, if OPENAI_API_KEY or OPENAI_BASE_URL is set in your shell, an older LangChain version may pick those up instead of your arguments. Passing base_url and api_key explicitly avoids the confusion, and it keeps your real OpenAI key from being sent to the wrong host.
Check the connection before building anything bigger. The GET /v1/models route lists the model, and a single invoke call confirms that chat completions work. The quickstart in the docs has the same checks in curl form.
Prompts, chains and streaming
A prompt template piped into the model is the usual building block. The roleplay-style system prompt below is a good test, because it is the kind of request that tends to get refused elsewhere:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_messages([
("system", "You are {persona}. Stay in character and write in {style}."),
("human", "{request}"),
])
chain = prompt | llm | StrOutputParser()
text = chain.invoke({
"persona": "a cynical smuggler captain in a space opera",
"style": "short, punchy paragraphs",
"request": "Describe the first meeting with a nervous new crew member.",
})
print(text)
For streaming, use stream on the chain. The server sends Server-Sent Events when stream: true is set, and LangChain turns each event into a chunk:
for chunk in chain.stream({
"persona": "a dry-witted lighthouse keeper",
"style": "first person, past tense",
"request": "Tell me about the worst storm you remember.",
}):
print(chunk, end="", flush=True)
The async versions, ainvoke and astream, work the same way. One thing to remember: a streamed request holds one of your concurrency slots until the stream ends, not until the first token arrives. If you open eight streams and forget to consume one of them, that slot stays busy.
Tool calling through bind_tools
The endpoint supports tools, tool_choice, streamed tool_calls and tool results sent back with role: "tool". In LangChain that maps onto bind_tools and ToolMessage.
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, ToolMessage
@tool
def roll_dice(sides: int) -> int:
'''Roll one die with the given number of sides.'''
import random
return random.randint(1, sides)
llm_tools = llm.bind_tools([roll_dice])
messages = [HumanMessage("Roll a twenty-sided die for my attack.")]
ai = llm_tools.invoke(messages)
messages.append(ai)
for call in ai.tool_calls:
result = roll_dice.invoke(call["args"])
messages.append(ToolMessage(content=str(result), tool_call_id=call["id"]))
final = llm_tools.invoke(messages)
print(final.content)
This is a single round of the loop. For an agent that may call several tools in a row, repeat the invoke, run, append cycle until ai.tool_calls comes back empty, and put a hard cap on the number of rounds so a confused model cannot loop forever. If you use LangGraph, its prebuilt tool-calling agent accepts the same llm object.
Tool arguments arrive as JSON generated by the model. Treat them like user input: validate types, clamp numbers and never pass them straight to a shell or a database query.
Structured output with JSON mode
JSON mode is available through response_format: {"type": "json_object"}. In LangChain you can pass it as a model keyword argument, or let with_structured_output request it for you:
from pydantic import BaseModel
class Character(BaseModel):
name: str
role: str
secret: str
structured = llm.with_structured_output(Character, method="json_mode")
result = structured.invoke(
"Invent one character for a noir mystery. "
"Reply as JSON with the keys name, role and secret."
)
print(result.name, "-", result.role)
With method="json_mode" the schema is not enforced by the server, so the prompt has to name the keys, as above. The Pydantic class then validates what comes back. If validation fails, the usual fix is a retry with a slightly lower temperature, not a longer prompt. Also set a sensible max_tokens for structured calls: a reply that hits the limit mid-object is invalid JSON no matter how well the model behaved.
Node.js with @langchain/openai
The JavaScript package takes the base URL through a configuration object:
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "uncensored",
apiKey: process.env.UNCENSORED_API_KEY,
configuration: { baseURL: "https://api.uncensoredllm.top/v1" },
temperature: 0.8,
});
const reply = await llm.invoke("Give me three names for a haunted tavern.");
console.log(reply.content);
Streaming uses await llm.stream(...) and a for await loop. Tools go through bindTools with a Zod schema, which LangChain converts into the JSON schema the API expects.
Concurrency, retries and cost
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. LangChain's batch method is where you are most likely to hit those numbers, because it fans out in parallel. Cap it:
inputs = [{"persona": "a pirate", "style": "rhymed couplets",
"request": f"Write toast number {i}."} for i in range(40)]
results = chain.batch(inputs, config={"max_concurrency": 6})
Keeping the value below 8 leaves room for other traffic on the same key. For the occasional 429, ChatOpenAI(max_retries=4) is enough in most apps, since the OpenAI client backs off between attempts and honours Retry-After. The API returns 429 with code rate_limited when you exceed the per-minute count and concurrency when too many requests overlap. Temporary overload also returns 429 with Retry-After: 5. If you are weighing this against running models locally, see the page on uncensored Ollama models. The numbers live on the pricing page.
Cost is easy to estimate. Input is $0.15 per 1M tokens and output is $0.50 per 1M. A chain call with 2,000 input tokens and 500 output tokens costs 2,000 x $0.15 / 1,000,000 = $0.0003 for input plus 500 x $0.50 / 1,000,000 = $0.00025 for output, so $0.00055 in total. A thousand such calls come to $0.55. Failed or refused requests are not charged, so retries on errors do not add to the bill.
Billing is prepaid credit with no subscription, topped up in whole amounts from $20 to $500 by crypto (USDT on TRC20, USDC on Base). Credit never expires, and prompts are not used for training.
Common problems
- 404 or "not found": the base URL is missing
/v1, or has/chat/completionsappended. - 401: the key is wrong, or an environment variable is overriding your argument.
- Model not found: the model name must be exactly
uncensored. - Context errors on long chats: the window is 100,000 tokens for prompt plus completion. Trim memory buffers or summarise old turns before you reach it.
- Parameters ignored: temperature, top_p, stop, seed and the penalties are passed through, so they should work. Unknown provider-specific fields are not documented, so do not rely on them.
One rule applies whatever framework you use: the service refuses any sexual content involving minors, and no prompt engineering changes that. For everything else that is lawful adult use, you now have a working LangChain connection.
More guides
Questions and answers
Do I need a special LangChain package for this API?
No. The standard langchain-openai package (or @langchain/openai for Node) works, because the endpoint is OpenAI-compatible. Set base_url, api_key and model to uncensored.
Does LangChain tool calling work with this endpoint?
Yes. The API supports tools, tool_choice and streamed tool_calls, so bind_tools and ToolMessage work as they do with any OpenAI-style model.
What is the context window?
100,000 tokens for prompt plus completion. max_tokens is optional, and the completion can use whatever part of the window the prompt leaves free.
How do I try it without paying?
Sign up, then claim the $0.50 trial credit on the API key page. It needs no payment method, lasts 7 days and is limited to one per person.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.