Home / Guides / Frameworks and SDKs

LangChain with DeepSeek and GLM: ChatOpenAI setup

Updated 2026-12-04 · Use DeepSeek and GLM in LangChain with ChatOpenAI: first call, streaming, tool calling, structured output, agents, thinking off, LangChain.js.

Connection details

Base URL (OpenAI compatible)
https://api.aifans.fan/v1
API key
Create one in the console; it starts with sk- (no account yet? sign up)
Recommended models
deepseek-v4.1-flash (all models and prices)

LangChain's ChatOpenAI class works with any API that implements OpenAI Chat Completions. Point it at AIFans API with two parameters, base_url and api_key, and your chains, tools, structured output and agents run on deepseek-v4.1-flash, glm-5.3 and the other models here, billed per token.

Install and set your key

Create a key in the console (sign up first if needed) and keep it in an environment variable rather than in code:

pip install -U langchain langchain-openai
export AIFANS_API_KEY="YOUR_API_KEY"   # PowerShell: $env:AIFANS_API_KEY = "YOUR_API_KEY"

Your first call

# pip install -U langchain langchain-openai
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="deepseek-v4.1-flash",
    base_url="https://api.aifans.fan/v1",
    api_key=os.environ["AIFANS_API_KEY"],
    max_tokens=2000,      # thinking counts toward this: do not set it too low
    max_retries=3,        # retries 429 and 5xx with backoff
)
print(llm.invoke("Explain vector databases in two sentences.").content)

model is the model ID from the models page; everything else is standard LangChain.

With init_chat_model

If your code builds models with init_chat_model, pass the provider and the base URL:

from langchain.chat_models import init_chat_model

llm = init_chat_model(
    model="deepseek-v4.1-flash",
    model_provider="openai",
    base_url="https://api.aifans.fan/v1",
    api_key=os.environ["AIFANS_API_KEY"],
)

Or with environment variables only

ChatOpenAI reads OPENAI_API_KEY and OPENAI_BASE_URL, so existing code needs no change at all, only a different model name:

# macOS / Linux
export OPENAI_API_KEY="YOUR_API_KEY"
export OPENAI_BASE_URL="https://api.aifans.fan/v1"
# Windows PowerShell
$env:OPENAI_API_KEY = "YOUR_API_KEY"
$env:OPENAI_BASE_URL = "https://api.aifans.fan/v1"

Streaming

for chunk in llm.stream("Write a haiku about Python."):
    print(chunk.text, end="", flush=True)

# token counts while streaming: ask for them explicitly
llm = ChatOpenAI(model=..., base_url=..., api_key=..., stream_usage=True)

Tool calling

from langchain_core.tools import tool

@tool
def get_weather(city: str) -> str:
    """Return the current weather for a city."""
    return f"Sunny and 24°C in {city}"

llm_with_tools = llm.bind_tools([get_weather])
msg = llm_with_tools.invoke("What's the weather in Lisbon?")
print(msg.tool_calls)   # [{'name': 'get_weather', 'args': {'city': 'Lisbon'}, ...}]

Structured output

Use method="function_calling": it works with any model that supports tool calls. (json_schema relies on OpenAI's own structured-output feature, which other models may not support.)

from pydantic import BaseModel, Field

class Ticket(BaseModel):
    category: str = Field(description="billing, bug or question")
    urgent: bool
    summary: str

extractor = llm.with_structured_output(Ticket, method="function_calling")
ticket = extractor.invoke("I was charged twice this month and need a refund today!")
print(ticket)   # category='billing' urgent=True summary='...'

Agents

LangChain 1.x builds agents with create_agent, which runs on LangGraph and takes any chat model:

from langchain.agents import create_agent

agent = create_agent(
    model=llm,
    tools=[get_weather],
    system_prompt="You are a helpful travel assistant.",
)
result = agent.invoke({"messages": [{"role": "user", "content": "Should I pack an umbrella for Lisbon?"}]})
print(result["messages"][-1].content)

Turn thinking off for simple tasks

Most models here think before they answer, and thinking is billed as output tokens. For classification, extraction or routing, switch it off:

fast = ChatOpenAI(
    model="deepseek-v4.1-flash", base_url="https://api.aifans.fan/v1", api_key=os.environ["AIFANS_API_KEY"],
    extra_body={"thinking": {"type": "disabled"}},   # no thinking: faster and cheaper
)

ChatOpenAI follows the official OpenAI format, so it does not return the model's thinking text (reasoning_content); you get the final answer only. If you need the thinking, call the API with the OpenAI SDK directly, as in the API reference.

Prefer the Anthropic format?

The same models are served on an Anthropic-compatible endpoint, so ChatAnthropic works too:

# pip install -U langchain-anthropic
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(
    model="deepseek-v4.1-flash",
    base_url="https://api.aifans.fan",          # no /v1 here: the client adds /v1/messages
    api_key=os.environ["AIFANS_API_KEY"],
    max_tokens=2000,
)

LangChain.js

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

const llm = new ChatOpenAI({
  model: "deepseek-v4.1-flash",
  apiKey: process.env.AIFANS_API_KEY,
  configuration: { baseURL: "https://api.aifans.fan/v1" },
});
const res = await llm.invoke("Explain vector databases in two sentences.");
console.log(res.content);

Which model to use

Model ID and useInputCached inputOutputContext
deepseek-v4.1-flash
Default for chains, RAG answers and agents
$0.195$0.0039$0.781M
glm-5.3
Harder work: planning, large refactors, tricky bugs
$0.812$0.1508$2.5521M
glm-5.3-flash
Quick edits and high-volume jobs at the lowest price
$0.087$0.0174$0.291M
minimax-m3.1-flash
A fast alternative for routine agent steps
$0.15$0.015$0.6—

USD per 1M tokens. Prices are read from our live price list; all models and prices.

Production checklist

  • Set max_retries: 429 (rate limited) and 502 are worth retrying, and failed calls are never billed.
  • Each key allows 100 requests per minute by default. For batch jobs, use llm.batch(inputs, config={"max_concurrency": 5}) and give the job its own key.
  • Give production keys a daily spending limit and, on servers with a fixed address, an IP allow-list.
  • We do not offer embedding models: keep your embeddings provider for vector stores and use these models for generation.

FAQ

Do I need a special LangChain package for these models?

No. langchain-openai is enough, because the API speaks OpenAI Chat Completions.

Does LangGraph work?

Yes. LangGraph takes any LangChain chat model, so pass the same ChatOpenAI object to your graph nodes.

Does it work with LlamaIndex or the Vercel AI SDK?

Yes; see LlamaIndex and the Vercel AI SDK.

Related guides