EN ▾

LangChain OpenAI pip Install: Use Our API

The langchain open ai pip route is two packages and three arguments: install langchain-openai, then give ChatOpenAI our base URL, your key and the model ID uncensored.

Updated

Glass chain links connecting a package box to a server cube, representing LangChain linked to an API

Install the packages

In a fresh virtual environment, run pip install langchain-openai. That pulls in langchain-core and the openai SDK as dependencies. If you also want the higher-level pieces such as agents or community integrations, install langchain separately with pip install langchain; the chat model class used below lives in langchain-openai and does not need it.

Older tutorials import ChatOpenAI from langchain.chat_models or langchain_community. Those paths have been deprecated for a while. The current import is from langchain_openai import ChatOpenAI, and it is the one this page uses. If you pin versions, check your own lock file, since LangChain changes quickly.

The package name uses a hyphen on pip (langchain-openai) and an underscore in Python (langchain_openai). Mixing them up is the most common install error for this setup, and the traceback is a plain "no matching distribution" or "no module" message.

Use a virtual environment so the LangChain packages do not collide with other projects. With the standard library, python -m venv .venv followed by activating it is enough. Confirm the install by running pip show langchain-openai, which prints the version you got. If an old project already has an openai package older than version 1, upgrade it first, because the client shape changed at that release and the current LangChain integration expects the newer one.

Next you need a key. Create an account on the key page, sign in with Google or with email and password, and copy the key. New users can claim $0.50 of trial credit there with one click, valid for 7 days and with no card needed.

Point ChatOpenAI at the endpoint

The service is OpenAI-compatible, so LangChain needs nothing special. You change the base URL and the key, and set the model ID to uncensored.

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.unfilteredaichat.top/v1",
    api_key="YOUR_KEY",
    temperature=0.8,
)

reply = llm.invoke("Write a two-line opening for a fantasy story.")
print(reply.content)

That is the whole setup. invoke accepts a string, a list of messages or a prompt value. The reply is an AIMessage, and the text sits in .content.

If you would rather not put the key in code, the underlying SDK reads OPENAI_API_KEY and OPENAI_BASE_URL from the environment, so you can export both and call ChatOpenAI(model="uncensored"). Explicit arguments are easier to debug, because a stray variable from another project cannot silently send your traffic to a different provider. Check which one you are using whenever results look odd.

A prompt, a model and a parser

Most real LangChain code is a chain. Here is a short one with a system prompt, a user variable and a string parser, using the same base URL and model.

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

llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.unfilteredaichat.top/v1",
    api_key="YOUR_KEY",
)

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a blunt editor. Give three concrete fixes, no flattery."),
    ("user", "{draft}"),
])

chain = prompt | llm | StrOutputParser()
print(chain.invoke({"draft": "The hero walked in. It was dark. He was sad."}))

Because the endpoint passes temperature, top_p, stop, seed and the penalties through, you can set them on ChatOpenAI as usual. For repeatable tests, set temperature low and pass a seed.

Streaming, JSON mode and tools

Streaming

Streaming works over SSE. Use stream on any chain and print the chunks as they arrive:

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="uncensored", base_url="https://api.unfilteredaichat.top/v1", api_key="YOUR_KEY")

for chunk in llm.stream("Describe a harbour town at dawn in four sentences."):
    print(chunk.content, end="", flush=True)

A streamed request keeps its concurrency slot until the stream finishes, so close or finish every stream you start.

JSON mode

Bind the response_format parameter to the model and mention JSON in the prompt:

import json
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="uncensored", base_url="https://api.unfilteredaichat.top/v1", api_key="YOUR_KEY")
json_llm = llm.bind(response_format={"type": "json_object"})
out = json_llm.invoke(
    "Return a JSON object with keys name, mood and hook for a tavern keeper NPC."
)
data = json.loads(out.content)
print(data["name"])

Tool calling

Tool calling goes through bind_tools. A plain Python function wrapped with the @tool decorator is enough:

from langchain_core.tools import tool
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="uncensored", base_url="https://api.unfilteredaichat.top/v1", api_key="YOUR_KEY")

@tool
def roll_dice(sides: int) -> int:
    # Roll a die with the given number of sides.
    import random
    return random.randint(1, sides)

with_tools = llm.bind_tools([roll_dice])
msg = with_tools.invoke("Roll a 20-sided die for me.")
print(msg.tool_calls)

When tool_calls is filled in, msg.content is usually empty. Run the tool, send its output back as a tool message and call the model again. If you use LangChain's agent helpers, they handle that loop for you. The API docs describe how tool results are passed as role: "tool" messages.

