AiCredits
Architecture Guide

WeChat Mini Program + LLM API: Architecture Patterns for Chinese Apps

Practical architecture patterns for wiring an LLM API into a WeChat Mini Program: secure proxy, SSE streaming, ICP domain rules, moderation, and cost control.

Published 2026-11-05 Updated 2026-11-05 7 min

Why a Mini Program Is a Hostile Place for an LLM Call

WeChat Mini Programs are the default distribution channel for consumer apps in China, and adding an LLM is now a routine product request: a support bot, a study helper, a menu translator, a shopping assistant. The trap is that the mini program runtime looks like a browser and behaves like neither a browser nor a server. Wire the model call the way you would in a React app and you will ship a leaked API key, a rejected review, and a spinner that never resolves.

The constraints are concrete. The package is downloaded to the device and can be unpacked, so anything inside it is public. Outbound hosts must be HTTPS, ICP-filed, and explicitly added to the request-domain whitelist in the admin console. wx.request gives you a short timeout, the main package has a tight size cap, and every token of AI output can be surfaced to users and to reviewers. Each constraint maps to an architecture decision.

Pattern 1 — Keep the Key on the Server

No provider key should ever appear in the mini program bundle. The client talks to your gateway; the gateway holds the key and decides what the model sees. This is not just hygiene — it is the only way to enforce anything.

  • The client knows only your gateway URL and the user's session identifier.

  • System prompts and guardrails live server-side, so you can change tone, limits, or refusal copy without a new review cycle.

  • Rate limits key on openid, which is stable per user per mini program, instead of on a token the client can forge.

  • Moderation, logging, and model routing happen where you can actually enforce them.

Pattern 2 — Design Around the Whitelist and ICP Filing

WeChat requires every request domain to be ICP-filed, served over HTTPS, and added to the whitelist. No wildcards, no localhost, no ad-hoc hosts. In practice that means one stable gateway domain with path-based routing (/chat/stream, /jobs), plus a mainland-friendly CDN in front of it.

It also means you cannot quietly call a model provider from the client even if an SDK fits inside the package. Teams outside mainland China that do not hold an ICP filing usually put the gateway behind a filed domain operated by their China partner, while the model call itself stays on their own infrastructure.

Pattern 3 — Stream Through the Proxy, Correctly

Users tolerate a slow answer far better than a frozen screen. Streaming in a mini program uses wx.request({ enableChunked: true }) together with the onChunkReceived callback on newer base libraries. You receive raw bytes, not a parsed event stream, so you must buffer, split on double newlines, and parse each data: line yourself.

The SSE detail that bites people: a token containing a newline breaks data: <text> framing. JSON-encode each delta on the server and decode it on the client.

# proxy.py  —  pip install fastapi uvicorn openai pydantic
import json
import os

from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

SYSTEM_PROMPT = (
    "You are the assistant inside a WeChat Mini Program. "
    "Reply in the user's language. Be concise: short paragraphs, no tables."
)

app = FastAPI()


class ChatRequest(BaseModel):
    openid: str
    message: str


@app.post("/chat/stream")
def chat_stream(req: ChatRequest):
    text = req.message.strip()
    if not text:
        raise HTTPException(status_code=400, detail="empty message")
    if len(text) > 2000:
        raise HTTPException(status_code=413, detail="message too long")

    def sse():
        stream = client.chat.completions.create(
            model="deepseek-v4-flash",
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": text},
            ],
            temperature=0.7,
            stream=True,
        )
        for chunk in stream:
            if not chunk.choices:
                continue
            delta = chunk.choices[0].delta.content
            if delta:
                # JSON-encode so newlines inside a token cannot break SSE framing
                yield f"data: {json.dumps({'d': delta}, ensure_ascii=False)}\n\n"
        yield "data: [DONE]\n\n"

    return StreamingResponse(
        sse(),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )
  • Send a heartbeat comment every few seconds so an intermediary proxy does not idle-close the connection.

  • Call requestTask.abort() when the user leaves the page. Abandoned streams still bill tokens.

  • Feature-detect enableChunked and fall back to the non-streaming endpoint on older clients.

  • Treat [DONE] as the only valid end signal; a dropped connection is an error, not a finished answer.

Pattern 4 — Long Work Belongs in a Job Queue

A mini program request will not wait for a two-minute generation. For anything heavier than a chat turn — a document summary, a batch translation, a weekly report — return 202 with a job_id immediately, run the model call in a worker, and poll GET /jobs/{id} from the client. Store job state in Redis or your database, not in process memory, because serverless and multi-worker deployments will not share a dictionary. This also gives you a natural place to retry provider errors and to cap concurrency per openid.

Pattern 5 — Moderation Is Part of the Request Path

