Why DeepSeek API Logging Is a Compliance Problem, Not a Logging Problem
There are two ways to fail a compliance review of an LLM integration, and they look nothing alike. The first is logging nothing: requests leave your app, answers come back, and the only trace is whatever your server wrote to stdout before the log rotated. When a customer asks what your system sent to a model on their behalf, the answer is a shrug.
The second is logging everything: raw prompts, raw responses, and — because someone dumped a kwargs dict inside an error handler — the Authorization header that carries the API key. Now you own an unbounded personal-data store with no deletion path, which is usually a worse finding than having no logs at all.
Audit-grade logging lives between those extremes. Metadata is kept long and durably. Content is kept briefly, redacted, and encrypted. And the whole stream is tamper-evident, so a reviewer can tell that nobody edited it after the fact.
What an Audit-Grade Record Actually Contains
A request_id generated client-side before the call, so the same ID can appear in your own API responses and support tickets.
tenant_id and actor_id, so subject access requests and per-customer attribution are index lookups instead of forensic greps.
A UTC timestamp and the exact model identifier you asked for — deepseek-v4-flash or deepseek-v4-pro.
A SHA-256 fingerprint of the prompt payload, which proves what was sent without storing it.
Token usage and finish_reason from the response, which double as your cost-attribution data.
An outcome field: ok, or the exception class. Never the full traceback, which may embed credentials or payload fragments.
The version of your redaction policy, so records written last quarter stay interpretable after the rules change.
A prev_hash and record_hash pair that chains each record to the one before it.
A Runnable Audited Client for deepseek-v4-flash
This wrapper sits in front of the OpenAI SDK and writes one self-contained JSONL record per call, including failures.
import hashlib
import json
import logging
import os
import time
import uuid
from datetime import datetime, timezone
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
# httpx logs request headers at DEBUG level, API key included. Keep it quiet.
logging.getLogger("httpx").setLevel(logging.WARNING)
audit = logging.getLogger("audit")
audit.setLevel(logging.INFO)
audit.propagate = False
_handler = logging.FileHandler("audit.jsonl", encoding="utf-8")
_handler.setFormatter(logging.Formatter("%(message)s"))
audit.addHandler(_handler)
def fingerprint(messages) -> str:
payload = json.dumps(messages, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def audited_chat(messages, *, tenant_id, actor_id, model="deepseek-v4-flash", **kwargs):
request_id = str(uuid.uuid4())
started = time.perf_counter()
record = {
"request_id": request_id,
"ts_utc": datetime.now(timezone.utc).isoformat(),
"tenant_id": tenant_id,
"actor_id": actor_id,
"model": model,
"prompt_sha256": fingerprint(messages),
"status": "error",
}
try:
resp = client.chat.completions.create(
model=model,
messages=messages,
**kwargs,
)
text = resp.choices[0].message.content or ""
record["status"] = "ok"
record["completion_id"] = resp.id
record["finish_reason"] = resp.choices[0].finish_reason
record["response_sha256"] = hashlib.sha256(text.encode("utf-8")).hexdigest()
usage = getattr(resp, "usage", None)
if usage is not None:
record["prompt_tokens"] = usage.prompt_tokens
record["completion_tokens"] = usage.completion_tokens
record["total_tokens"] = usage.total_tokens
return resp
except Exception as exc:
record["error_type"] = type(exc).__name__
record["error_message"] = str(exc)[:300]
raise
finally:
record["latency_ms"] = round((time.perf_counter() - started) * 1000, 1)
audit.info(json.dumps(record, separators=(",", ":")))
Three details matter more than the rest. First, the record is written in a finally block, so a timeout, a rate limit, or a malformed response still produces a row. Failed calls are exactly what auditors want to see, and they are the ones teams usually forget to log.
Second, the record stores prompt_sha256 and response_sha256 instead of the text itself. Be honest with your legal team about one thing: a hash of a prompt is pseudonymous data, not anonymous data. It still counts as personal data under most privacy regimes, so it belongs in the same retention policy as everything else — and low-entropy inputs like a phone number or an order reference can be brute-forced straight out of a hash.
Third, streaming. If you pass stream=True, usage only arrives in the final chunk, so add stream_options={"include_usage": True} and write the audit row when the stream closes or raises. Log the request_id you generated alongside the completion id from that final chunk. And do not remove the httpx line: if anyone raises your root logger to DEBUG, the first thing that leaks is your API key.
Redact Before You Persist, Not After
If you keep any content at all, redact it on the way in. A post-hoc cleanup job will always lag behind the file it is supposed to protect.
import re
POLICY_VERSION = "redaction-policy-v1"
# Order matters: the card rule runs first so long digit runs are not eaten
# by the looser phone pattern.
_RULES = [
("email", re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")),
("card", re.compile(r"(?<!\d)(?:\d[ -]?){13,19}(?!\d)")),
("phone", re.compile(r"(?<!\d)\+?\d[\d\s().-]{7,}\d(?!\d)")),
("ipv4", re.compile(r"(?<!\d)(?:\d{1,3}\.){3}\d{1,3}(?!\d)")),
]
def redact(text: str):
"""Return (redacted_text, [labels_hit]) for safe archival."""
hits = []
for label, rule in _RULES:
text, count = rule.subn(f"[REDACTED:{label}]", text)
if count:
hits.append(label)
return text, hits
messages = [{"role": "user", "content": "Contact [email protected] about card 4111 1111 1111 1111"}]
safe = [{**m, "content": redact(m["content"])[0]} for m in messages]
print(safe)
Run the rules in a fixed order and store POLICY_VERSION on every record, so a reviewer knows which rules produced a given archive row.
Treat regexes as defense in depth, not a guarantee. Names and addresses need a model-based pass; if you do not have one, log less content rather than more.
Never log request headers, SDK kwargs, or full exception tracebacks. One convenient f-string in an error handler can undo an otherwise clean pipeline.
Redact responses too. Model output frequently echoes personal data copied from the input.
Make the Log Tamper-Evident With a Hash Chain
A JSONL file proves nothing on its own: anyone with write access can edit a line and the reviewer will never know. Chaining each record to the digest of the previous one makes edits detectable without any external service.
import hashlib
import json
import os
GENESIS = "0" * 64
def _digest(prev_hash: str, record: dict) -> str:
blob = json.dumps(record, sort_keys=True, separators=(",", ":"))
return hashlib.sha256((prev_hash + blob).encode("utf-8")).hexdigest()
def append_record(path: str, record: dict) -> str:
prev = GENESIS
if os.path.exists(path):
with open(path, "r", encoding="utf-8") as fh:
lines = fh.read().splitlines()
if lines:
prev = json.loads(lines[-1])["record_hash"]
record = {**record, "prev_hash": prev}
record["record_hash"] = _digest(prev, record)
with open(path, "a", encoding="utf-8") as fh:
fh.write(json.dumps(record, separators=(",", ":")) + "\n")
return record["record_hash"]
def verify_chain(path: str) -> str:
prev = GENESIS
with open(path, "r", encoding="utf-8") as fh:
for lineno, line in enumerate(fh, start=1):
rec = json.loads(line)
stored = rec.pop("record_hash")
if _digest(prev, rec) != stored:
return f"tampered at line {lineno}"
prev = stored
return "ok"
Wire it in by swapping the audit.info(...) call for append_record("audit.jsonl", record). Re-reading the whole file on every append is O(n), so cache the last hash in memory or, in production, keep records in a table with a unique constraint on prev_hash.
When the file rolls over, ship it to object storage with a retention lock and hand auditors verify_chain(path). Re-running that one function is the entire verification story, which is the point: verification should not require a platform.
Retention, Residency, and Erasure Without Breaking the Chain
Split the streams. Keep metadata for as long as your contractual or financial obligations require; keep content for the shortest window your support team genuinely needs.
Encrypt content per data subject with a key held in a KMS. To honour an erasure request, delete the key. The ciphertext stays where it is and the hash chain stays valid, but the record becomes unreadable — the cleanest way to reconcile delete my data with do not modify the audit trail.
Index by actor_id and prompt_sha256 so a subject access request is one query instead of a scan of a hundred gigabytes.
Log your own deletions. A nightly job that drops expired content should write an audit record stating how many rows it removed, otherwise your retention policy is unverifiable.
Know your vendor of record. AiCredits sells DeepSeek credits to international developers with card or PayPal and no Chinese phone number or bank account required, and issues per-project keys you can rotate independently of the audit pipeline.
Per-Tenant Token Accounting on the Same Stream
Because usage is already captured on every request, a per-customer rollup is a few lines of code — and it turns the audit log into the place you check before assuming a customer is being overcharged.
import json
from collections import defaultdict
rollup = defaultdict(int)
for line in open("audit.jsonl", encoding="utf-8"):
rec = json.loads(line)
rollup[rec.get("tenant_id", "unattributed")] += rec.get("total_tokens", 0)
print(dict(rollup))
Route high-volume, latency-tolerant paths to deepseek-v4-flash and reserve deepseek-v4-pro for requests where answer quality actually changes the outcome. Off-peak calls cost less than peak, and cache hits cost less than fresh input, so a shared stream that records the model and token counts per tenant pays for itself quickly. Check aicreditsapi.com/pricing for current rates rather than hard-coding assumptions into your dashboards.
One more practical habit: run a linter over every module that touches the client. AiCredits ships linting tools, and the usual compliance failure is not in the audit wrapper at all — it is a stray logger.info(kwargs) three files away, added during a debugging session and never removed.
Frequently Asked Questions
Not at default log levels, but it will at DEBUG — httpx logs request headers and bodies there, which means your API key and full prompt land in the log file. Pin logging.getLogger('httpx') to WARNING and route audit records to a separate handler with its own file and retention rules.
Only if a product feature needs it. Model output often contains personal data copied from the input, so redact it the same way and hold both under one retention window. If you only need proof of what happened, store response_sha256 and the token counts instead.
No. It is pseudonymous, not anonymous, so it stays inside your retention policy. Hashes of short, low-entropy inputs such as a phone number or an order reference can be brute-forced, which is why the hash belongs next to redacted content and not instead of it.
Pass stream_options={'include_usage': True}, accumulate the chunks, and write the audit row when the stream finishes or raises. Log the request_id you generated so a support ticket maps to exactly one row, and record the final chunk's usage figures.
Do not rewrite history. Encrypt content per data subject, delete that subject's key when an erasure request arrives, and log the key deletion as its own chained record. The ciphertext remains, verify_chain still passes, and the data is no longer readable by anyone.