EN ▾
Get API key
Get API key

Uncensored LLM API for adults

LangChain RAG Chatbot on GitHub: Setup with Our API

A retrieval-augmented chatbot needs three parts: an index of your documents, a retriever and a chat model. This walkthrough builds all three with LangChain, using an OpenAI-compatible endpoint for the model, and ends with a repo layout you can publish.

Updated

Document tiles flowing through a retrieval funnel into a chat terminal, illustrating a LangChain RAG pipeline

Key points

  • ChatOpenAI from langchain_openai works with this API once you set base_url, api_key and model to uncensored.
  • The API has no embeddings endpoint, so build the vector index with a local embedding model or another provider.
  • Keep keys in environment variables and commit a .env.example, never the real .env.
  • Retrieved context counts as input tokens at $0.15 per 1M, so chunk size and k directly set your cost per question.

What you are building

Most people who search for langchain rag chatbot github want a repository they can clone, point at their own files and run. The pattern behind nearly all of them is the same. You split documents into chunks, turn each chunk into a vector, store the vectors in an index, and at question time fetch the few chunks closest to the question. Those chunks go into the prompt, and the chat model answers using them.

This article shows that pipeline end to end in about 60 lines of Python. The chat model is an OpenAI-compatible hosted endpoint serving a model with ID uncensored. That matters for RAG on private or sensitive corpora such as fiction archives, moderation logs or forum exports, where a model that refuses to quote the retrieved text would break the whole product. Because the endpoint speaks the standard chat format, LangChain needs no special adapter.

Prerequisites and one important limit

You need Python 3.10 or newer and an API key from the API key page. New accounts can claim $0.50 of trial credit with one click, which covers many test questions. Install the packages:

pip install langchain langchain-openai langchain-community langchain-text-splitters langchain-huggingface faiss-cpu sentence-transformers

Now the limit. This API offers POST /v1/chat/completions and GET /v1/models only. There is no embeddings endpoint, so you cannot call OpenAIEmbeddings against it. The simple fix is a local embedding model through sentence-transformers, which runs on a laptop CPU for small corpora. You can also use any other embeddings provider; the chat model and the embedding model do not have to match, because retrieval only compares vectors made by the same embedding model with each other.

Put the key in your environment rather than in code:

export API_KEY="your-key-here"
# quick check that the key and model work
curl https://api.unrestrictedchatbot.top/v1/models -H "Authorization: Bearer $API_KEY"
# the list should include the model id: uncensored

Index your documents

Put plain text or Markdown files into a data/ folder. The script below loads them, splits them into overlapping chunks and saves a FAISS index to disk so you do not re-embed on every run.

# ingest.py
from pathlib import Path
from langchain_community.vectorstores import FAISS
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter

# This is the embedding model; the chat model is "uncensored" on
# https://api.unrestrictedchatbot.top/v1 and is configured in chat.py
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

texts, metas = [], []
for path in Path("data").glob("**/*"):
    if path.suffix.lower() in {".txt", ".md"}:
        texts.append(path.read_text(encoding="utf-8"))
        metas.append({"source": str(path)})

splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=120)
docs = splitter.create_documents(texts, metadatas=metas)

index = FAISS.from_documents(docs, embeddings)
index.save_local("faiss_index")
print(f"indexed {len(docs)} chunks")

Chunk size is the setting that most affects quality and cost. Chunks of about 800 characters keep each piece on one topic. Larger chunks carry more context but dilute the match and cost more per question. Overlap of 10 to 15 percent stops a sentence from being cut in half at a boundary.

Wire the retriever to the chat model

The second script loads the index and builds a chain with LangChain Expression Language. The only unusual lines are the three arguments to ChatOpenAI.

# chat.py
import os
from langchain_community.vectorstores import FAISS
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_openai import ChatOpenAI

embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
index = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
retriever = index.as_retriever(search_kwargs={"k": 4})

llm = ChatOpenAI(
    base_url="https://api.unrestrictedchatbot.top/v1",
    api_key=os.environ["API_KEY"],
    model="uncensored",
    temperature=0.3,
)

