EN ▾
Get API key

LangChain OpenAI Compatible API: Setup and Examples

Updated:

To use a LangChain OpenAI compatible API, you keep the ChatOpenAI class and change two arguments: the base URL and the key. This page gives working Python and JavaScript code for this hosted text API, then covers streaming, tools, JSON output and the limits that matter once you run agents.

A chain of linked glowing nodes connecting a laptop to a server, representing LangChain calling a compatible API

Key points

  • ChatOpenAI works unchanged: set base_url to the site's /v1 address, pass your key and use the model <code>uncensored</code>.
  • Streaming, tool calling and JSON mode are all supported by the API, so LangChain's streaming and bind_tools paths apply.
  • Agent loops resend context on every step, so cap parallelism at the 8 concurrent requests a full key allows.
  • A typical five-step agent run with small prompts costs a fraction of a cent at $0.15 and $0.50 per 1M tokens.

The short version

LangChain does not care who serves the model, as long as the server speaks the OpenAI chat completions protocol. This API does, so the integration is a constructor call rather than a custom class. Install the partner package, then point it at your endpoint:

pip install langchain-openai
import os
from langchain_openai import ChatOpenAI

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

reply = llm.invoke("Write a two-sentence scene description for a rainy dock at night.")
print(reply.content)

That is the whole integration. Everything built on top of ChatOpenAI (prompt templates, output parsers, chains, LangGraph agents) now talks to this endpoint. If you do not have a key yet, the key page explains how to sign up and claim the $0.50 trial credit, which needs no card.

The model behind the endpoint is one open-weight model, tuned to answer without content refusals for lawful adult use, run by an independent provider. It is not a router, and it is not the official API of any model vendor. In practice that means the model string is always uncensored, and you should not expect to switch models by changing that string.

Python setup in detail

Environment variables

Hard-coding a key in a notebook is how keys end up on GitHub. Export it in your shell and read it in code:

export API_KEY="paste-your-key-here"

The underlying openai library also reads OPENAI_API_KEY and OPENAI_BASE_URL if you prefer to set those and leave the constructor bare. Behaviour around these variable names has shifted between package versions, so passing base_url and api_key explicitly is the safer habit.

Prompt templates and chains

Once the model object exists, the rest is stock LangChain:

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

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a script doctor. Tighten dialogue without changing the plot."),
    ("user", "{scene}"),
])

chain = prompt | llm | StrOutputParser()
print(chain.invoke({"scene": "She said that she was going to leave, and then she did not."}))

Use temperature, top_p and seed the way you would with any OpenAI model. The API passes temperature, top_p, stop, seed and the frequency and presence penalties through to the model.

Max tokens

You can leave max_tokens unset. The window is 100,000 tokens shared between prompt and completion, and a completion may use whatever the prompt leaves free. Set max_tokens when you want a ceiling for budget reasons, for example in a loop that could run away.

JavaScript and TypeScript

The JS package takes the base URL through a configuration object, which is a common source of confusion because the Python version has a top-level argument.

npm install @langchain/openai @langchain/core
import { ChatOpenAI } from "@langchain/openai";

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

const res = await llm.invoke("Summarise this in one line: the ferry leaves at six and the bar closes at five.");
console.log(res.content);

If you see requests going to api.openai.com in your network logs, the configuration.baseURL value did not reach the client. Check for a typo in the key name and for an older package version that expects a different option name.

Streaming

The API streams over server-sent events when the request has stream: true, and it sends token usage at the end of the stream. LangChain's stream method turns that into an iterator of chunks:

llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.stableaudio.cc/v1",
    api_key=os.environ["API_KEY"],
    stream_usage=True,
)

for chunk in llm.stream("Describe a quiet railway station at dawn in four sentences."):
    print(chunk.content, end="", flush=True)

The stream_usage=True flag asks the client to request usage in the stream, so the final chunk carries token counts you can log.

One limit matters here. A streamed request occupies its concurrency slot until the stream ends. If your UI opens a stream and the user wanders off, that slot stays busy. On a full key you have 8 slots, on a trial key 2. Close streams you no longer read.

Tool calling with bind_tools

The API supports the OpenAI tool format: a tools list, tool_choice, streamed tool_calls, and results sent back as messages with role: "tool". LangChain wraps this in bind_tools.

from langchain_core.tools import tool

@tool
def word_count(text: str) -> int:
    """Count the words in a piece of text."""
    return len(text.split())

llm_tools = llm.bind_tools([word_count])
msg = llm_tools.invoke("How many words are in: the quick brown fox jumps over the lazy dog?")
print(msg.tool_calls)

