EN ▾
Get API key
https://api.deepseekapipricing.com/v1

DeepSeek API LangChain Setup: Python and Node

For a deepseek api langchain setup you only need the ChatOpenAI class, a base URL, a key and the model name. This guide covers Python and Node code for chat, streaming, tool calling, JSON output and concurrency, using an independent OpenAI-compatible endpoint rather than the vendor's own API.

Updated

Glowing chain links connecting servers to chat bubbles, representing a LangChain integration with an API

Key points

  1. Use ChatOpenAI with base_url set to https://api.deepseekapipricing.com/v1 and model uncensored.
  2. Pass api_key explicitly so an OpenAI key in your environment is never sent here.
  3. Streaming, bind_tools and JSON mode work through the standard OpenAI-format parameters.
  4. Cap max_concurrency at 8 for a full key, or 2 on a trial key, to avoid 429 errors.

What you need before you start

LangChain talks to any server that implements the OpenAI chat completions protocol, so there is no special integration to install. Your starting point is the same package you would use for OpenAI itself: langchain-openai for Python or @langchain/openai for Node. Only three values change.

  • Base URL: https://api.deepseekapipricing.com/v1
  • Model: uncensored
  • Key: sent as Authorization: Bearer <key>, which the client does for you

A clarification on naming. This endpoint is an independent service running one open-weight model tuned to answer without content refusals for lawful adult use. It is not the official DeepSeek API and not a router across vendors, so the model name is always uncensored, not a vendor model ID. If you need a key, the API key page shows the sign-up steps and the one-click $0.50 trial.

Install and make the first call in Python

Install the packages:

pip install -U langchain-openai langchain-core
# then use base_url https://api.deepseekapipricing.com/v1 and model "uncensored"

Then create the model object. Pass the key explicitly instead of relying on the OPENAI_API_KEY environment variable, which may hold a real OpenAI key that you do not want sent to a different host.

import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.deepseekapipricing.com/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
    temperature=0.7,
    max_retries=2,
)

print(llm.invoke("Say hello in five words.").content)

If this prints a greeting, the connection, the key and the model name are all correct. The most common mistake at this stage is leaving off /v1 in the base URL, which typically produces a not-found error.

Prompts, chains and streaming

From here, LangChain works as usual. A prompt template, the model and an output parser compose into a chain with the pipe operator:

# llm = ChatOpenAI(model="uncensored", base_url="https://api.deepseekapipricing.com/v1", ...)
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_messages([
    ("system", "You write tight, vivid scene descriptions for adult fiction."),
    ("human", "Describe this setting in under 80 words: {setting}"),
])

chain = prompt | llm | StrOutputParser()
print(chain.invoke({"setting": "a flooded subway station at night"}))

Streaming goes over server-sent events. In LangChain you call stream, and each chunk carries a piece of text. Set stream_usage=True on the model if you want token counts at the end of the stream; the API sends usage in the final event.

llm_stream = ChatOpenAI(
    model="uncensored",
    base_url="https://api.deepseekapipricing.com/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
    stream_usage=True,
)

for chunk in llm_stream.stream("Write a four-line poem about a night train."):
    print(chunk.content, end="", flush=True)

A streamed request keeps its concurrency slot until the stream finishes, so if you abandon a stream without closing it, that slot stays busy longer than you expect.

Node and TypeScript

The JavaScript package takes the base URL inside a configuration object:

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

const llm = new ChatOpenAI({
  model: "uncensored",
  apiKey: process.env.UNCENSORED_API_KEY,
  configuration: { baseURL: "https://api.deepseekapipricing.com/v1" },
  maxRetries: 2,
});

const res = await llm.invoke("Say hello in five words.");
console.log(res.content);

const stream = await llm.stream("Write a four-line poem about a night train.");
for await (const chunk of stream) {
  process.stdout.write(chunk.content);
}

Run it as an ES module ("type": "module" in package.json, or a .mjs file). Everything else in the Node API, including prompt templates and runnables, behaves as it does with any other chat model.

Tool calling and agents

The API supports the OpenAI tool format: the tools and tool_choice parameters, streamed tool_calls, and tool results returned as messages with role: "tool". In LangChain you declare tools with a decorator and attach them with bind_tools:

# llm = ChatOpenAI(model="uncensored", base_url="https://api.deepseekapipricing.com/v1", ...)
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, ToolMessage

@tool
def order_status(order_id: str) -> str:
    """Return the shipping status of an order."""
    return f"Order {order_id} left the warehouse yesterday."

llm_tools = llm.bind_tools([order_status])

messages = [HumanMessage("Where is order 1042?")]
ai = llm_tools.invoke(messages)
messages.append(ai)

for call in ai.tool_calls:
    result = order_status.invoke(call["args"])
    messages.append(ToolMessage(content=result, tool_call_id=call["id"]))

print(llm_tools.invoke(messages).content)

Writing the loop by hand once is worth the ten minutes. It shows you exactly what the model returned, which arguments it chose for each call, and where a bad tool description leads to a wrong guess. Once that is clear, switch to a prebuilt agent and keep the hand-written version as a debugging reference.

That is the whole loop by hand: the model asks for a tool, you run it, you return the result, and the model writes the final answer. If you prefer a ready-made agent loop, the langgraph package offers create_react_agent(llm, [order_status]), and you invoke it with {"messages": [("user", "Where is order 1042?")]}.

