This page shows how to use a custom OpenAI endpoint in LangChain for Python, so ChatOpenAI and OpenAIEmbeddings call open models you deployed on BitsRun. At the end you will chat, stream, call tools and embed text, with the two settings that trip people up on non-OpenAI servers. It takes about 10 minutes once you have an endpoint.
Checked against the LangChain docs and langchain-openai 1.8.0 source on 2026-11-14.
What you get
| Package | langchain-openai |
| Chat | ChatOpenAI(base_url=..., api_key=..., model=...) |
| Embeddings | OpenAIEmbeddings(..., check_embedding_ctx_length=False) |
| Streaming and tools | Supported (tools need a model trained for them) |
| Cost when idle | Nothing. Endpoints sleep and wake on the next request |
Before you start
A BitsRun chat endpoint, and an embedding endpoint if you want vectors. Follow Deploy your first model or Deploy an Ollama model to the cloud.
Each base URL,
https://<endpoint-id>.endpoint.bitsrun.com/v1, from the Copy button on the endpoint card.<endpoint-id>is the endpoint's id.An API key starting with
brk_(see API keys).Python 3 with the package installed:
bashpip install -U langchain-openai
How to use ChatOpenAI with a custom base URL
Save your key in an environment variable:
bashexport BITSRUN_API_KEY="brk_your_key"Create
chat.py:pythonimport os from langchain_openai import ChatOpenAI llm = ChatOpenAI( base_url="https://<endpoint-id>.endpoint.bitsrun.com/v1", api_key=os.environ["BITSRUN_API_KEY"], model="qwen3:8b", timeout=600, max_retries=2, ) print(llm.invoke("Give me one tip for writing clear emails.").content)Run
python chat.py. You should see one short tip.
model is the name you deployed. An endpoint serves exactly one model and always uses it. timeout=600 (seconds) covers a cold start; see below.
How to stream and call tools
Streaming prints the reply as it is written:
for chunk in llm.stream("Write a haiku about trains."):
print(chunk.content, end="", flush=True)Tool calls use bind_tools, as in the LangChain ChatOpenAI docs:
from pydantic import BaseModel, Field
class GetWeather(BaseModel):
"""Get the current weather in a given location"""
location: str = Field(description="The city and state, e.g. San Francisco, CA")
llm_with_tools = llm.bind_tools([GetWeather])
ai_msg = llm_with_tools.invoke("what is the weather like in San Francisco")
print(ai_msg.tool_calls)You should see a list with one GetWeather call. This needs a model trained for tools: run bitsrun size <model> --json and look for "tools": true. See Tool calling.
How to use OpenAIEmbeddings with a non-OpenAI server
Point OpenAIEmbeddings at an embedding endpoint and turn off its length check:
import os
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(
base_url="https://<embedding-endpoint-id>.endpoint.bitsrun.com/v1",
api_key=os.environ["BITSRUN_API_KEY"],
model="snowflake-arctic-embed-l-v2.0",
check_embedding_ctx_length=False,
)
vector = embeddings.embed_query("How do I reset my password?")
vectors = embeddings.embed_documents(["First document", "Second document"])
print(len(vector))Why check_embedding_ctx_length=False: by default, OpenAIEmbeddings splits your text with OpenAI's tokenizer and sends token ids instead of text. The langchain-openai source says to set it to False for non-OpenAI providers so raw text is sent. BitsRun's embedding endpoints expect text. More in Self-hosted embeddings API and Embeddings.
What happens when the endpoint is asleep
The first request after a quiet period wakes the endpoint, and the wait is never billed.
| Model kind | Warm GPU (ran recently) | New GPU machine |
|---|---|---|
| GGUF models on llama.cpp | A few seconds to about 40 seconds | About 2 to 3 minutes |
| Embedding models on Text Embeddings Inference | A few seconds to about 40 seconds | About 2 to 3 minutes |
| Safetensors chat models on vLLM | About 40 seconds | About 3 to 4 minutes |
BitsRun keeps the request open for up to 8 minutes, so set timeout=600. One more setting matters for async streaming (astream): langchain-openai has a stream_chunk_timeout of 120 seconds by default, measured between content chunks. Keep-alive comments are not content, so a cold start on a new GPU machine can trip it. Raise it for async streaming:
llm = ChatOpenAI(
base_url="https://<endpoint-id>.endpoint.bitsrun.com/v1",
api_key=os.environ["BITSRUN_API_KEY"],
model="qwen3:8b",
timeout=600,
stream_chunk_timeout=600,
)Sync stream() is not affected. Read Cold starts for the details.
If something goes wrong
| Message or symptom | What to do |
|---|---|
401 unauthorized | The key is missing, mistyped or revoked. Check BITSRUN_API_KEY. |
404 not_found | Check base_url ends in /v1. Chat calls on an embedding endpoint, or a key limited to another endpoint, also get 404. |
| Embedding requests fail | Add check_embedding_ctx_length=False so text is sent, not token ids. |
402 payment_required | Your balance is $0. Add credit in the dashboard. |
429 rate_limited | Too many requests open at once for your plan. Retry with a short, growing pause. |
| Async stream times out after 2 minutes | Set stream_chunk_timeout=600. |
Error body with model_starting | The model took longer than 8 minutes to wake. Send the request again. |
Every code is on Error codes.
Frequently asked questions
How do I use a self-hosted model with LangChain?
Deploy the model on BitsRun, then create ChatOpenAI with base_url set to your endpoint URL ending in /v1, api_key set to your brk_ key, and model set to the name you deployed.
Does OpenAIEmbeddings need check_embedding_ctx_length=False?
Yes, for BitsRun and most non-OpenAI servers. Without it, LangChain sends OpenAI token ids instead of your text.
Can I set the base URL with an environment variable?
Yes. LangChain reads OPENAI_API_BASE or OPENAI_BASE_URL when you do not pass base_url. Passing it in code is clearer when you also use OpenAI itself.
Can I use LangChain agents with BitsRun?
Yes, with a model that supports tool calls. BitsRun chat endpoints accept tools and tool_choice, which agents rely on.
Next step
Need a model for your chain? See Host a GGUF model as an OpenAI-compatible API. Estimate the cost with the cost calculator, then create your account.