EN ▾

langchain.llms.openai: Use an OpenAI-Compatible API

Updated

If you searched for langchain.llms.openai, the short answer is that the old import is deprecated and the working replacement is ChatOpenAI from langchain_openai. This page shows the changes, with a custom base URL and the model ID uncensored.

Key points

  • Replace the legacy llms OpenAI wrapper with ChatOpenAI from the langchain-openai package; this API serves chat completions only.
  • Set base_url, api_key and model on ChatOpenAI and the rest of your chain stays the same.
  • Streaming, tool binding and JSON mode all pass through to the endpoint.
  • Cap batch concurrency at 8 to stay inside the full-key limit.
Chain links passing light to a central node, representing a LangChain pipeline connected to an API

What happened to the old LangChain LLM import

Older tutorials start with from langchain.llms import OpenAI, and searches for langchain.llms.openai still land on them. That class wrapped the legacy completions route, where you send one string and get one string back. LangChain later split its code into separate packages, moved integrations out of the main langchain package, and now keeps the OpenAI classes in langchain-openai. Recent releases print deprecation warnings for the old path, and in current versions it may fail to import at all.

Two classes live in the new package. OpenAI is the completions-style wrapper that kept the old name. ChatOpenAI talks to the chat completions route with a list of messages. This API exposes POST /v1/chat/completions and GET /v1/models, so ChatOpenAI is the class to use. If your old code calls llm("some prompt") with a plain string, you will change that to llm.invoke("some prompt"), which still accepts a string and wraps it in a user message for you.

The other half of the question is how to aim LangChain at a provider that is not OpenAI. Because the service is OpenAI-compatible, you do not need a special integration. You pass a different base_url, a different key and a different model name.

Install and make the first call

Install the integration package and set your key as an environment variable so it stays out of source control.

pip install -U langchain-openai langchain-core
export API_KEY="YOUR_API_KEY"
import os
from langchain_openai import ChatOpenAI

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

reply = llm.invoke("Summarise what a retriever does in a RAG pipeline, in two sentences.")
print(reply.content)
print(reply.usage_metadata)

The parameter names matter. In recent langchain-openai versions base_url and api_key are accepted directly; older releases used openai_api_base and openai_api_key, which still work as aliases. If your install complains about an unexpected argument, upgrade the package first.

The model value is uncensored. That is the only model ID on this service, and it is a single open-weight model run by an independent provider, not a router that picks between vendors. You can confirm what the endpoint lists with a call to GET /v1/models using the same key. If you have not created a key yet, the key page walks through sign-up and the one-click trial credit.

Build a chain with prompts and parsers

Everything above ChatOpenAI in your code stays the same. Prompt templates, output parsers and the pipe syntax do not know which provider is behind the model object.

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

prompt = ChatPromptTemplate.from_messages([
    ("system", "You write short, plain release notes for developers."),
    ("user", "Turn these commit messages into release notes:\n{commits}"),
])

chain = prompt | llm | StrOutputParser()

notes = chain.invoke({
    "commits": "fix: retry on 429\nfeat: add --dry-run flag\nchore: bump deps"
})
print(notes)

For streaming, call chain.stream(...) and print each piece as it arrives. The service sends server-sent events when stream is true and includes usage at the end of the stream. If you want that usage in LangChain, construct the model with stream_usage=True.

llm_stream = ChatOpenAI(
    model="uncensored",
    base_url="https://api.qwencoder.top/v1",
    api_key=os.environ["API_KEY"],
    stream_usage=True,
)

for chunk in (prompt | llm_stream).stream({"commits": "fix: typo in README"}):
    print(chunk.content, end="", flush=True)

Remember that a streamed request occupies one of your concurrency slots until the stream finishes. A loop that opens a stream and abandons it without reading to the end keeps that slot busy.

Tools and JSON mode

Agents depend on tool calling, and this endpoint supports it: you send tools and optionally tool_choice, the model answers with tool_calls, and you return results as messages with role: "tool". In LangChain you rarely write that by hand. Define a function with the @tool decorator and call bind_tools.

from langchain_core.tools import tool

@tool
def add(a: int, b: int) -> int:
    # Add two integers.
    return a + b

llm_tools = llm.bind_tools([add])
msg = llm_tools.invoke("What is 17 plus 25? Use the tool.")
print(msg.tool_calls)

if msg.tool_calls:
    call = msg.tool_calls[0]
    result = add.invoke(call["args"])
    print(result)

The printed tool_calls list holds the function name and parsed arguments. To finish the loop, append the assistant message and a ToolMessage with the result and call the model again. LangGraph's prebuilt agents do this loop for you, and they also work with any chat model object, including this one.

