- Nsfwchat
- LangChain Chat Models in Python with a Custom Endpoint
LangChain Chat Models in Python with a Custom Endpoint
Working with langchain chat models python code against this API takes one class and three settings. Point ChatOpenAI at your Nsfwchat base URL, add your key, and every chat model method you already know keeps working.

Key points
- ChatOpenAI from langchain-openai works unchanged once base_url and api_key are set.
- Streaming, tool calling and JSON mode all pass through the OpenAI-compatible endpoint.
- Full keys allow 8 concurrent requests, so cap batch concurrency below that.
- Failed or refused requests are not charged, and usage is returned for every call.
The short version: ChatOpenAI with a different base URL
LangChain does not need a special integration for this API. The service speaks the OpenAI chat completions protocol, so the standard ChatOpenAI class from the langchain-openai package is the right tool. If you came here searching for langchain chat models python examples that use a non-OpenAI endpoint, this is the whole trick: override base_url, pass the key you got from the dashboard, and set the model to uncensored.
Install the two packages first, then export your key so it never lands in source control.
pip install -U langchain-openai langchain-core
export NSFWCHAT_API_KEY="paste-your-key-here"
Now create the model object. Keep it in its own module so the rest of your project can import it.
# llm.py
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.nsfwchat.cc/v1",
api_key=os.environ["NSFWCHAT_API_KEY"],
temperature=0.8,
max_retries=2,
timeout=120,
stream_usage=True,
)
if __name__ == "__main__":
reply = llm.invoke("Write a two-sentence opening for a noir short story.")
print(reply.content)
print(reply.usage_metadata)
Run it. If you see a story opening and a dictionary with input_tokens and output_tokens, the connection is correct. If you do not have a key yet, the API key page shows how to sign up and claim the one-click trial credit.
A note on secrets: ChatOpenAI also reads the OPENAI_API_KEY environment variable when no key is passed, which can send the wrong key to the wrong host if you have both configured. Passing api_key and base_url explicitly, as above, removes that risk. It also makes the code obvious to the next person who reads it.
Messages, system prompts and history
Chat models in LangChain take a list of message objects. The same list maps one to one onto the messages array the API expects, so nothing is lost in translation. A system message sets the behavior, human and AI messages carry the conversation.
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from llm import llm
history = [
SystemMessage(content="You are the narrator of a dark fantasy story for adult readers. Stay in character."),
HumanMessage(content="The party reaches the gates of the drowned city."),
AIMessage(content="Black water laps at the iron gates. Something below the surface is watching."),
HumanMessage(content="I draw my sword and step onto the causeway."),
]
answer = llm.invoke(history)
print(answer.content)
Nothing is stored on the server between calls, so you resend the history each time. That is how every OpenAI-compatible API works, and it is also why long conversations cost more input tokens as they grow. With a 100,000-token context window you have plenty of room, but you still decide what to keep. A common pattern is to keep the system message plus the last N turns and summarize the rest.
The model is tuned to answer without content refusals for lawful adult use, so a system prompt that sets up fiction, roleplay or a companion persona does not get second-guessed halfway through a scene. The one hard limit is that sexual content involving minors is never allowed.
If you build the list from a database, remember that order matters and roles must alternate sensibly. A system message goes first, then user and assistant messages in the order they happened. Do not drop the assistant replies to save space; the model reads its own earlier lines to keep the voice consistent, and a history made only of user messages produces replies that ignore what was already said. When you need to shorten, cut whole exchanges from the oldest end instead of trimming sentences out of the middle.
Streaming responses
For anything a person reads live, stream. llm.stream() yields chunks as server-sent events arrive, and astream() does the same for async code. Because the constructor above sets stream_usage=True, the final chunk carries token usage, which is handy for logging cost per request.
from llm import llm
final = None
for chunk in llm.stream("Describe a rainy harbor town in four sentences."):
print(chunk.content, end="", flush=True)
final = chunk if final is None else final + chunk
print()
print(final.usage_metadata)
One detail matters for capacity planning. A streamed request keeps its concurrency slot until the stream ends. If your app opens a stream per user and the user walks away without closing it, that slot stays busy. Set a client-side timeout and close abandoned streams.
Tool calling with bind_tools
The API supports tools, tool_choice and streamed tool_calls, and results go back as role: "tool" messages. LangChain wraps all of that in bind_tools. Define a function with the @tool decorator, bind it, and inspect tool_calls on the reply.
import random
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, ToolMessage
from llm import llm
@tool
def roll_dice(sides: int) -> int:
'''Roll one die with the given number of sides.'''
return random.randint(1, sides)
model = llm.bind_tools([roll_dice])
messages = [HumanMessage(content="Roll a twenty-sided die to see if the lock opens.")]
ai = model.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 = model.invoke(messages)
print(final.content)
This is a two-call loop: the first call returns the request to run a tool, the second returns prose that uses the result. Keep tool descriptions short and argument names plain. Small, clear schemas get called correctly more often than elaborate ones, and you should always validate arguments before acting on them.
Async calls and parameters that carry over
Web backends should use the async methods, which share names with the sync ones but start with a: ainvoke, astream and abatch. They run on the same ChatOpenAI object, so the module from earlier works without changes.
import asyncio
from llm import llm
async def main():
async for chunk in llm.astream("Summarize the plot of a heist film in three sentences."):
print(chunk.content, end="", flush=True)
asyncio.run(main())
Sampling settings are passed through to the model, so the usual constructor fields behave as you expect. A few that matter for chat models in Python projects:
temperatureandtop_pcontrol variety. Start at 0.7 to 0.9 for storytelling and lower for extraction tasks.max_tokensis optional here. If you omit it, the reply can use whatever is left of the 100,000-token window, so set a cap when you want short answers.seedmakes tests more repeatable. It is passed through, but treat it as best effort and not a guarantee.stoptakes a list of strings that end generation early, useful for turn-based formats.frequency_penaltyandpresence_penaltyreduce repeated phrasing in long outputs.
Put the ones you always use in the constructor, and override per call with llm.bind(temperature=0.2) when a single step needs different behavior. That way a creative step and a strict JSON step can share one configured client.
JSON mode and prompt templates
For structured output, use JSON mode through bind. The API accepts response_format: {"type":"json_object"}. As with other OpenAI-style endpoints, say the word JSON in your prompt and describe the keys you want.
import json
from langchain_core.prompts import ChatPromptTemplate
from llm import llm
prompt = ChatPromptTemplate.from_messages([
("system", "Reply with a JSON object with keys name, mood and hook. No other text."),
("human", "Invent a tavern keeper for a {setting} setting."),
])
chain = prompt | llm.bind(response_format={"type": "json_object"})
out = chain.invoke({"setting": "frontier desert"})
data = json.loads(out.content)
print(data["name"], "-", data["hook"])
JSON mode guarantees syntactically valid JSON, not your exact schema. Check the keys you need and retry once on a miss. Pipe composition with | also lets you add StrOutputParser() at the end when you only want text.
Batching, concurrency and 429 errors
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. When you cross a limit, the API returns HTTP 429 with error code rate_limited (too many per minute) or concurrency (too many at once). On temporary overload it also returns 429 with a Retry-After: 5 header.
llm.batch() runs inputs in parallel, so set max_concurrency under your limit. Leave headroom if other parts of the app also call the API.
from llm import llm
prompts = [f"Give one-line character note number {i}." for i in range(40)]
results = llm.batch(prompts, config={"max_concurrency": 6})
for r in results[:3]:
print(r.content)
The max_retries=2 in the constructor makes the underlying OpenAI client retry on 429 and connection errors with backoff. If you still see failures, lower the concurrency rather than raising retries, since retries that pile up make the burst worse. The common integration mistakes article covers other traps such as resending oversized histories.
Checking cost and debugging
Billing is per token at $0.15 per 1M input tokens and $0.50 per 1M output tokens, drawn from prepaid credit. Failed or refused requests are not charged. Every response includes an X-Balance-USD header, and you can read headers in LangChain by calling the raw client:
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.nsfwchat.cc/v1", api_key=os.environ["NSFWCHAT_API_KEY"])
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "ping"}],
max_tokens=5,
)
print(raw.headers.get("X-Balance-USD"), raw.headers.get("X-Request-Id"))
Save the X-Request-Id whenever something looks wrong; support can trace a request with it. Common failures and fixes:
- 401 error: the key is missing or has a stray space. Print
len(os.environ["NSFWCHAT_API_KEY"])to check. - Model not found: the model name must be exactly
uncensored. You can confirm withGET /v1/models. - 404 on the URL: the base URL ends in
/v1, and LangChain appends/chat/completionsitself. - Unsupported embedding calls: this API is text chat only, so
OpenAIEmbeddingswill not work against it. Use a separate embedding provider for retrieval.
Prices and top-up bonuses are listed on the pricing page, and the quickstart docs show the raw HTTP shapes if you want to compare them with what LangChain sends.
More guides
Questions and answers
Do I need a special LangChain package for this API?
No. Use langchain-openai and its ChatOpenAI class, then set base_url to your site's /v1 address and model to uncensored.
Can I use LangChain agents and tools with it?
Yes. Tool calling is supported, so bind_tools and agent frameworks built on it work. Validate tool arguments yourself, because the model can produce malformed ones like any LLM.
Does it work with LangChain embeddings or vector stores?
The API is text chat only, with no embeddings endpoint. You can still use a vector store by getting embeddings from another source and sending retrieved text to this model.
How do I avoid 429 errors in batch jobs?
Set max_concurrency in the config below 8 for a full key, or 2 for a trial key, and keep the request rate under 300 per minute.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.
Read the docs