The short version
To set up langchain chat with your data, you need three pieces: a document loader and splitter, a vector store with an embedding model, and a chat model that writes the final answer. The chat model is the only part that talks to this API. Install langchain-openai, set the base URL to https://api.unfilteredchat.top/v1, use the model ID uncensored, and pass your key.
The one thing to plan for is embeddings. This service is text chat only, with no embeddings endpoint, so the vectors must come from somewhere else. A local sentence-transformers model is the easy choice, and it keeps your documents on your machine during indexing. The rest of this article builds the pipeline step by step and ends with tool calling, JSON mode, and the cost of a typical question.
Install and connect the chat model
Create a virtual environment and install the packages. These are the current split LangChain packages; if you hit an import error, check the version of langchain-core first.
pip install langchain-openai langchain-core langchain-text-splitters langchain-huggingface sentence-transformers
Get a key from the API key page. New accounts can claim a $0.50 trial with one click after sign-up, which is plenty for testing a retrieval pipeline. Keep the key in an environment variable so it never lands in your repository.
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.unfilteredchat.top/v1",
api_key=os.environ["UNFILTERED_API_KEY"],
temperature=0.2,
)
print(llm.invoke("Reply with the single word: ready").content)
If that prints a reply, authentication, the base URL and the model ID are all correct. If you get a 401, the key is wrong or missing. If you get a 404, the base URL is probably missing the /v1 suffix. The documentation lists the two supported methods, POST /v1/chat/completions and GET /v1/models.
Index your documents locally
Retrieval has two halves. Indexing happens once: split the files into passages, turn each passage into a vector, store the vectors. Querying happens on every question: embed the question, fetch the closest passages, and hand them to the chat model. Because there is no embeddings endpoint here, indexing uses a local model.
from pathlib import Path
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_core.vectorstores import InMemoryVectorStore
text = Path("notes.txt").read_text(encoding="utf-8")
splitter = RecursiveCharacterTextSplitter(chunk_size=1200, chunk_overlap=150)
chunks = splitter.split_text(text)
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
store = InMemoryVectorStore(embeddings)
store.add_texts(chunks)
print(len(chunks), "chunks indexed")
A chunk size of about 1,200 characters, roughly 300 tokens, is a sensible start for prose. Smaller chunks give sharper matches but lose surrounding context. Larger chunks keep context but waste prompt tokens on text the question did not need. Try 800 and 2,000 on your own files and read the answers; the right size depends on how your documents are written.
The in-memory store is fine for a few thousand chunks. For larger collections, swap in Chroma, FAISS or a hosted vector database. The chat side does not change at all, because it only ever sees plain text passages.
Wire retrieval to the chat model
Now the part that answers questions. The prompt tells the model to use the supplied passages and to say so when they do not contain the answer. That last instruction matters: without it, a model will happily fill gaps from general knowledge and you will not know which sentences came from your files.
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.unfilteredchat.top/v1",
api_key=os.environ["UNFILTERED_API_KEY"],
temperature=0.2,
)
prompt = ChatPromptTemplate.from_messages([
("system", "Answer using only the passages below. "
"If they do not contain the answer, say you could not find it.\n\n{context}"),
("human", "{question}"),
])
chain = prompt | llm | StrOutputParser()
def ask(question: str) -> str:
hits = store.similarity_search(question, k=4)
context = "\n\n---\n\n".join(h.page_content for h in hits)
return chain.invoke({"context": context, "question": question})
print(ask("What did we decide about the release date?"))
This is plain retrieval-augmented generation, written without the older chain helpers so you can see every step. You can swap the helper function for a LangChain retriever object later; the behavior is the same.
Stream answers and respect the limits
For a chat interface, stream the response so text appears as it is generated. Streaming uses server-sent events, and LangChain handles the parsing.
for piece in chain.stream({"context": context, "question": "Summarize the open risks."}):
print(piece, end="", flush=True)
Two limits matter for retrieval apps that serve several users. A full key allows 8 concurrent requests and 300 requests per minute; a trial key allows 2 and 60. A streamed request holds its concurrency slot until the stream finishes, so a slow reader can occupy a slot longer than you expect. When you exceed a limit the API answers with HTTP 429. The error code rate_limited means too many requests per minute, and concurrency means too many at once. On a temporary overload it also returns 429 with Retry-After: 5.
LangChain retries failed calls by default. Set the retry count explicitly and keep it small, then queue user requests on your side so the eighth and ninth simultaneous chats wait instead of failing.
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.unfilteredchat.top/v1",
api_key=os.environ["UNFILTERED_API_KEY"],
max_retries=3,
timeout=120,
)Tool calling: let the model decide when to search
The pipeline above retrieves on every question, even for "thanks" or "rephrase that". Tool calling fixes this. You expose the search as a tool, and the model asks for it only when it needs your documents. The API supports tools, tool_choice, streamed tool_calls, and tool results sent back as role: "tool" messages, which LangChain wraps as ToolMessage.
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, ToolMessage
@tool
def search_docs(query: str) -> str:
'''Search the indexed documents and return the most relevant passages.'''
hits = store.similarity_search(query, k=4)
return "\n\n---\n\n".join(h.page_content for h in hits)
agent_llm = ChatOpenAI(
model="uncensored",
base_url="https://api.unfilteredchat.top/v1",
api_key=os.environ["UNFILTERED_API_KEY"],
).bind_tools([search_docs])
messages = [HumanMessage("What does the notes file say about the release date?")]
ai = agent_llm.invoke(messages)
messages.append(ai)
for call in ai.tool_calls:
result = search_docs.invoke(call["args"])
messages.append(ToolMessage(content=result, tool_call_id=call["id"]))
final = agent_llm.invoke(messages)
print(final.content)
If the model answers directly without calling the tool, ai.tool_calls is empty and the loop does nothing, which is the behavior you want for small talk. To force a search every time, pass tool_choice when binding. Tool use quality varies between models, so keep tool descriptions short, give parameters plain names, and test with the questions your users actually ask.
JSON mode for structured answers
Some data questions want a table or a record, not a paragraph: extract every deadline from a contract, list action items from meeting notes. JSON mode makes the model return a valid JSON object, and you can bind it in LangChain with one argument.
import json
json_llm = llm.bind(response_format={"type": "json_object"})
reply = json_llm.invoke([
("system", "Return a JSON object with the key action_items, a list of "
"objects with owner and task. Use only this text:\n\n" + context),
("human", "List the action items."),
])
data = json.loads(reply.content)
print(data["action_items"])
Say the word JSON in the prompt and describe the keys you expect. JSON mode guarantees syntax, not your schema, so validate the parsed object with Pydantic or a simple key check before you use it, and retry once on failure.
What a question costs
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, pay as you go from prepaid credit. A retrieval question has a predictable shape. Four chunks of about 300 tokens is 1,200 tokens of context. Add roughly 300 tokens for the system prompt, the question and any chat history, and you send about 1,500 input tokens. A short answer of 300 tokens comes back.
- Input: 1,500 / 1,000,000 x $0.15 = $0.000225
- Output: 300 / 1,000,000 x $0.50 = $0.00015
- Total: $0.000375 per question, so 1,000 questions cost $0.375
The $0.50 trial credit therefore covers more than 1,300 questions of this size. Failed or refused requests are not charged. Details on top-ups and the volume bonus are on the pricing page; payment is by crypto (USDT on TRC20, USDC on Base), and credit never expires.
The main way to spend more is to raise k or the chunk size. Each extra 300-token chunk adds $0.000045 per question, which is small, but it also dilutes the context, so more is not automatically better.
Common problems and fixes
- Answers ignore the documents. Print the retrieved chunks. If the right passage is missing, the problem is retrieval: change the chunk size, add overlap, or raise
k. - Import errors. LangChain moved integrations into separate packages. Import
ChatOpenAIfromlangchain_openai, not from the oldlangchain.chat_modelspath. - Token counting warnings. LangChain may try to count tokens with a tokenizer meant for another model. The warning is harmless; the billing figures come from the usage block in the response.
- 429 on bursts. Add a semaphore of 8 (2 on a trial key) around your calls.
- Long documents. The context window is 100,000 tokens for prompt plus completion. You can put a whole short document in the prompt without retrieval, but retrieval is cheaper and usually more accurate on long files.
The service is for lawful adult use and does not allow sexual content involving minors. Prompts are not used for training, so private notes and drafts are safe to index in the sense that matters for model improvement. The general overview of the endpoint is on the uncensored chat API page.