Batching without hitting 429

LangChain makes parallel work easy, which is also how people hit limits. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. Past those numbers the API returns HTTP 429 with concurrency or rate_limited, and on temporary overload a 429 with Retry-After: 5.

Set the cap in the runnable config, and let the client retry:

llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.unfilteredaichat.top/v1",
    api_key="YOUR_KEY",
    max_retries=4,
)

inputs = [f"Give one name for tavern number {i}" for i in range(40)]
results = llm.batch(inputs, config={"max_concurrency": 8})
print(len(results))

On a trial key use max_concurrency of 2. The built-in retries back off on 429, which covers the short overload case. If you stream in many workers, remember that each open stream counts toward the 8.

Chat history and long prompts

LangChain keeps history in whatever structure you give it. The simplest version is a list of messages that you append to after each turn. This is explicit, easy to log, and works well with this API because the endpoint is stateless: every request carries the full conversation.

from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="uncensored", base_url="https://api.unfilteredaichat.top/v1", api_key="YOUR_KEY")

history = [SystemMessage(content="You are the narrator of a slow, atmospheric mystery.")]

def turn(user_text):
    history.append(HumanMessage(content=user_text))
    reply = llm.invoke(history)
    history.append(AIMessage(content=reply.content))
    return reply.content

print(turn("I step into the empty lighthouse."))
print(turn("I check the logbook on the desk."))

Each call sends everything so far, and input tokens are billed on every call. A chat that grows to 20,000 tokens costs 20,000 x $0.15 / 1M = $0.003 in input for each further turn. That is small, but it adds up over thousands of sessions, so trim old turns or summarise them once the history passes a size you choose. The 100,000-token window leaves a lot of headroom, and the model reads the whole thing, which is useful for long fiction.

The same approach works inside RunnableWithMessageHistory if you want LangChain to manage the store. Whichever you pick, count tokens before sending when you are near the limit, because prompt and completion share the one window.

Quick connection test

If a first call fails, test the endpoint outside LangChain with plain curl against https://api.unfilteredaichat.top/v1/models using your key as a Bearer token. A list that includes uncensored proves the key and URL are right, and any remaining problem is in your chain.

What does not carry over from the OpenAI setup

This is the part that trips up RAG projects. The service exposes POST /v1/chat/completions and GET /v1/models, and nothing else. In particular:

  • No embeddings. OpenAIEmbeddings pointed at this base URL will fail. Use a separate embedding model from a provider or a local library for your vector store, and use this API for generation only.
  • No image, audio or video endpoints. Text only.
  • No fine-tuning. Prompting and system messages are your tools.

The model itself is one open-weight model run by an independent provider. It is not an official API of OpenAI or any other vendor, and it is not a router that picks among them, so do not expect another vendor's model names to work. The only model ID is uncensored. List it with GET /v1/models if you want to confirm your connection.

The context window is 100,000 tokens for prompt plus completion, and max_tokens is optional. A memory component that stuffs the whole history into every call will eventually approach that, so trim or summarise as the chat grows. The guide to the unfiltered AI API covers the service from the integration side.

What a LangChain job costs

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, billed from prepaid credit with no subscription. Chains tend to have larger prompts than plain chat, since retrieved passages and instructions are included on every call. Take a RAG-style step that sends 3,000 input tokens and gets 500 back.

  • One run: 3,000 x $0.15 / 1M = $0.00045 in, and 500 x $0.50 / 1M = $0.00025 out, so $0.0007.
  • 10,000 runs: 30M input tokens cost $4.50 and 5M output tokens cost $2.50. The total is $7.00.

Failed or refused requests are not charged, and credit never expires. Top-ups are any whole amount from $20 to $500, by by crypto (USDT on TRC20, USDC on Base), with +5% from $50, +10% from $100 and +15% from $200. See the pricing page for the current numbers. Prompts are not used for training, and the model answers without content refusals for lawful adult use; sexual content involving minors is never produced.

Questions and answers

Which pip package do I need for LangChain with this API?

Install langchain-openai. It includes ChatOpenAI and brings in the openai SDK. Set base_url to https://api.unfilteredaichat.top/v1 and model to uncensored.

Can I use OpenAIEmbeddings with this base URL?

No. The service has no embeddings endpoint, so use a different embedding source for your vector store and this API for chat completions.

Does LangChain streaming work?

Yes. The API streams over SSE, and llm.stream() and astream() work as with other OpenAI-compatible endpoints.

How many parallel calls can I make?

Eight on a full key and two on a trial key. Set max_concurrency in the LangChain config to match.

Your key is one form away

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

Get API key