prompt = ChatPromptTemplate.from_messages([
    ("system",
     "Answer using only the context below. Quote it when helpful. "
     "If the context does not contain the answer, say so plainly.\n\n"
     "Context:\n{context}"),
    ("human", "{question}"),
])

def format_docs(docs):
    return "\n\n---\n\n".join(d.page_content for d in docs)

chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)

if __name__ == "__main__":
    while True:
        q = input("question> ")
        for token in chain.stream(q):
            print(token, end="", flush=True)
        print()

Run python ingest.py once, then python chat.py. Streaming works over SSE, so tokens appear as they are generated. The allow_dangerous_deserialization flag is needed for FAISS files you wrote yourself; never load an index downloaded from a stranger, because that format can execute code on load.

Cost per question

RAG makes each request larger than a plain chat turn, and you pay for every input token. Price is $0.15 per 1M input tokens and $0.50 per 1M output tokens, so you can estimate it directly. Take the defaults above: four chunks of roughly 800 characters is about 800 tokens of context, plus a system prompt and question of around 150 tokens, so call the input 1,000 tokens. A 300-token answer is the output.

  • Input: 1,000 x $0.15 / 1,000,000 = $0.00015
  • Output: 300 x $0.50 / 1,000,000 = $0.00015
  • Total per question: $0.0003

A thousand questions cost $0.30. If you raise k to 12 and the input grows to 3,000 tokens, the same answer costs 3,000 x $0.15 / 1,000,000 = $0.00045 for input plus $0.00015 for output, so $0.0006 per question, double the cost. More context is not always better. Test k at 3, 5 and 8 on a handful of real questions and keep the smallest value that answers them correctly. Failed or refused requests are not charged, which keeps retries cheap. See the pricing page for top-up amounts and bonuses.

A repo layout worth publishing

If you are putting the project on GitHub, a few habits make it usable by strangers and keep you out of trouble.

  • Never commit keys. Add .env and faiss_index/ to .gitignore. Commit a .env.example containing API_KEY= with no value.
  • Pin versions in requirements.txt. LangChain packages change names and import paths often, and an unpinned repo stops working within months.
  • Split ingest and chat into separate scripts, as above, so a reader can swap the loader without touching the chain.
  • Keep the base URL and model in config so users can change them with environment variables instead of editing source.
  • Do not commit private data. If your data/ folder holds anything you do not own, ship a small sample corpus instead.

In the README, tell readers the endpoint is OpenAI-compatible and where to get a key. The API documentation covers parameters, limits and response headers they will want to read.

Troubleshooting

HTTP 429 with code concurrency. A full key allows 8 concurrent requests and a trial key only 2. A streamed request holds its slot until the stream ends, so a loop that fires many questions at once will hit this. Run questions through a small worker pool or add retries with backoff. A 429 with a Retry-After: 5 header means temporary overload; wait five seconds and try again.

Answers ignore the context. Lower the temperature, tighten the system prompt, and print the retrieved chunks to check they are relevant. Retrieval problems are far more common than model problems.

Prompt too long. The context window is 100,000 tokens including the completion, which is generous, but a runaway k or a huge chunk size can still exceed it. Keep the body under 8 MB.

Tool use. If you want an agent that decides when to search, tool calling is supported, so you can expose the retriever as a tool and let the model call it.

Questions and answers

Can I use OpenAIEmbeddings with this API?

No. The API serves chat completions and the model list only, so embeddings must come from a local model or another provider. The retriever and the chat model are independent.

Which LangChain class do I use for the model?

Use ChatOpenAI from langchain_openai with base_url set to https://api.unrestrictedchatbot.top/v1, your key as api_key and model set to uncensored.

Is it safe to publish the project on GitHub?

Yes, as long as the key and your private documents stay out of the repository. Use environment variables, a .env.example file and a .gitignore that covers .env and the saved index.

How do I keep cost down in a RAG chatbot?

Retrieve fewer and smaller chunks, trim chat history, and cap answer length with max_tokens if needed. Input tokens cost $0.15 per 1M, so every extra chunk adds up across many questions.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API key