EN ▾

LangChain init_chat_model with an OpenAI-Compatible API

LangChain's init_chat_model can talk to any OpenAI-compatible endpoint if you pass a base URL and a key. This page shows the exact call for our API, plus streaming, tools, structured output and rate limit settings.

Updated

Chain links connecting building blocks to a server, representing LangChain connecting to an API

Key points

  • Install langchain-openai, then call init_chat_model with model_provider="openai", our base URL and the model ID uncensored.
  • Streaming, tool calling and JSON mode all work through the normal LangChain methods.
  • Keep batch concurrency at 8 or lower on a full key, and 2 on a trial key.
  • The $0.50 trial credit is enough to test a whole chain before you top up.

The short answer

To use langchain init_chat_model with our API, install langchain and langchain-openai, then point the OpenAI provider at our base URL. The provider name stays openai because the API speaks the OpenAI protocol. Only the URL, the key and the model ID change.

pip install -U langchain langchain-openai
import os
from langchain.chat_models import init_chat_model

llm = init_chat_model(
    "uncensored",
    model_provider="openai",
    base_url="https://api.contentmoderationapis.com/v1",
    api_key=os.environ["API_KEY"],
    temperature=0.7,
)

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

That is the whole setup. The model ID is uncensored, the auth header is a standard bearer token, and LangChain builds it from api_key. If the call returns text, everything underneath works: key, base URL, model and network path.

Why the provider is openai

init_chat_model is a factory. It looks at the provider name, imports the matching integration package and returns a chat model object. For OpenAI-style endpoints that package is langchain-openai, and the class behind it is ChatOpenAI. Extra keyword arguments such as base_url and api_key are forwarded to that class.

Our service is a hosted open-weight model behind an OpenAI-compatible interface. It is not the official API of any model vendor, so there is no dedicated LangChain package for it and none is needed. You can also use the prefix form, which does the same thing:

llm = init_chat_model(
    "openai:uncensored",
    base_url="https://api.contentmoderationapis.com/v1",
    api_key=os.environ["API_KEY"],
)

If you prefer the class directly, ChatOpenAI(model="uncensored", base_url=..., api_key=...) gives an identical object. Use whichever reads better in your codebase. The factory is handy when the model name comes from config and you want one line to swap providers later.

Keep the key and URL out of the code

Put the key in an environment variable and read it at startup. A .env file loaded with python-dotenv works fine in development.

export API_KEY="your-key-here"
export API_BASE="https://api.contentmoderationapis.com/v1"
import os
from langchain.chat_models import init_chat_model

llm = init_chat_model(
    "uncensored",
    model_provider="openai",
    base_url=os.environ["API_BASE"],
    api_key=os.environ["API_KEY"],
)

Passing both values explicitly is safer than relying on default environment variables. If you already have OPENAI_API_KEY set for another project, an implicit lookup could send the wrong key to the wrong host. Explicit arguments remove that risk.

You can get a key on the API key page. Sign-up is with Google or with email and password, and the trial credit is claimed with one click on that same page.

Streaming, messages and parameters

Streaming goes over SSE, and LangChain's stream method consumes it for you. Each chunk carries a small piece of text.

from langchain_core.messages import SystemMessage, HumanMessage

messages = [
    SystemMessage("You are a blunt editor. Keep answers under 80 words."),
    HumanMessage("Tighten this: the meeting that we had was a long one."),
]

for chunk in llm.stream(messages):
    print(chunk.content, end="", flush=True)

Sampling settings are passed through to the model. temperature, top_p, stop, seed and the frequency and presence penalties are all accepted. Set them in init_chat_model for a default, or per call with llm.bind(temperature=0.2).

The context window is 100,000 tokens, prompt plus completion. You do not have to set max_tokens; if you leave it out, the completion can use whatever room is left. For chains that summarize long documents, set a cap anyway so a runaway answer does not cost more than you planned.

Tool calling and JSON output

Tool calling follows the OpenAI format, so bind_tools works as in the LangChain docs. Define a function with the @tool decorator, bind it, and read the calls from the response.

from langchain_core.tools import tool

@tool
def get_order_status(order_id: str) -> str:
    # Return the status of an order by its id.
    return "shipped"

llm_tools = llm.bind_tools([get_order_status])
reply = llm_tools.invoke("Where is order 8841?")
print(reply.tool_calls)

Your code runs the tool and sends the result back as a message with the tool role. In LangChain you append a ToolMessage with the matching tool_call_id and invoke the model again.

For structured output, JSON mode is available through response_format. The simplest route in LangChain is the json_mode method of with_structured_output:

from pydantic import BaseModel

class Ticket(BaseModel):
    category: str
    urgency: int

structured = llm.with_structured_output(Ticket, method="json_mode")
result = structured.invoke(
    "Return JSON with keys category and urgency (1-5) for: 'Site is down for all users.'"
)
print(result)

Describe the keys in the prompt. JSON mode makes the reply a JSON object, but it does not know your schema, so the prompt has to name the fields. Pydantic then validates the shape on your side. Our quickstart docs list the supported request fields in one place.

Switching models without rewriting code

One reason to use init_chat_model at all is that the model becomes a config value. Read the model name, provider and base URL from settings, and the rest of your chain never learns which backend it is talking to. A small helper keeps that tidy:

import os
from langchain.chat_models import init_chat_model

def build_llm(**overrides):
    params = {
        "model": os.environ.get("LLM_MODEL", "uncensored"),
        "model_provider": "openai",
        "base_url": os.environ.get("LLM_BASE_URL", "https://api.contentmoderationapis.com/v1"),
        "api_key": os.environ["API_KEY"],
        "temperature": 0.7,
    }
    params.update(overrides)
    return init_chat_model(**params)

creative = build_llm(temperature=1.0)
precise = build_llm(temperature=0.1, max_tokens=300)

This gives you a creative model for drafting and a precise one for extraction, both sharing the same key. Keep in mind that every model object makes its own requests, so two chains running at once still share the same limit of 8 concurrent requests on a full key.

Be careful with one habit: do not assume features of another provider carry over. This API is text only, so image inputs, embeddings and fine-tuning calls will not work, and LangChain components that rely on them need a different backend. For a vector store you would run embeddings elsewhere and use this API only for generation.

Rate limits and batch jobs

This is where LangChain users hit trouble. A chain run with batch or a RunnableParallel can fire many requests at once. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. A streamed request holds its slot until the stream ends, so long streams count against concurrency for their whole duration.

Cap the fan-out in the run config:

prompts = [f"Summarize document {i} in one line." for i in range(40)]
results = llm.batch(prompts, config={"max_concurrency": 6})

Going over a limit returns HTTP 429. The error code is rate_limited for requests per minute and concurrency for too many at once. On temporary overload you also get a 429 with a Retry-After: 5 header. ChatOpenAI retries on its own; you can raise the count with max_retries=4 when creating the model. Retries that wait a few seconds are usually enough, but a steady stream of 429s means you should lower max_concurrency rather than retry harder.

Responses include X-Balance-USD, X-Request-Id and the rate limit headers. Log the request ID when you open a support ticket.

Common errors and what they mean

  • 401 or authentication error. The key is missing or wrong, or api_key was not passed and an unrelated key was picked up from the environment. Pass it explicitly.
  • 404 or model not found. The model ID must be exactly uncensored. You can confirm what the server offers with GET /v1/models.
  • Connection errors to api.openai.com. The base URL was not applied. Check you wrote base_url in init_chat_model, and that the URL ends in /v1.
  • 429 with concurrency. Too many parallel calls. Lower max_concurrency.
  • Truncated JSON. Output hit your max_tokens cap. Raise it, or ask for shorter fields.

Failed or refused requests are not charged, so debugging a bad configuration does not eat your credit.

Cost of a LangChain test run

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, pay as you go from prepaid credit. Suppose an agent run uses 4 model calls of about 2,000 input tokens and 300 output tokens each. That is 8,000 input tokens and 1,200 output tokens.

Input: 8,000 / 1,000,000 x $0.15 = $0.0012. Output: 1,200 / 1,000,000 x $0.50 = $0.0006. Total: $0.0018 per run, so the $0.50 trial credit covers about 277 such runs. Agent loops grow the prompt on every step, so measure your own numbers before trusting this estimate. The pricing page lists the top-up amounts and bonuses.

Questions and answers

Which model_provider do I use for a custom OpenAI-compatible endpoint?

Use "openai" and pass base_url and api_key to init_chat_model. The endpoint speaks the OpenAI protocol, so the standard integration handles it.

Do I need a special LangChain package for this API?

No. The langchain-openai package is enough, since the API accepts standard OpenAI chat completion requests with the model ID uncensored.

Does init_chat_model support tool calling with this API?

Yes. Tool calling uses the OpenAI format, so bind_tools works, including streamed tool calls. Send tool results back as tool role messages.

How many parallel requests can LangChain make?

A full key allows 8 concurrent requests and 300 per minute. A trial key allows 2 and 60. Set max_concurrency in the run config to stay under them.

Your key is one form away

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

Get API key