AiCredits
Dev Guide

How to Use DeepSeek API with LangChain: Practical Examples

Build production-ready DeepSeek apps with LangChain: chains, streaming, structured output, tool calling, async batching, caching, and model routing. Runnable code.

Published 2026-09-26 Updated 2026-09-26 9 min

Why Run DeepSeek Through LangChain

DeepSeek's API is OpenAI-compatible, which means every LangChain component that speaks the OpenAI protocol works with it almost untouched: ChatOpenAI, LCEL chains, output parsers, tool binding, and abatch. You get DeepSeek's cost profile with LangChain's composition model, instead of hand-rolling HTTP calls and retry logic.

The catch is that most tutorials glue together three or four moving parts without explaining which ones actually matter in production. This guide builds up from a single call to a routed, cached, retry-hardened pipeline, with code you can paste and run at each step.

Setup

pip install -U langchain-openai langchain-core pydantic

export AICREDITS_API_KEY="your-key-here"

Step 1: A Minimal Chat Chain

Point ChatOpenAI at your gateway base URL and you are done. The /v1 suffix matters — omitting it produces confusing 404s that look like bad model names.

import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage

llm = ChatOpenAI(
    model="deepseek-v4-flash",
    base_url="https://api.aicreditsapi.com/v1",
    api_key=os.environ["AICREDITS_API_KEY"],
    temperature=0.2,
    max_retries=3,
    timeout=60,
)

reply = llm.invoke(
    [
        SystemMessage(content="You are a concise Python tutor. Answer in under 80 words."),
        HumanMessage(content="Why is a list comprehension usually faster than a for-loop with .append()?"),
    ]
)
print(reply.content)

Step 2: Wrap It in an LCEL Chain

Chains are where LangChain earns its keep. Compose a prompt template, the model, and a parser with the pipe operator, then reuse the whole thing as a single callable. Keep the system message byte-identical across requests so the provider's prompt cache can do its job — identical prefixes are cheaper than fresh ones.

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

prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a senior code reviewer. List concrete issues only, one per line."),
        ("human", "Review this function:\n\n```python\n{code}\n```"),
    ]
)

chain = prompt | llm | StrOutputParser()

snippet = "def avg(nums):\n    return sum(nums) / len(nums)"
print(chain.invoke({"code": snippet}))

Step 3: Stream Tokens to the UI

Because StrOutputParser sits at the end of the chain, .stream() yields plain strings rather than message objects — exactly what a web handler wants to flush to the client.

chunks = 0
for chunk in chain.stream({"code": snippet}):
    chunks += 1
    print(chunk, end="", flush=True)
print(f"\n--- {chunks} chunks streamed")

Step 4: Structured Output You Can Trust

Parsing free text with regex breaks the moment the model adds pleasantries. Define a Pydantic model instead and let tool calling do the schema enforcement. Force the function-calling path explicitly — it is the most portable method across OpenAI-compatible endpoints.

from typing import Literal
from pydantic import BaseModel, Field

class Ticket(BaseModel):
    """Structured classification of a support ticket."""

    category: Literal["billing", "bug", "feature_request", "other"] = Field(
        description="Primary category"
    )
    urgency: Literal["low", "medium", "high"] = Field(description="Business urgency")
    one_line_summary: str = Field(description="Summary under 15 words")

classifier = llm.with_structured_output(Ticket, method="function_calling")

ticket = classifier.invoke(
    "Every PayPal checkout has returned HTTP 500 for three hours. Customers can't pay."
)
print(ticket.category, ticket.urgency, "|", ticket.one_line_summary)

Step 5: Tool Calling Without an Agent Framework

You do not need a full agent runtime to get tool use. bind_tools plus a manual loop is roughly fifteen lines, fully debuggable, and avoids the hidden prompt overhead that agent scaffolds add to every turn.

from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, ToolMessage

