LangChain init_chat_model with a GLM-Style Endpoint
If you searched for langchain init_chat_model glm, the working answer is short: treat the endpoint as an OpenAI provider, set the base URL and the model ID uncensored, and everything else in LangChain stays the same.
Updated
Key points
- Call init_chat_model with model_provider set to openai and pass base_url and api_key explicitly.
- Install langchain and langchain-openai; no vendor-specific package is needed.
- Streaming, bind_tools and JSON mode all work through the normal LangChain interfaces.
- Cap max_concurrency to stay inside the 8-request limit of a full key.

The working call
The helper init_chat_model picks a chat model class from a provider name. This service speaks the OpenAI chat completions protocol, so the provider is openai and the only changes are the base URL and the key. The question behind langchain init_chat_model glm is usually "which provider string do I use?", and the answer is the OpenAI one.
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.glmapi.top/v1",
api_key=os.environ["GLM_KEY"],
temperature=0.7,
)
print(llm.invoke("Name three uses for a paperclip.").content)
The model is one open-weight model run by an independent provider, tuned to answer without content refusals for lawful adult use. It is not an official vendor API, so no vendor-named provider package applies. Get a key from the key page if you do not have one yet.
Check the connection before building a chain
When a LangChain script fails, the cause is often the connection and not the chain. Before you debug prompts, send one plain request outside LangChain and confirm that the key, the base URL and the model ID are accepted.
curl https://api.glmapi.top/v1/chat/completions \
-H "Authorization: Bearer $GLM_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "uncensored", "messages": [{"role": "user", "content": "ping"}], "max_tokens": 5}'
If that works and the LangChain call does not, the problem sits in your arguments: a missing base_url, a variable that holds an old key, or an import from the wrong package. If both fail, the key is the suspect, and the docs list the headers to check. Failed requests are not charged, so repeated test calls cost nothing while you sort this out.
It also helps to turn on LangChain's debug output for a single run. Seeing the exact base URL in the log settles most arguments about which host a request really went to.
Why the provider is openai
LangChain looks at model_provider to decide which integration package to import. Names such as anthropic or google_genai load classes that talk to those vendors' own APIs, with their own request formats. Pointing one of them at this base URL would send the wrong payload.
The openai provider loads ChatOpenAI from langchain-openai, which sends standard POST /v1/chat/completions requests. Any server that implements that route can be used by overriding base_url. That is what you are doing here.
You can also write the model string as "openai:uncensored" and skip the keyword. Both forms are equivalent:
import os
from langchain.chat_models import init_chat_model
llm = init_chat_model(
"openai:uncensored",
base_url="https://api.glmapi.top/v1",
api_key=os.environ["GLM_KEY"],
)
If you prefer to skip the helper, ChatOpenAI accepts the same arguments directly:
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.glmapi.top/v1",
api_key=os.environ["GLM_KEY"],
)
The helper is handy when the model is chosen at run time, for example from a config file. Use the class directly when the model is fixed.
Environment variables instead of arguments
The OpenAI integration also reads OPENAI_API_KEY and OPENAI_BASE_URL from the environment, which keeps secrets out of the code:
export OPENAI_API_KEY="your-key"
export OPENAI_BASE_URL="https://api.glmapi.top/v1"
from langchain.chat_models import init_chat_model
llm = init_chat_model("uncensored", model_provider="openai")
This is convenient for one provider and risky when a project talks to two. If another part of your app uses the real OpenAI API with the same variable names, the two will collide. In that case pass base_url and api_key explicitly, as in the first example, and use a differently named variable such as GLM_KEY for this key.
Streaming, messages and token usage
Streaming works through the standard stream method. The service sends Server-Sent Events and reports usage at the end of the stream.
import os
from langchain.chat_models import init_chat_model
from langchain_core.messages import SystemMessage, HumanMessage
llm = init_chat_model(
"uncensored",
model_provider="openai",
base_url="https://api.glmapi.top/v1",
api_key=os.environ["GLM_KEY"],
)
messages = [
SystemMessage("You are a concise technical editor."),
HumanMessage("Rewrite: the thing is not working good."),
]
for chunk in llm.stream(messages):
print(chunk.content, end="", flush=True)
For a non-streaming call, response.usage_metadata holds input and output token counts. Multiply them by the rates ($0.15 per 1M input, $0.50 per 1M output) and you have the cost of the call. For example, a chain step with 3,000 input tokens and 1,000 output tokens costs 3,000 × $0.15 / 1,000,000 + 1,000 × $0.50 / 1,000,000 = $0.00045 + $0.0005 = $0.00095.
Remember that a streamed request holds one of your concurrency slots until the stream ends. If you break out of the loop early, close the stream so the slot is released.
Tools and structured output
Tool calling follows the OpenAI format, so bind_tools works as documented in LangChain. Tool results go back as messages with the tool role, which LangChain's ToolMessage produces for you.
import os
from langchain.chat_models import init_chat_model
from langchain_core.tools import tool
@tool
def get_word_count(text: str) -> int:
'''Count the words in a text.'''
return len(text.split())
llm = init_chat_model(
"uncensored",
model_provider="openai",
base_url="https://api.glmapi.top/v1",
api_key=os.environ["GLM_KEY"],
)
llm_tools = llm.bind_tools([get_word_count])
ai = llm_tools.invoke("How many words are in: the quick brown fox?")
print(ai.tool_calls)
For structured output, use JSON mode explicitly. The service supports response_format with the type json_object:
import os
from pydantic import BaseModel
from langchain.chat_models import init_chat_model
class Ticket(BaseModel):
title: str
priority: str
llm = init_chat_model(
"uncensored",
model_provider="openai",
base_url="https://api.glmapi.top/v1",
api_key=os.environ["GLM_KEY"],
)
structured = llm.with_structured_output(Ticket, method="json_mode")
print(structured.invoke(
"Return JSON with keys title and priority for: login page crashes on submit."
))
With JSON mode, the prompt itself should say that you want JSON and name the keys, as shown above. The mode constrains the output to valid JSON but does not guess your schema. Always validate the parsed result, because a small model will occasionally return a field with the wrong type.
Async code and LangGraph
The same model object works in async code. Use ainvoke, astream and abatch instead of the sync methods. LangGraph agents accept the object as their model without changes, so an agent built around init_chat_model needs no special case for this endpoint. Because agent loops call the model once per step, a ten-step run issues ten requests. Count them against the 300-per-minute ceiling if several users share one key.
A practical way to size a deployment: measure the average number of model calls per user task, multiply by tasks per minute at peak, and compare the result with 300. Then check concurrency separately. Eight simultaneous requests is a different limit, and slow long replies hold slots longer than short ones. If peak load exceeds either number, queue the work on your side. Rejected requests are not charged, but a queue gives users a smooth experience where retries give them delays.
Rate limits inside chains and agents
LangChain makes it easy to fan out: batch, parallel branches and agents that call several tools can all open requests at once. A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60. Past those numbers you get HTTP 429 with the code concurrency or rate_limited.
Set the limit on your side instead of discovering it from errors:
import os
from langchain.chat_models import init_chat_model
llm = init_chat_model(
"uncensored",
model_provider="openai",
base_url="https://api.glmapi.top/v1",
api_key=os.environ["GLM_KEY"],
max_retries=4,
)
prompts = [f"Summarize item {i} in one line." for i in range(40)]
answers = llm.batch(prompts, config={"max_concurrency": 6})
Six leaves headroom under the limit of 8, which matters if another process uses the same key. max_retries lets the underlying client retry on 429, and when the service is briefly overloaded it sends Retry-After: 5. On a trial key, drop max_concurrency to 2.
The context window is 100,000 tokens for prompt plus completion, so agents that append every tool result to the history will eventually hit it. Trim or summarize older messages, and read the docs for the details of the request format. Prices are on the pricing page.
Common mistakes
- Using the wrong provider string. A vendor-specific provider sends a different request format. Use
openai. - Forgetting
base_url. Without it the request goes to the real OpenAI host and your key is rejected there. - Using a different model name. The only model ID is
uncensored. Check it withGET /v1/models. - Importing a stale package.
init_chat_modellives inlangchain.chat_modelsin current releases. If the import fails, upgradelangchainandlangchain-openaitogether. - Expecting other modalities. This is a text-only API. There is no image or audio generation and no embeddings endpoint, so a vector store needs embeddings from somewhere else.
More guides
Questions and answers
Which model_provider should I pass to init_chat_model?
Pass openai, because the endpoint implements the OpenAI chat completions protocol. Then set base_url to https://api.glmapi.top/v1 and the model to uncensored.
Do I need a special LangChain package?
No. langchain and langchain-openai are enough. There is no vendor-specific integration for this service.
Does LangChain tool calling work here?
Yes. The API supports tools, tool_choice and streamed tool calls, so bind_tools and agents behave as they do with other OpenAI-compatible models.
Why do I get HTTP 429 in a batch run?
You are over the concurrent-request or per-minute limit. Lower max_concurrency in the run config; a full key allows 8 at once and a trial key allows 2.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.
Get API key