Chinese consumer apps face both WeChat review and the generative-AI service rules, and reviewers do test edge cases. Run the user's input through security.msgSecCheck or your own classifier before the model sees it, and run the model's output through a check before it reaches the page. Keep a log of openid, timestamp, and a hash of the prompt so you can answer a takedown request or a review question months later.

  • Strip or mask phone numbers, ID numbers, and addresses before sending prompts upstream when the product does not need them.

  • Refuse rather than improvise: a fixed refusal string is safer than letting the model argue with a moderation flag.

  • Cache the moderation verdict for identical short inputs so a retry does not trigger a second check.

Pattern 6 — Default to flash, Escalate to pro

Most mini program traffic is short: a question, a rewrite, a classification. deepseek-v4-flash handles that with the lowest latency and cost. Reserve deepseek-v4-pro for multi-step reasoning, code, and long-context analysis, and gate it behind an explicit user action or a failed validation check on the flash attempt. Never let the client pass an arbitrary model name — map the decision server-side.

ModelUse it forTrade-off
deepseek-v4-flashChat replies, extraction, classification, translation, anything streamed to the screenFastest and cheapest; weaker on multi-step reasoning
deepseek-v4-proDebugging, planning, long documents, tasks the user explicitly marks as deep analysisStronger output, slower and costs more per call

Cost control is mostly about what you send, not which model you pick. Prompt caching makes repeated system prompts and long shared context cheaper on cache hits, and off-peak traffic costs less than peak. Check aicreditsapi.com/pricing for current rates instead of budgeting from a blog post.

# routing.py  —  model choice and context budgeting
import os

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

SYSTEM_PROMPT = "You are a concise assistant inside a WeChat Mini Program."
HARD_HINTS = ("step by step", "debug", "prove", "trade-off", "分析", "方案", "为什么")


def pick_model(user_message: str) -> str:
    if len(user_message) > 800 or any(h in user_message.lower() for h in HARD_HINTS):
        return "deepseek-v4-pro"
    return "deepseek-v4-flash"


def trim_history(history: list[dict], max_chars: int = 6000) -> list[dict]:
    kept, size = [], 0
    for msg in reversed(history):
        size += len(msg.get("content", ""))
        if size > max_chars:
            break
        kept.append(msg)
    return list(reversed(kept))


def answer(history: list[dict], user_message: str) -> str:
    messages = (
        [{"role": "system", "content": SYSTEM_PROMPT}]
        + trim_history(history)
        + [{"role": "user", "content": user_message}]
    )
    resp = client.chat.completions.create(
        model=pick_model(user_message),
        messages=messages,
        temperature=0.5,
        max_tokens=800,
    )
    return resp.choices[0].message.content

Pattern 7 — Bound the Context per openid

Users expect the mini program to remember the last few turns, but resending the entire conversation is the quickest way to waste a token budget. Trim by characters, summarize older turns into one stored paragraph keyed by openid, and hard-cap the history. A few thousand characters covers most consumer chat sessions; push the rest into a summary field your backend owns and refresh it every few turns.

If the key ships in the bundle, it is not a secret — it is a giveaway.

FAQ

Can I call the model API directly from a WeChat Mini Program?

Technically wx.request can reach any whitelisted HTTPS domain. Practically, you would expose your key in a package that can be decompiled, and the provider domain would need to be ICP-filed and whitelisted. Use your own gateway instead.

Does streaming work inside a mini program?

Yes, with enableChunked on newer base libraries. You receive raw chunks and must parse the SSE frames yourself. Always keep a non-streaming fallback for older clients.

Which model should I default to?

deepseek-v4-flash for almost everything, escalating to deepseek-v4-pro only when the task needs deeper reasoning or the user asks for it explicitly.

How do I pay for DeepSeek API credits without a Chinese bank account?

AiCredits sells DeepSeek API credits payable by international card or PayPal, with no Chinese phone number or bank required. The same key and base_url used above work unchanged.

Where to Start

None of these patterns are exotic. They are the ordinary discipline of putting a server between an untrusted client and a paid API, plus the WeChat-specific rules around domains and review. Build the proxy first, add streaming second, and route models last — in that order, each step is testable on its own.

If your team sits outside mainland China or lacks a Chinese corporate bank account, AiCredits sells DeepSeek API credits payable by card or PayPal, so you can top up without a local entity. Our linting tools can also flag the classic client-side mistakes — a hardcoded key, an unbounded history array — before a reviewer does.

Still stuck at DeepSeek's checkout?

This article explains why the payment fails. If what you actually need is a working key today, there is a shorter path: prepaid DeepSeek credits, no subscription, key issued to your account right after checkout.

  • $9 / $19 / $29 USD one-time credit packs — 1 USD = 500K credits (so $9 = 4.5M); billed by actual usage, never expires, tax excluded
  • Card, Apple Pay, Google Pay or Alipay via Creem — no PayPal account needed
  • Email signup only — no Chinese phone number, no Chinese bank account
  • Same DeepSeek models and the same OpenAI-compatible API — change one base_url

Get a DeepSeek key → Or try it free first

Not sure how prepaid billing works? See the full DeepSeek API credits guide → — packs, usage-based billing, supported models and payment methods.

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 ×