@tool
def estimate_tokens(text: str) -> int:
    """Estimate the token count of a string (roughly 4 characters per token)."""
    return max(1, len(text) // 4)

tool_llm = llm.bind_tools([estimate_tokens])
conversation = [
    HumanMessage("How many tokens is 'the quick brown fox jumps over the lazy dog'? Use the tool.")
]

ai_msg = tool_llm.invoke(conversation)
conversation.append(ai_msg)

for call in ai_msg.tool_calls:
    result = estimate_tokens.invoke(call["args"])
    conversation.append(ToolMessage(content=str(result), tool_call_id=call["id"]))

print(tool_llm.invoke(conversation).content)

Step 6: Async Batch for Throughput

Sequential invoke calls are the most common performance mistake in LLM code. abatch fans out concurrent requests with a bounded concurrency limit, which is usually the difference between a batch job finishing in seconds instead of minutes.

import asyncio

async def main():
    reviews = await chain.abatch(
        [
            {"code": "def avg(nums):\n    return sum(nums) / len(nums)"},
            {"code": "items = []\nfor i in range(1000):\n    items.append(i)"},
        ],
        config={"max_concurrency": 4},
    )
    for r in reviews:
        print(r, "\n---")

asyncio.run(main())

Step 7: Production Guardrails

Three additions separate a demo from something you can ship: a response cache, aggressive retries with a timeout, and deliberate model routing. Note the failure behaviour of each.

import os
from langchain_core.globals import set_llm_cache
from langchain_core.caches import InMemoryCache
from langchain_openai import ChatOpenAI

set_llm_cache(InMemoryCache())  # process-local; swap for Redis/SQLite in production

COMMON = dict(
    base_url="https://api.aicreditsapi.com/v1",
    api_key=os.environ["AICREDITS_API_KEY"],
    max_retries=4,
    timeout=90,
)

fast = ChatOpenAI(model="deepseek-v4-flash", temperature=0.2, **COMMON)
strong = ChatOpenAI(model="deepseek-v4-pro", temperature=0.2, **COMMON)

HARD_HINTS = ("refactor", "architecture", "prove", "root cause")

def route(text: str) -> ChatOpenAI:
    """Escalate to pro only when the task actually needs it."""
    return strong if any(h in text.lower() for h in HARD_HINTS) else fast

task = "Refactor this into a generator: def load(paths): return [open(p).read() for p in paths]"
print(route(task).invoke(task).content)

Choosing Between deepseek-v4-flash and deepseek-v4-pro

Task shapeModelWhy
Classification, extraction, summarisation, chatdeepseek-v4-flashHandles high-volume routine work with the fastest turnaround
Multi-step refactors, gnarly debugging, long-context reasoningdeepseek-v4-proBetter output quality on hard problems; slower and costs more per call
Anything user-facing and latency-sensitivedeepseek-v4-flashPro is worth it for quality-critical, non-interactive jobs
Bulk backfills and offline gradingdeepseek-v4-proRun off-peak: rates are lower outside peak windows

Pitfalls That Break Real Apps

  • Missing /v1. base_url must include it, or every call 404s and looks like a model problem.

  • Copy-pasted model strings from old tutorials. Retired aliases no longer resolve — always set model="deepseek-v4-flash" unless you have a reason to escalate.

  • Streaming plus structured output. These cannot be combined; pick one per call.

  • Token budgeting with tiktoken. DeepSeek's tokenizer is not identical to OpenAI's. Treat estimates as directional and leave headroom in max_tokens.

  • Zero retries. Rate limits and transient 5xx responses are normal at volume. Keep max_retries at 3 or higher with a generous timeout.

  • RAG with no embedder. DeepSeek's API does not serve embeddings — pair it with a dedicated embedding provider and keep retrieval on your side.

  • Rewriting the system prompt per request. Unstable prefixes defeat provider-side prompt caching, which makes repeat calls cheaper.

Where AiCredits Fits

If you are outside China, the friction is rarely the code — it is provisioning. AiCredits sells DeepSeek API credits to international developers with payment by card or PayPal, no Chinese phone number or bank account required. Because the gateway is OpenAI-compatible and exposes the same https://api.aicreditsapi.com/v1 surface, everything above works unchanged; you swap the base URL and keep your LangChain code. Current rates, including off-peak and cache-hit behaviour, are listed at aicreditsapi.com/pricing.

AiCredits also ships code linting tools, which pair nicely with the reviewer chain in Step 2 — lint catches mechanical defects so your model calls are spent on judgement, not style.

FAQ

Do I need the langchain-deepseek package?

No. It is a thin wrapper around an endpoint configuration. ChatOpenAI with an explicit base_url is more portable, works with any OpenAI-compatible gateway (including AiCredits), and behaves identically with LCEL, parsers, and tool binding.

Why do I get a model-not-found error?

Two usual causes: a retired model alias copied from an older tutorial, or a base_url that is missing the /v1 path segment. Set model="deepseek-v4-flash" and verify the full base URL first.

Can I stream while using structured output?

No. Streaming returns partial tokens, structured output needs a complete tool call to validate the schema. Run the structured call without streaming and stream only free-text responses.

Does DeepSeek provide embeddings for RAG pipelines?

The API does not serve an embeddings endpoint. Use a dedicated embedding model, store vectors locally or in your own vector database, and pass retrieved passages into the prompt as regular context.

Rule of thumb: default everything to deepseek-v4-flash, cache aggressively, batch in parallel, and escalate to deepseek-v4-pro only when a task measurably fails on the fast model.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×