LangChain with Abliterator: Python and JavaScript
Run LangChain and LangChain.js on Abliterator with ChatOpenAI: where the base URL goes in each, streaming with usage, tool agents and structured output.
Python: ChatOpenAI(model="kimi-k3.1-pro-abliterated", base_url="https://abliterator.ai/v1", api_key=os.environ["ABL_API_KEY"]). JavaScript: new ChatOpenAI({ model: "kimi-k3.1-pro-abliterated", apiKey: process.env.ABL_API_KEY, configuration: { baseURL: "https://abliterator.ai/v1" } }); in LangChain.js the base URL sits inside configuration.
This page covers Python and JavaScript. Each section is complete on its own, with install steps, a first request, streaming and the LangChain-specific settings that trip people up.
Python
LangChain reaches OpenAI-compatible servers through ChatOpenAI in the langchain-openai package. Set base_url and api_key and every Runnable, chain and agent built on it uses Abliterator. Tested with langchain 1.5 and langchain-openai 1.8; the parameters are documented in LangChain's ChatOpenAI integration guide.
Install
pip install langchain langchain-openai
export ABL_API_KEY="sk-abl-v1-..."
Connect ChatOpenAI to Abliterator
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="kimi-k3.1-pro-abliterated",
base_url="https://abliterator.ai/v1",
api_key=os.environ["ABL_API_KEY"],
max_tokens=1024,
)
reply = llm.invoke(
[
("system", "You write detection content for a SOC."),
("human", "Describe three log signals that suggest a web shell on an IIS server."),
]
)
print(reply.content)
print(reply.usage_metadata)
base_url is an alias for openai_api_base. Explicit arguments win over the OPENAI_API_BASE and OPENAI_BASE_URL environment variables.
Streaming
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="deepseek-v4.1-flash-abliterated",
base_url="https://abliterator.ai/v1",
api_key=os.environ["ABL_API_KEY"],
stream_usage=True,
)
total = None
for chunk in llm.stream("Explain how admins review and revoke risky OAuth consent grants, for an awareness training."):
print(chunk.content, end="", flush=True)
total = chunk if total is None else total + chunk
print("\n", total.usage_metadata)
Adding chunks merges them into one AIMessageChunk, so total.usage_metadata holds the token counts from Abliterator's final usage event. astream and astream_events work the same way.
A tool-calling agent with create_agent
LangChain 1.x builds agents with create_agent. It loops between the model and your tools until the model answers in text:
import os
from langchain.agents import create_agent
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
@tool
def lookup_ioc(indicator: str) -> str:
"""Look up an IP, domain or hash in the internal threat-intel store."""
return f"{indicator}: seen in 3 incidents, last 2026-11-02, tagged 'commodity loader'"
llm = ChatOpenAI(model="kimi-k3.1-pro-abliterated", base_url="https://abliterator.ai/v1", api_key=os.environ["ABL_API_KEY"])
agent = create_agent(
llm,
tools=[lookup_ioc],
system_prompt="You are a threat-intel assistant. Use tools before answering.",
)
result = agent.invoke({"messages": [{"role": "user", "content": "Is 203.0.113.50 known to us?"}]})
print(result["messages"][-1].content)
For typed output without an agent, llm.with_structured_output(MyPydanticModel) defaults to the json_schema method on ChatOpenAI, which Abliterator passes through as response_format. See /docs/structured-outputs.
Troubleshooting
- 404 on
/v1/responses. ChatOpenAI switched to the Responses API. That happens when you setuse_responses_api=True,reasoning={...},output_version="responses/v1",include,truncationoruse_previous_response_id, or bind a built-in tool such as web search. Remove those, or forceuse_responses_api=False. - Reasoning text is missing.
ChatOpenAIkeeps only standard OpenAI fields and drops provider extensions such asreasoning_content. The final answer in.contentis unaffected. /docs/reasoning explains what Abliterator returns. strict=Truetools fail validation. Strict schemas cannot have optional arguments. Give every parameter a type and no default, or dropstrict.- The request goes to api.openai.com. A
ChatOpenAIbuilt elsewhere (for exampleinit_chat_model("openai:...")withoutbase_url) ignores the client you configured. Passbase_urlandapi_keythere too. - Many parallel calls hit 429.
batch()and agents can fan out quickly. Setmax_concurrencyin the run config to stay under your plan's concurrent-request limit (/pricing).
JavaScript
In LangChain.js, OpenAI-compatible servers are reached through ChatOpenAI from @langchain/openai. The one detail that differs from Python: the base URL sits under configuration, as the LangChain.js ChatOpenAI docs show. Examples were run with langchain 1.6, @langchain/openai 1.8 and Node 22 as ES modules.
Install
npm install langchain @langchain/openai @langchain/core zod
export ABL_API_KEY="sk-abl-v1-..."
Connect ChatOpenAI to Abliterator
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "kimi-k3.1-pro-abliterated",
apiKey: process.env.ABL_API_KEY,
configuration: { baseURL: "https://abliterator.ai/v1" },
maxTokens: 1024,
});
const reply = await llm.invoke([
["system", "You are an application security reviewer."],
["human", "List the checks you would run on a JWT implementation during an authorized assessment."],
]);
console.log(reply.content);
console.log(reply.usage_metadata);
Streaming
.stream() yields AIMessageChunks. Concatenating them with .concat() gives one message whose usage_metadata comes from Abliterator's closing usage event:
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "deepseek-v4.1-flash-abliterated",
apiKey: process.env.ABL_API_KEY,
configuration: { baseURL: "https://abliterator.ai/v1" },
});
let full;
for await (const chunk of await llm.stream("Explain the difference between EDR and XDR telemetry in five bullets.")) {
process.stdout.write(typeof chunk.content === "string" ? chunk.content : "");
full = full ? full.concat(chunk) : chunk;
}
console.log("\n", full.usage_metadata);
streamUsage defaults to true in LangChain.js, so you do not need to set it.
A tool agent with createAgent
createAgent from the langchain package runs the model-tool loop for you. Tools are defined with tool() and a Zod schema:
import { createAgent, tool } from "langchain";
import { ChatOpenAI } from "@langchain/openai";
import { z } from "zod";
const whois = tool(
async ({ domain }) => `${domain}: registered 2026-11-20, privacy-protected, hosted on a network with many abuse reports`,
{
name: "whois_lookup",
description: "Return cached WHOIS facts for a domain.",
schema: z.object({ domain: z.string() }),
},
);
const llm = new ChatOpenAI({
model: "kimi-k3.1-pro-abliterated",
apiKey: process.env.ABL_API_KEY,
configuration: { baseURL: "https://abliterator.ai/v1" },
});
const agent = createAgent({
model: llm,
tools: [whois],
systemPrompt: "You triage suspicious domains for the security operations team.",
});
const result = await agent.invoke({
messages: [{ role: "user", content: "Should we block login-verify-account.example? Check it first." }],
});
console.log(result.messages.at(-1).content);
Structured output with Zod
withStructuredOutput returns parsed objects instead of messages:
import { ChatOpenAI } from "@langchain/openai";
import { z } from "zod";
const Advisory = z.object({
title: z.string(),
severity: z.enum(["low", "medium", "high", "critical"]),
mitigations: z.array(z.string()),
});
const llm = new ChatOpenAI({
model: "kimi-k3.1-pro-abliterated",
apiKey: process.env.ABL_API_KEY,
configuration: { baseURL: "https://abliterator.ai/v1" },
});
const advisory = await llm
.withStructuredOutput(Advisory, { name: "advisory" })
.invoke("Write a short internal advisory about an exposed Redis instance with no auth.");
console.log(advisory.severity, advisory.mitigations);
Use z.nullable() rather than z.optional() for fields the model may leave empty; strict JSON schemas cannot have optional properties.
Troubleshooting
- The request goes to api.openai.com.
baseURLwas set at the top level of the constructor. Move it intoconfiguration. - 404 on
/v1/responses. ChatOpenAI switches to the Responses API whenuseResponsesApi: trueis set, when you bind a built-in tool such as web search, or when you passtext,truncation,include,previous_response_idorreasoning.summary. Abliterator only serves Chat Completions, so drop those options. OpenAIError: Missing credentials.apiKeywas undefined becauseABL_API_KEYis not exported in the process environment. LangChain then looked forOPENAI_API_KEY.- Agent stops with a recursion error. The model kept calling tools. Make tool outputs conclusive, or raise the limit with
agent.withConfig({ recursionLimit: 50 }). - Deprecation warnings for
modelName. It is an old alias. Usemodel, andapiKeyinstead ofopenAIApiKey.
Frequently asked questions
Why do I get no token usage when streaming from LangChain?
ChatOpenAI turns stream_usage on only for the default OpenAI URL. With a custom base_url it stays off, so pass stream_usage=True and the final chunk will carry usage_metadata.
How do I set reasoning effort without breaking the request?
Use the reasoning_effort field on ChatOpenAI. The reasoning={...} dict is a Responses API parameter, and setting it makes LangChain switch to /v1/responses, which Abliterator does not serve.
Does create_agent work with Abliterator models?
Yes. create_agent drives the model through standard tool calls on Chat Completions, which both Abliterator models support. The example on this page runs a one-tool agent end to end.
Where does the base URL go in LangChain.js?
Inside configuration: new ChatOpenAI({ configuration: { baseURL } }). configuration is passed straight to the OpenAI SDK client, so baseURL, defaultHeaders and timeout options all go there.
Does LangChain.js keep the reasoning text Abliterator returns?
Yes. The Chat Completions converter copies a reasoning_content field into additional_kwargs.reasoning_content on the message and on stream chunks, while content holds the answer.
Can I use createAgent from the langchain package with Abliterator?
Yes. createAgent calls the model with standard tool definitions and runs your tools between turns. Pass it the ChatOpenAI instance rather than a model string, so it uses your Abliterator base URL.