For structured output, JSON mode is available through response_format:

json_llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.qwencoder.top/v1",
    api_key=os.environ["API_KEY"],
    model_kwargs={"response_format": {"type": "json_object"}},
)

out = json_llm.invoke(
    "Return a JSON object with keys name and port for a local dev server."
)
print(out.content)

As with other OpenAI-style APIs, say the word JSON in the prompt and describe the keys you expect. JSON mode promises valid JSON, not your exact schema, so validate the result with Pydantic or a similar library before you use it. The docs page lists the parameters the endpoint accepts.

Migrating old code: before and after

Most migrations touch only a handful of lines. Here is the old pattern next to the replacement, so you can search your repository for the first form and swap in the second.

# Before (legacy, completions-style)
# from langchain.llms import OpenAI
# llm = OpenAI(openai_api_key="...", temperature=0.7)
# print(llm("Write a haiku about queues"))

# After (chat completions, custom endpoint)
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.qwencoder.top/v1",
    api_key=os.environ["API_KEY"],
    temperature=0.7,
)
print(llm.invoke("Write a haiku about queues").content)

Three differences catch people. The return value is now a message object, so you read .content instead of using the string directly. Direct calls like llm(...) are replaced by invoke. And prompts that relied on the model continuing raw text, such as a few-shot pattern ending mid-sentence, behave differently under a chat template, so put your instructions in a system message and the task in a user message.

If you work in JavaScript, the equivalent is the @langchain/openai package, where the endpoint goes into the configuration object:

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

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

const res = await llm.invoke("Name two uses of a message queue.");
console.log(res.content);

Environment variables are another route. The OpenAI client underneath reads OPENAI_BASE_URL and OPENAI_API_KEY, so exporting those with this endpoint and key lets existing code run without edits, as long as you also change the model name to uncensored. Explicit arguments are easier to debug, so prefer them in anything you will maintain.

Concurrency, retries and 429 errors

LangChain makes parallelism easy, and that is 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 either limit the API returns HTTP 429 with the error code rate_limited for the per-minute limit or concurrency for too many at once. During a short overload it also returns 429 with a Retry-After: 5 header.

Two settings handle most of it. First, max_retries on the model object makes the underlying client retry with backoff. Second, max_concurrency in the run config limits how many items a batch runs at once.

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

questions = [f"Give one tip about topic {i}." for i in range(40)]
answers = llm_safe.batch(questions, config={"max_concurrency": 6})
print(len(answers))

Six leaves a little headroom under the cap of eight, which matters if another script shares the same key. Watching the per-minute limit is separate: with 300 requests per minute, 40 short calls are fine, but a loop of thousands needs a pause or a token bucket. The X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency response headers confirm the limits applied to your key, and X-Balance-USD shows your remaining credit.

Cost and context when you build chains

Chains add tokens you do not see. A system prompt repeated on every call, retrieved documents stuffed into the context, and chat history all count as input. Output tokens cost more than input tokens here: $0.15 per 1M input and $0.50 per 1M output.

A worked example. A retrieval chain sends 6,000 input tokens (system prompt, question and retrieved passages) and gets 400 tokens back. Input costs 6,000 / 1,000,000 x $0.15 = $0.0009. Output costs 400 / 1,000,000 x $0.50 = $0.0002. One call is $0.0011, so 1,000 calls cost $1.10. Failed or refused requests are not charged.

The context window is 100,000 tokens for prompt plus completion, and max_tokens is optional, so you do not need to set it to get a long answer. Set it anyway when you want to cap spend on an agent that might loop. The pricing page covers top-ups: by crypto (USDT on TRC20, USDC on Base), any whole amount from $20 to $500, with +5% from $50, +10% from $100 and +15% from $200. Prompts are not used for training.

One content rule applies to every project, framework or not: the model is tuned to answer without content refusals for lawful adult use, and sexual content involving minors is never allowed.

Questions and answers

Is the old LangChain llms OpenAI import deprecated?

Yes. The old import path from the main langchain package is deprecated, and current code should use ChatOpenAI or OpenAI from the langchain-openai package.

Should I use ChatOpenAI or OpenAI with this API?

Use ChatOpenAI. The endpoint serves POST /v1/chat/completions, and the completions-style OpenAI class targets a different route.

Which model name do I pass to LangChain?

Pass uncensored as the model, together with base_url https://api.qwencoder.top/v1 and your API key.

Why do I get 429 errors from a LangChain batch?

You are probably over 8 concurrent requests or 300 per minute on a full key, or 2 and 60 on a trial key. Lower max_concurrency and keep max_retries above zero.

Your key is one form away

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

Get API key