NSFW LLM APILangChain for LLM Application Development: Setup
LangChain for LLM Application Development: Setup
LangChain works with this API by changing the base URL and key. This page gives working code for chains, streaming, tool calling, JSON mode and parallel batches.

Key points
- Use ChatOpenAI with base_url set to the API and model set to uncensored.
- Streaming, tool calling and JSON mode all go through the standard OpenAI format.
- Keep batch concurrency under 8 on a full key and 2 on a trial key to avoid 429 errors.
- The API is text only, so embeddings and image tools need another source.
Short version: two parameters and a model name
Using LangChain for LLM application development with this API takes two changes to the standard OpenAI wiring: point base_url at https://api.nsfwllmapi.com/v1 and use your key from this site. The model ID is uncensored. Everything else in LangChain (prompt templates, output parsers, chains, tools, streaming) keeps working because the service speaks the OpenAI chat completions format.
The ChatOpenAI class in the langchain-openai package is the one to use. The endpoint exposes POST /v1/chat/completions and GET /v1/models, so anything in LangChain that stays on chat completions works. Features that depend on other vendors' services, such as image generation, audio or embeddings, do not, because this API is text only.
If you do not have a key yet, the API key page offers a one-click $0.50 trial credit after sign-up. That is plenty for every example below.
pip install -U langchain-openai langchain-core
export LLM_API_KEY="paste-your-key-here"import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.nsfwllmapi.com/v1",
api_key=os.environ["LLM_API_KEY"],
temperature=0.8,
)
reply = llm.invoke("Write a two-sentence opening for a gothic mystery.")
print(reply.content)
print(reply.usage_metadata)What each setting does
Four constructor arguments matter on day one:
model="uncensored"is the only model on the endpoint. You can confirm it withGET /v1/models.base_urlredirects every request from OpenAI to this API. In older LangChain releases the same setting is calledopenai_api_base.api_keybecomes theAuthorization: Bearerheader. Read it from an environment variable so it never lands in a repository.temperature,top_p,stop,seedand the frequency and presence penalties are passed through to the model. For creative writing, a temperature between 0.7 and 1.0 is a common range; for tool calls and JSON, drop it to 0 to 0.3.
The context window is 100,000 tokens, prompt and completion together, and max_tokens is optional. You will rarely need it in a chain unless you want to cap cost or reply length. Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, so a prompt-template experiment that sends 2,000 tokens in and gets 500 back costs 2,000 x 0.15 / 1,000,000 + 500 x 0.50 / 1,000,000 = $0.00055. The pricing page lists top-ups and bonuses.
A habit that pays off in larger projects: keep prompts in their own module or files rather than inside functions, and build the model object in one place. When the whole app asks a single factory for its LLM, changing the temperature, the key or the base URL later is a one-line edit, and tests can swap in a fake model without touching the chains. It also makes it obvious how many different prompts your app really sends, which matters because every one of them is billed by the token.
One note on the printed usage_metadata in the first snippet: it carries input, output and total token counts, which is the quickest way to see what a chain really sends once templates and history are filled in.
Building a chain
A chain is where LangChain starts to pay for itself. The expression language joins a prompt template, the model and an output parser with the | operator, so the same chain can be invoked, streamed or batched without rewriting it.
import os
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
llm = ChatOpenAI(model="uncensored", base_url="https://api.nsfwllmapi.com/v1",
api_key=os.environ["LLM_API_KEY"], temperature=0.8)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a fiction editor. Reply in {language}. Be specific and brief."),
("human", "Give three ways to raise the tension in this scene:\n\n{scene}"),
])
chain = prompt | llm | StrOutputParser()
print(chain.invoke({
"language": "English",
"scene": "Two rivals share a lift that stops between floors.",
}))The template fills {language} and {scene}, the model answers, and StrOutputParser turns the message object into a plain string. Swapping the parser for a JSON parser, or adding a second prompt that critiques the first answer, changes the chain but not the way it talks to the API.
Keeping the history under control
With a chat-style app you will pass a growing list of messages. Each turn resends the whole list, and you pay for that input every time, so cap it. LangChain's trim_messages helper does this inside the chain:
import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import trim_messages
llm = ChatOpenAI(model="uncensored", base_url="https://api.nsfwllmapi.com/v1",
api_key=os.environ["LLM_API_KEY"])
trimmer = trim_messages(
max_tokens=20, # counted in messages here, not tokens
token_counter=len,
strategy="last",
include_system=True,
start_on="human",
)
chain = trimmer | llmHere the counter is simply len, so the cap is 20 messages. For a real token budget, pass a token counter that matches your needs. Staying well below 100,000 tokens also keeps requests fast and cheap.
Streaming
Streaming uses server-sent events (stream: true under the hood) and LangChain exposes it through .stream() and .astream(). Setting stream_usage=True asks for token counts in the final chunk, which this API sends at the end of a stream.
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="uncensored", base_url="https://api.nsfwllmapi.com/v1",
api_key=os.environ["LLM_API_KEY"], stream_usage=True)
final = None
for chunk in llm.stream("Describe a lighthouse at dusk in one paragraph."):
print(chunk.content, end="", flush=True)
final = chunk if final is None else final + chunk
print()
print(final.usage_metadata)Streaming has one operational cost that is easy to miss: a streamed request occupies its concurrency slot until the stream ends. A full key allows 8 concurrent requests, so eight slow readers on eight open streams will block a ninth call. If your app hands streams to browsers, make sure you close them when a user leaves the page, or the slot stays busy.
Tool calling
The API supports tools, tool_choice, streamed tool_calls, and tool results sent back as messages with the role tool. In LangChain that maps to bind_tools, the tool_calls list on the AI message, and ToolMessage. The loop below runs one tool call by hand, which is the clearest way to see the mechanics before you reach for an agent framework.
import os
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, ToolMessage
@tool
def count_words(text: str) -> int:
"""Count the words in a piece of text."""
return len(text.split())
llm = ChatOpenAI(model="uncensored", base_url="https://api.nsfwllmapi.com/v1",
api_key=os.environ["LLM_API_KEY"], temperature=0)
llm_with_tools = llm.bind_tools([count_words])
messages = [HumanMessage("How many words are in: the quick brown fox jumps?")]
ai = llm_with_tools.invoke(messages)
messages.append(ai)
for call in ai.tool_calls:
result = count_words.invoke(call["args"])
messages.append(ToolMessage(content=str(result), tool_call_id=call["id"]))
final = llm_with_tools.invoke(messages)
print(final.content)Three habits help with tool calling on any open-weight model. Write a clear docstring, since it becomes the tool description the model reads. Keep argument names plain and descriptive. And set the temperature low, because sampling noise is the main reason a model invents an argument. If a tool call comes back malformed, validate it, send the error text back as a ToolMessage and let the model retry once instead of crashing the run.
JSON mode and structured output
JSON mode is available through response_format: {"type": "json_object"}. In LangChain you attach it with .bind():
import json, os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="uncensored", base_url="https://api.nsfwllmapi.com/v1",
api_key=os.environ["LLM_API_KEY"], temperature=0.3)
json_llm = llm.bind(response_format={"type": "json_object"})
msg = json_llm.invoke([
("system", "Answer with a JSON object that has the keys title (string) and tags (list of strings)."),
("human", "Summarize a heist story set on a night train."),
])
data = json.loads(msg.content)
print(data["title"], data["tags"])JSON mode asks the model for a single valid JSON object. It does not enforce your keys, so describe the shape in the system message, parse the result and validate it with Pydantic or a schema library. Treat the first failure as normal: log the raw text, retry once, and only then fail. For a pipeline that processes thousands of items, that two-line retry removes most of the noise.
Concurrency, retries and JavaScript
LangChain makes parallel work easy, which is where limits start to matter. A full key allows 8 concurrent requests and 300 requests per minute; a trial key allows 2 and 60. Past a limit the API answers HTTP 429. The error code is rate_limited when you exceed requests per minute and concurrency when too many calls are open at once. On temporary overload it also returns 429 with Retry-After: 5.
The OpenAI client that sits under ChatOpenAI retries 429 responses and honours Retry-After, and max_retries controls how often. Pair that with a max_concurrency value below your limit so most calls never see a 429:
import os
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
llm = ChatOpenAI(model="uncensored", base_url="https://api.nsfwllmapi.com/v1",
api_key=os.environ["LLM_API_KEY"], max_retries=3)
chain = llm | StrOutputParser()
prompts = [f"Write a one-line tagline for scene number {i}." for i in range(1, 41)]
results = chain.batch(prompts, config={"max_concurrency": 6})
print(len(results), "done")Six leaves headroom under the limit of 8 for anything else your app does at the same moment. On a trial key, set it to 1 or 2.
The same thing in Node
LangChain's JavaScript package takes the base URL inside a configuration object:
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "uncensored",
apiKey: process.env.LLM_API_KEY,
temperature: 0.8,
configuration: { baseURL: "https://api.nsfwllmapi.com/v1" },
});
const res = await llm.invoke("Give me a title for a story about a tide clock.");
console.log(res.content);Response headers such as X-Balance-USD are not surfaced by most LangChain classes. If you want balance tracking, either call the endpoint with a plain HTTP client once an hour or read the token counts from usage_metadata and multiply by the two rates.
For other client libraries and a raw curl example, see the quickstart documentation.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 on every call | Key missing, or the old OpenAI key still in OPENAI_API_KEY | Pass api_key explicitly from your own variable |
| 404 or connection error | Base URL missing /v1 | Use https://api.nsfwllmapi.com/v1 exactly |
| Unknown model error | A default OpenAI model name left in place | Set model="uncensored" |
429 with concurrency | More parallel calls than the key allows | Lower max_concurrency; close unused streams |
| Invalid JSON in output | Prompt does not describe the shape | State the keys in the system message; retry once |
One more difference to remember: this is a single open-weight model run by an independent provider, not a router across vendors and not any lab's official API. It is tuned to answer without content refusals for lawful adult use, and the one hard limit is that sexual content involving minors is never allowed. Build your app's own age gate and rules on top of that. Prompts are not used for training.
More guides
Questions and answers
Which LangChain class do I use with this API?
Use ChatOpenAI from the langchain-openai package (or @langchain/openai in JavaScript). Set base_url to https://api.nsfwllmapi.com/v1, model to uncensored, and pass your API key.
Does tool calling work through LangChain?
Yes. The API supports tools, tool_choice and streamed tool_calls, so bind_tools works. Send each result back as a ToolMessage with the matching tool_call_id.
Can I use embeddings or vector stores with this API?
Not from this API. It is text only, with no embeddings, image, audio or video endpoints. Use a separate embedding source for retrieval and send the retrieved text to the chat model.
How do I avoid 429 errors when batching?
Keep max_concurrency below 8 on a full key or below 2 on a trial key, and leave max_retries on. A 429 with code concurrency means too many open requests, and Retry-After tells you how long to wait.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.