EN ▾
Get API key

LangChain Ollama Set URL: Point It at a Hosted API

Isometric chain of connected blocks linked to a cloud node, illustrating a LangChain pipeline using a hosted model

To make LangChain Ollama set URL behave, you pass a base URL to the chat class. For a local server that is port 11434; for a hosted OpenAI-compatible endpoint you switch to ChatOpenAI and give it the new address.

Updated

Key points

  • ChatOllama talks to Ollama's native API; a hosted OpenAI-compatible endpoint needs ChatOpenAI.
  • Set base_url to https://api.ollamauncensored.cc/v1, model to uncensored, and pass your key.
  • Streaming, tool calling and JSON mode all work through the standard LangChain interfaces.
  • Cap batch concurrency below your key's limit to avoid HTTP 429 errors.

Two classes, two kinds of URL

LangChain ships separate integrations for Ollama and for anything that speaks the OpenAI format, and the difference decides which URL you set. ChatOllama, from the langchain-ollama package, calls Ollama's own routes. It takes a base_url such as http://localhost:11434, with no /v1 suffix, because it adds its own paths. Use it when the target really is an Ollama server, local or remote.

ChatOpenAI, from langchain-openai, calls /v1/chat/completions. Its base_url includes the /v1 part. Any server that implements that route can sit behind it, which includes the hosted endpoint on this site. So the practical rule is simple: if you want LangChain to use this API, set the URL on ChatOpenAI, not on ChatOllama. Pointing ChatOllama at an OpenAI-style endpoint produces 404 errors, because the routes it requests do not exist there.

The settings you need are the same as for any OpenAI client: base URL https://api.ollamauncensored.cc/v1, model ID uncensored, and a bearer key. If you do not have a key yet, create one here; a new account can claim $0.50 of trial credit with no card.

Python: the minimal working setup

Install the packages first:

pip install langchain-openai langchain-core

Then build the model object with the hosted address:

import os
from langchain_openai import ChatOpenAI

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

msg = llm.invoke("Write a one-sentence logline for a heist story.")
print(msg.content)

Older tutorials use the argument names openai_api_base and openai_api_key, and import the class from langchain_community. Both still turn up in search results. Prefer the current langchain_openai import and the base_url and api_key names, since those match the underlying OpenAI SDK.

If you want no URL in code at all, set OPENAI_BASE_URL and OPENAI_API_KEY in the environment. ChatOpenAI picks them up, so ChatOpenAI(model="uncensored") is enough. This is handy when the same project runs against local Ollama in development and a hosted endpoint in production: the code stays identical and only the environment differs.

Streaming, messages and chains

Everything downstream of the model object uses normal LangChain interfaces, so chains written for another provider need no edits beyond the constructor. Here is a prompt-to-model chain that streams tokens:

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
import os

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

prompt = ChatPromptTemplate.from_messages([
    ("system", "You write short scenes for an adult fiction project."),
    ("human", "Scene idea: {idea}"),
])

chain = prompt | llm | StrOutputParser()

for piece in chain.stream({"idea": "two rivals share a night train"}):
    print(piece, end="", flush=True)

Streaming uses server-sent events from the API (stream: true), and the final chunk carries usage counts, which is why stream_usage=True is useful: LangChain can attach token totals to the last message. The 100,000-token window is shared between prompt and completion, so conversation memory buffers can grow large before they cause trouble, but trimming old turns still keeps cost down since input tokens are billed at $0.15 per 1M.

Tools and structured output

The API supports tool calling with tools, tool_choice, streamed tool_calls and results sent back as role: "tool". LangChain wraps this in bind_tools:

from langchain_core.tools import tool

@tool
def roll_dice(sides: int) -> int:
    # Roll a die with the given number of sides.
    import random
    return random.randint(1, sides)

llm_tools = llm.bind_tools([roll_dice])
ai = llm_tools.invoke("Roll a twenty-sided die for me.")
print(ai.tool_calls)

For JSON output, the endpoint supports JSON mode through response_format: {"type":"json_object"}. In LangChain you can bind it directly, and remember to ask for JSON in the prompt text as well:

json_llm = llm.bind(response_format={"type": "json_object"})
out = json_llm.invoke(
    "Return a JSON object with keys name and mood for a tavern keeper."
)
print(out.content)

The model is an open-weight one, so tool-call reliability varies with prompt quality and tool descriptions. Keep tool schemas small, write clear descriptions, and validate the arguments before you run anything with side effects. Sampling parameters such as temperature, top_p, stop, seed and the penalties are passed through, so you can set them on the constructor or per call.

LangChain.js

The JavaScript package uses a nested option for the URL, which is a frequent source of confusion:

import { ChatOpenAI } from "@langchain/openai";

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

const res = await llm.invoke("Suggest a name for a cyberpunk noodle bar.");
console.log(res.content);

The URL goes inside configuration as baseURL, while the model name and key stay at the top level. If you put baseURL at the top level, it is ignored and the client quietly calls the default OpenAI address, then fails on the key. When a JS setup returns an auth error that does not match your key, check that nesting first.

Batching without hitting 429

LangChain's batch and abatch methods run many prompts in parallel, which is where limits show up. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. Exceeding the first returns HTTP 429 with the code concurrency; exceeding the second returns rate_limited. A streamed call keeps its concurrency slot until the stream ends, so streams count for longer than short calls do.

Set the cap explicitly in the config rather than relying on defaults:

prompts = [f"Give one tip about topic {i}." for i in range(40)]
results = llm.batch(prompts, config={"max_concurrency": 6})

A value of 6 leaves headroom under 8 for any other process using the same key. On a trial key, use 2 or less. The max_retries setting on the constructor handles transient errors, and a 429 with Retry-After: 5 means the service is briefly overloaded, so a short wait is the correct response. For the exact numbers behind cost per run, the pricing page shows the token rates, and the docs list the response headers, including X-Balance-USD.

Switching between local and hosted

Many projects want a local model while developing and a hosted one for real traffic. The cleanest way is a small factory function that reads the target from the environment, so no other file knows which backend is active:

import os
from langchain_openai import ChatOpenAI

def make_llm():
    return ChatOpenAI(
        model=os.environ.get("LLM_MODEL", "uncensored"),
        base_url=os.environ.get("LLM_BASE_URL", "https://api.ollamauncensored.cc/v1"),
        api_key=os.environ["API_KEY"],
    )

For the local case, Ollama's OpenAI-style layer at http://localhost:11434/v1 works with the same class, so you can keep ChatOpenAI in both environments and only change LLM_BASE_URL, LLM_MODEL and the key. That removes the need to maintain two code paths. The differences you still have to respect are context size and speed: a local model is bounded by your hardware, while the hosted one gives you a 100,000-token window.

Agent graphs built with LangGraph or similar libraries take the same model object, so the factory works there too. If an agent loops over tools many times, remember that each model call is a separate request, and each one counts against the per-minute limit.

What a LangChain run costs

LangChain adds prompt scaffolding, so inputs run larger than the text you typed. Take a retrieval chain that sends 6,000 input tokens (instructions, retrieved passages and the question) and gets 400 tokens back. Input costs 6,000 x $0.15 / 1,000,000 = $0.0009. Output costs 400 x $0.50 / 1,000,000 = $0.0002. One call is $0.0011. A batch of 1,000 such calls comes to $1.10.

The lesson from the numbers is that input tokens dominate in chain-style work, even though output is priced higher per token. Trimming retrieved context and old chat history saves more than shortening replies. Billing is prepaid with no subscription, failed or refused requests are not charged, and top-ups start at $20; the pricing page has the bonus tiers.

Troubleshooting the URL

  • 404 Not Found. You used ChatOllama against the hosted endpoint, or the base URL lacks /v1. Switch to ChatOpenAI and include the suffix.
  • Calls go to the wrong host. An environment variable overrides your intent. Print llm.openai_api_base to see the effective address.
  • Model not found. A leftover local tag. The model ID here is uncensored.
  • Auth error in JS. The URL or key sits at the wrong level of the options object.
  • Works locally, fails hosted. Check that you replaced the dummy key with a real one.

When nothing obvious explains a failure, turn on LangChain's debug output or call the endpoint with curl using the same URL, key and model. If curl works and LangChain does not, the problem is in the constructor arguments; if both fail, the issue is the key or the account balance. Every response carries an X-Request-Id header, and quoting it in a message to support lets someone find the exact call. Testing with a short prompt first also keeps experiments cheap while you sort out the setup.

Keep one rule in mind: the content rule on this service forbids sexual content involving minors, with no exceptions, and the service is meant for lawful adult use such as fiction, roleplay and companion apps.

Questions and answers

Can ChatOllama use this API?

No. ChatOllama calls Ollama's native routes, which this service does not offer. Use ChatOpenAI with base_url set to https://api.ollamauncensored.cc/v1.

Should the URL end with /v1?

For ChatOpenAI, yes. For ChatOllama against a real Ollama server, no, because it adds its own paths.

What model name do I pass?

Pass uncensored as the model. It is the only model ID, and you can confirm it with GET /v1/models.

How do I avoid rate-limit errors in batches?

Set max_concurrency in the batch config below your key's limit, for example 6 on a full key, which allows 8 concurrent requests.

Your key is one form away

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