If the model decides to call the tool, msg.tool_calls holds the name and arguments. Running the tool and sending the result back is the loop that LangGraph's prebuilt agents automate. Whether the model picks the right tool, and how reliably it fills in arguments, depends on the model and your prompt, so test with your real tool schemas before you trust a long chain. Keep tool descriptions short and arguments flat.

For agents, tool_choice is a useful lever. Forcing a specific tool on the first step removes one source of drift.

JSON mode for parsers

When a downstream step needs machine-readable output, ask for JSON mode. The API accepts response_format: {"type": "json_object"}, and you can pass it through LangChain with bind:

import json

json_llm = llm.bind(response_format={"type": "json_object"})
out = json_llm.invoke(
    "Return a JSON object with keys title and mood for a short story about a lighthouse keeper."
)
data = json.loads(out.content)
print(data["title"], "-", data["mood"])

Two habits make this dependable. First, say the word JSON in the prompt and describe the keys you want, because JSON mode guarantees valid syntax, not your schema. Second, still wrap json.loads in a try block and retry once on failure. A response that hits the end of the window mid-object is invalid JSON no matter the mode.

Concurrency, retries and cost in agent loops

Agents behave differently from single calls. Each step resends the conversation so far plus the new tool result, so input grows with every turn, and several steps can run at once if you batch.

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. When you exceed a limit the API returns HTTP 429 with the error code rate_limited (too many per minute) or concurrency (too many at once). Brief overload also returns 429, with a Retry-After: 5 header. LangChain helps in two places:

  • ChatOpenAI(max_retries=...) retries failed calls with backoff.
  • llm.batch(inputs, config={"max_concurrency": 4}) caps how many calls a batch runs at once. Keep the number at or below your slot count, and leave headroom if other processes share the key.

Now the money. Take a five-step agent run where the prompt grows as tool results accumulate: 2,000, 2,600, 3,200, 3,800 and 4,400 input tokens, with 150 output tokens at each step.

  • Input total: 16,000 tokens, so 16,000 / 1,000,000 x $0.15 = $0.0024
  • Output total: 750 tokens, so 750 / 1,000,000 x $0.50 = $0.000375
  • Run total: $0.002775, about 0.28 cents

At that rate a $20 top-up pays for roughly 7,200 such runs ($20 / $0.002775). Runs with big retrieved documents or long chat histories will cost more, and the input side dominates, so trimming context is the main saving. Requests that fail or are refused are not charged. The pricing page has the top-up tiers, and the docs list every supported parameter.

Debugging a LangChain call

When something fails, take LangChain out of the picture first. Send the same request with curl and the same key. If curl works and LangChain does not, the problem is in your constructor arguments. If both fail, the problem is the key, the balance or a limit.

Three LangChain-specific traps come up often. The first is a default model name left in place by a template or a saved config: print llm.model_name and confirm it reads uncensored. The second is a proxy or tracing wrapper that rewrites the base URL; check the environment for stray OPENAI_API_BASE or OPENAI_BASE_URL values that override what you passed. The third is hidden retries. With max_retries raised, a failing call can look slow instead of broken, so turn retries down to 0 while you debug and read the actual error.

LangChain's debug and verbose switches print the exact messages sent, which helps when a prompt template inserts more history than you expected. Compare that text with the usage numbers in the response. If the prompt token count is far above what you intended, an unbounded memory object is usually the cause, and a window or summary memory will bring the cost of each agent step down. Each response also carries an X-Request-Id header; keep it in your logs, because it is the quickest way to point support and documentation readers at one specific call.

Where this fits in an audio workflow

The API cannot transcribe or synthesise audio, so on a site about audio tooling it sits in the text layer: after speech-to-text produces a transcript, a LangChain chain can clean it, split it into scenes, label speakers or extract fields as JSON. Before text-to-speech, a chain can rewrite a script for the ear. The speech to text cost breakdown looks at the transcription side of the same pipeline. Prompts are not used for training, but strip anything private from transcripts that the task does not need.

Questions and answers

Does LangChain support OpenAI compatible endpoints?

Yes. ChatOpenAI accepts a custom base URL, so any server that implements the OpenAI chat completions protocol works, including this one.

What goes in the model field?

Use uncensored. The endpoint serves a single model, so there is nothing else to choose.

Can I use streaming and tool calling together?

Yes. The API streams tool_calls over SSE, and LangChain handles the chunks. Test your own tool schemas first, since reliability depends on the model and prompt.

Why do I get HTTP 429 in a LangChain agent?

Either too many requests per minute (rate_limited) or too many at once (concurrency). Lower max_concurrency, close unused streams and retry after the Retry-After delay.

Is there an embeddings model for vector stores?

No. The API is text chat only, so use a separate embeddings provider for retrieval.

Your key is one form away

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

Get API key

$0.50 trial creditGet API key