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.

Updated LangChainPythonJavaScript

Quick answer

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 set use_responses_api=True, reasoning={...}, output_version="responses/v1", include, truncation or use_previous_response_id, or bind a built-in tool such as web search. Remove those, or force use_responses_api=False.
  • Reasoning text is missing. ChatOpenAI keeps only standard OpenAI fields and drops provider extensions such as reasoning_content. The final answer in .content is unaffected. /docs/reasoning explains what Abliterator returns.
  • strict=True tools fail validation. Strict schemas cannot have optional arguments. Give every parameter a type and no default, or drop strict.
  • The request goes to api.openai.com. A ChatOpenAI built elsewhere (for example init_chat_model("openai:...") without base_url) ignores the client you configured. Pass base_url and api_key there too.
  • Many parallel calls hit 429. batch() and agents can fan out quickly. Set max_concurrency in 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. baseURL was set at the top level of the constructor. Move it into configuration.
  • 404 on /v1/responses. ChatOpenAI switches to the Responses API when useResponsesApi: true is set, when you bind a built-in tool such as web search, or when you pass text, truncation, include, previous_response_id or reasoning.summary. Abliterator only serves Chat Completions, so drop those options.
  • OpenAIError: Missing credentials. apiKey was undefined because ABL_API_KEY is not exported in the process environment. LangChain then looked for OPENAI_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. Use model, and apiKey instead of openAIApiKey.

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.

Try it in your browser.

Ask it something your usual model refuses.

Start a chat

No sign-up to try. $10 free when you verify your email.