EN ▾
Get API key
https://api.grokunrestricted.top/v1

Uncensored LLM API for developers

grokunrestricted.topGrokunrestricted API with LangChain: Setup Guide

Grokunrestricted API with LangChain: Setup Guide

This guide shows how to point LangChain at an OpenAI-compatible endpoint, with working Python and Node code for chat, streaming, tools and JSON output. You change the base URL and key, nothing else.

Updated

Glowing chain links carrying data cubes through a prism, representing a LangChain pipeline

Key points

  • Use ChatOpenAI with base_url set to https://api.grokunrestricted.top/v1 and model uncensored.
  • Streaming, tool calling and JSON mode all pass through the OpenAI wire format.
  • Respect 8 concurrent requests and 300 per minute on a full key; set max_concurrency and retries.
  • Failed or refused requests are not charged.

What you need

The setup for a grokunrestricted api langchain project is short because LangChain's OpenAI chat class accepts a custom base URL. You need three things: an API key from the key page, the base URL https://api.grokunrestricted.top/v1, and the model ID uncensored. The endpoint speaks the OpenAI chat completions format, so LangChain does not know or care that it is not talking to OpenAI.

Install the packages first.

pip install -U langchain-openai langchain-core

For Node, use npm install @langchain/openai @langchain/core. Keep the key out of your source. Export it as an environment variable and read it at start-up.

export UNCENSORED_API_KEY="YOUR_KEY"

A short note on scope: the model behind this API is one open-weight model run by an independent provider. It is not the official API of any model vendor. LangChain treats it as a generic OpenAI-compatible chat model, which is exactly what it is on the wire.

The first call

Create the model object once and reuse it. The two arguments that matter are base_url and model.

import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.grokunrestricted.top/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
    temperature=0.7,
)

reply = llm.invoke("Give me three names for a fantasy tavern.")
print(reply.content)

If you see a 401, re-copy the key; the client adds the bearer prefix for you. If you see a 404, check that the base URL ends in /v1 and has no trailing path such as /chat/completions. LangChain appends that part itself.

The same thing in Node:

import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
  model: "uncensored",
  apiKey: process.env.UNCENSORED_API_KEY,
  configuration: { baseURL: "https://api.grokunrestricted.top/v1" },
  temperature: 0.7,
});

const reply = await llm.invoke("Give me three names for a fantasy tavern.");
console.log(reply.content);

Sampling parameters such as temperature, top_p, stop, seed and the penalties are passed through to the model, so the usual LangChain arguments work.

Prompts, chains and streaming

A chain with a prompt template looks the same as with any other chat model.

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a game master who writes short scenes."),
    ("human", "Describe {place} in four sentences."),
])
chain = prompt | llm | StrOutputParser()

for chunk in chain.stream({"place": "a flooded library"}):
    print(chunk, end="", flush=True)

Under the hood .stream() sends stream: true and reads server-sent events. One detail matters for capacity planning: a streamed request holds its concurrency slot until the stream ends, so a slow reader counts against your limit for as long as it takes to consume the output.

To get token counts at the end of a stream, the usage block is delivered with the final chunk. With ChatOpenAI you can read it from usage_metadata on the aggregated message.

full = None
for chunk in llm.stream("Summarize SSE in one paragraph."):
    full = chunk if full is None else full + chunk
print(full.usage_metadata)

If usage_metadata is empty in your version, pass stream_usage=True to the constructor.

Tool calling

The API supports tools, tool_choice, streamed tool_calls, and tool results sent back as messages with role: "tool". In LangChain you declare a tool with a decorator and bind it.

from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, ToolMessage