How well a model chooses tools depends on the model, so test with your real tool schemas. Short, specific tool descriptions and a low temperature help. An agent that makes six calls with a growing history of about 27,000 input tokens in total and 1,800 output tokens costs roughly $0.00405 plus $0.0009, or about half a cent.

Structured output with JSON mode

JSON mode is supported through response_format. Bind it to the model and also say in the prompt that you want JSON with specific keys, since the format flag controls syntax, not your schema:

# llm = ChatOpenAI(model="uncensored", base_url="https://api.deepseekapipricing.com/v1", ...)
import json

json_llm = llm.bind(response_format={"type": "json_object"})

msg = json_llm.invoke(
    "Return a JSON object with keys title (string) and tags (list of 3 strings) "
    "for a short story about a lighthouse keeper."
)
data = json.loads(msg.content)
print(data["title"], data["tags"])

Validate the parsed result with Pydantic or your own checks before you trust it, and handle json.JSONDecodeError with one retry. For large extraction jobs, parse every response defensively rather than assuming the first one is clean.

Retrieval, memory and callbacks

This API has no embeddings endpoint, so a retrieval pipeline needs a separate source of embeddings. Everything after retrieval is plain chat. A typical retrieval chain pulls the top passages from your vector store, pastes them into the prompt, and asks the model to answer from that text. Because the context window is 100,000 tokens, you can afford generous passages, but remember the bill: every token of retrieved context is input at $0.15 per million, so 20,000 tokens of context cost $0.003 per question.

For chat memory, the simplest approach is a message list that you trim by token count before each call. LangChain offers helpers such as trim_messages for this. Keep the system message and the latest turns, and drop or summarize the middle once the history reaches a limit you choose. A smaller history also keeps answers focused, and it lowers the cost of every turn, because the whole history is resent as input each time.

Callbacks are the place to record what a call cost. Each response includes a usage block with prompt and completion tokens, and in LangChain the returned message carries it in usage_metadata:

# llm = ChatOpenAI(model="uncensored", base_url="https://api.deepseekapipricing.com/v1", ...)
msg = llm.invoke("Name three rivers.")
u = msg.usage_metadata
cost = u["input_tokens"] * 0.15 / 1_000_000 + u["output_tokens"] * 0.50 / 1_000_000
print(u, f"${cost:.6f}")

Log the cost with the request ID so a surprising bill can be traced to one chain.

System prompts and tone

The model has no built-in content refusals, so the system message is where you set the behavior of your product: the persona, the tone, the topics it should avoid and the format of the reply. Write it as you would a brief for a new colleague. Short and specific works better than long and vague. Content involving minors is a hard limit on this service, so do not build prompts that approach it.

A short checklist before you ship

  • The key lives in an environment variable or a secret store, never in the repository.
  • max_concurrency is set to your key's limit, or below it if other services share the key.
  • Retries use a short back-off, and 429 responses with Retry-After: 5 are honored.
  • Streams are closed on client disconnect so slots are freed.
  • JSON outputs are parsed defensively and validated.
  • Costs are logged per chain from the usage block.
  • A fallback exists for the case where the endpoint is unreachable, even if the fallback is an error message.

Follow that list and the integration will behave like any other LangChain chat model. The difference is on the content side, where requests that other models decline for lawful adult use are answered.

Rate limits, concurrency and common errors

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent requests and 60 per minute. The request body can be up to 8 MB, and the context window is 100,000 tokens covering prompt and completion together.

LangChain's batch helpers fan out requests, so set a ceiling that matches your key:

# llm = ChatOpenAI(model="uncensored", base_url="https://api.deepseekapipricing.com/v1", ...)
inputs = [{"setting": s} for s in ["a rooftop garden", "a desert diner", "a quiet harbor"]]
results = chain.batch(inputs, config={"max_concurrency": 8})

Use 2 instead of 8 on a trial key. When you exceed a limit, the API returns HTTP 429 with the error code rate_limited (too many requests per minute) or concurrency (too many at once). On temporary overload it also returns 429, with a Retry-After: 5 header. The max_retries setting in the client handles transient cases, but if you see the error code concurrency repeatedly, lower max_concurrency instead of adding retries.

  • Not-found errors on every call: check that the base URL ends in /v1.
  • Authentication error: the key is missing or has a typo; confirm it is passed through api_key.
  • Model errors: the model name must be exactly uncensored.
  • Slow batch runs: stalled streams hold concurrency slots, so close them or set a timeout.

Pricing is $0.15 per million input tokens and $0.50 per million output tokens, and failed or refused requests are not charged. The pricing page lists top-ups, and the documentation covers every parameter and the response headers, including X-Request-Id and X-Balance-USD, which are handy to log in a LangChain callback.

01

Questions and answers

Which LangChain class should I use?

Use ChatOpenAI from langchain-openai in Python, or ChatOpenAI from @langchain/openai in Node. Set the base URL to https://api.deepseekapipricing.com/v1 and the model to uncensored.

Does streaming work with LangChain?

Yes. The API streams over SSE and sends usage at the end, so llm.stream works. Set stream_usage=True if you want token counts in the stream.

Can I use embeddings or vector stores here?

Not from this API. It is text only and has no embeddings endpoint, so use a separate embedding source for retrieval and send the retrieved text here.

Why do I get HTTP 429?

Either you exceeded the per-minute limit (rate_limited), sent too many requests at once (concurrency), or the provider was briefly overloaded. Lower max_concurrency and respect Retry-After.

Your key is one form away

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

Get API key