@tool
def roll_dice(sides: int) -> int:
    """Roll a 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 20-sided die for me.")]

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)

Two practical points. First, keep tool descriptions short and the argument names obvious, since a smaller open-weight model follows plain schemas better than elaborate ones. Second, always check that ai.tool_calls is not empty before you loop; the model can answer in text instead. If you need to force a call, pass tool_choice through bind_tools.

For agents, the same bound model works with LangGraph's prebuilt agent helpers, since they only need a chat model that supports tool calling.

JSON mode and structured output

JSON mode is enabled with response_format set to {"type": "json_object"}. In LangChain you can bind it directly.

import json

json_llm = llm.bind(response_format={"type": "json_object"})
out = json_llm.invoke(
    "Return a JSON object with keys name and level for a new character. JSON only."
)
data = json.loads(out.content)
print(data["name"], data["level"])

Mention the word JSON in the prompt and describe the keys you want. JSON mode guarantees valid syntax in the common case, not your schema, so validate the result. With Pydantic you can use llm.with_structured_output(MySchema, method="json_mode"), and the schema goes into the prompt for you. Wrap the parse in a try block and retry once on failure rather than trusting every reply.

Do not rely on schema-enforcing options that depend on features this API does not list. Stick to json_object and tool calling, which are the two documented routes.

Conversation memory without blowing the window

Chat apps built on LangChain usually keep a message history and resend it each turn. The window here is 100,000 tokens for prompt plus completion, which is large, but cost grows with every resent token, so cap the history on purpose. The simplest method is to keep only the last N messages. Recent LangChain versions provide a trimming helper that does this by token count.

from langchain_core.messages import trim_messages

trimmer = trim_messages(
    max_tokens=8000,
    strategy="last",
    token_counter=llm,
    include_system=True,
    start_on="human",
)

chain = trimmer | llm
reply = chain.invoke(history)

Passing the model as the token counter makes LangChain use its own approximate counting for the model, which is close enough for budgeting even though the real tokenizer may differ a little. Treat the number as an estimate and leave headroom. If you want long-term memory, summarize old turns into a short note with one extra call and put that note in the system message. A summary call costs tokens too, so do it every 20 turns or so rather than every turn.

For roleplay and companion apps, keep character sheets and rules in a fixed system message at the top, then the trimmed history, then the new user message. That order keeps the persona stable as old turns drop off. Remember that the persona text is resent on every call, so a 1,500-token sheet sent 40 times is 60,000 input tokens, which is $0.009 at $0.15 per 1M.

Retrieval over your own documents

There is no embeddings endpoint on this API, so a retrieval chain needs the vectors from somewhere else, such as a local embedding model that runs on your machine. The chat model only sees the final text. Once you have retrieved passages, the generation step is an ordinary prompt.

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

rag_prompt = ChatPromptTemplate.from_messages([
    ("system", "Answer only from the context. If it is missing, say so."),
    ("human", "Context:\n{context}\n\nQuestion: {question}"),
])

answer = (rag_prompt | llm | StrOutputParser()).invoke({
    "context": "\n\n".join(passages),
    "question": "What does the lease say about pets?",
})

Because the window holds 100,000 tokens, you can pass many passages, but more is not always better. Past a certain point, extra passages add cost and distract the model. Start with the top four or five and measure answers on a fixed question set before widening. Tag each passage with its source in the context string so you can ask the model to cite it, and so you can see in the output which passage caused a wrong answer.

One cost note for retrieval: five passages of 600 tokens plus a 300-token question and instructions is 3,300 input tokens. With a 400-token answer, a call costs 3,300 × $0.15 / 1M + 400 × $0.50 / 1M = $0.000495 + $0.0002 = $0.000695.

Rate limits, retries and concurrency

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. When you cross a line the API answers HTTP 429 with the 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.

LangChain retries failed calls on its own. Tune it instead of leaving the defaults.

llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.grokunrestricted.top/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
    max_retries=4,
    timeout=120,
)

results = chain.batch(
    [{"place": p} for p in places],
    config={"max_concurrency": 6},
)

Setting max_concurrency to 6 leaves two slots free for other work on the same key. Parameter details are in the docs and rates are on the pricing page. The response headers X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency tell you what your key allows, and X-Balance-USD shows remaining credit.

Troubleshooting

  • Model not found. The ID is uncensored, lower case. Call GET /v1/models to confirm what the key sees.
  • Context length errors. The window is 100,000 tokens for prompt plus completion. Trim chat memory with a window or summary buffer before it grows that large.
  • Empty or short replies. Check max_tokens. It is optional here, and a small value you set earlier may be cutting output.
  • Timeouts on long outputs. Use streaming and raise the client timeout.
  • Unexpected refusals. The model is tuned for lawful adult use, but no model is perfect. See the troubleshooting guide for prompt patterns.

Cost is easy to watch. Input is $0.15 per 1M tokens and output is $0.50 per 1M, so a call with 3,000 input tokens and 800 output tokens costs $0.00045 + $0.0004 = $0.00085. Failed or refused requests are not charged.

Questions and answers

Which LangChain class should I use?

ChatOpenAI from langchain-openai in Python or @langchain/openai in Node. Set the base URL and use model uncensored.

Does tool calling work with LangChain agents?

Yes. The API supports tools, tool_choice and tool results as role tool, so bind_tools and LangGraph agent helpers work with it.

Can I use embeddings or vector stores?

This API is text chat only and has no embeddings endpoint. Use a separate embedding source for retrieval.

What do I do about 429 errors?

Lower max_concurrency, keep retries enabled and honor Retry-After. A full key allows 8 concurrent requests and 300 per minute.

Can I test without paying?

New users can claim $0.50 of trial credit with one click after sign-up. It lasts 7 days and needs no payment.

Your key is one form away

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

https://api.grokunrestricted.top/v1Get API key