A support bot that answers eight out of ten tickets is easy to demo and hard to ship. The failure mode is never that the model can't write — it's that it writes something confidently wrong: a refund window you don't offer, a delivery date it invented, a promise your ops team then has to honour.
This guide builds the boring, reliable version: answers grounded in your own policy text, live order data pulled through tool calls, context that stays cheap to send, and an escalation path triggered by rules instead of vibes. Every snippet runs as written with the OpenAI SDK (pip install openai) pointed at https://api.aicreditsapi.com/v1. You'll need a key first — AiCredits issues DeepSeek API credits payable by card or PayPal, with no Chinese phone number or bank account required.
Choose the Model Per Job, Not Per Product
deepseek-v4-flash should be your default almost everywhere. It covers the high-volume work: policy Q&A, order status, tone adjustments on a draft reply. deepseek-v4-pro costs more per request, so route to it deliberately — multi-step exception handling, contradictory policies, a customer who has already been transferred twice. Route by task, not by customer tier: a simple order-status question doesn't need the stronger model just because the account is on a premium plan.
| Job | Model | Reason |
|---|---|---|
| Policy Q&A, order status, tone rewrites | deepseek-v4-flash | Fast and inexpensive enough to run on every inbound message |
| Tool-calling loops (order lookups, ticket updates) | deepseek-v4-flash | Tool orchestration is deterministic work; the stronger model adds little |
| Multi-step exceptions, conflicting policies, angry-customer triage | deepseek-v4-pro | Worth the extra cost when a wrong answer becomes a refund dispute |
| Offline transcript analysis and backfills | deepseek-v4-flash (off-peak) | Off-peak requests cost less and nobody is waiting on the result |
Step 1: Ground Every Answer in Policy Text
Most support hallucinations come from a system prompt that says "be helpful" and nothing else. Give the model a small, authoritative block of policy text plus a hard rule for what to do when a question falls outside it.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
POLICY = '''
Refunds: unopened items only, within the return window.
Shipping: standard delivery in 3-5 business days; delays are announced by email.
Warranty: 12 months on manufacturing defects; accidental damage is not covered.
'''
SYSTEM = (
'You are a support agent for an online store. '
'Answer using ONLY the policy text below. '
'If the policy does not cover the question, reply with '
'ESCALATE: <one-line reason> and nothing else. '
'Never promise a refund, discount, or delivery date that is not in the policy.'
)
def answer(question, history=None):
messages = [{'role': 'system', 'content': SYSTEM + '\n\nPOLICY:\n' + POLICY}]
messages += history or []
messages.append({'role': 'user', 'content': question})
response = client.chat.completions.create(
model='deepseek-v4-flash',
messages=messages,
temperature=0.2,
max_tokens=400,
)
return response.choices[0].message.content.strip()
if __name__ == '__main__':
print(answer('Can I return an opened item?'))
print(answer('Do you price match a competitor?'))
Two choices in that snippet do most of the work. Low temperature keeps repeated questions producing repeatable answers, which matters when three agents see the same ticket thread. And the model has an explicit exit: a literal ESCALATE prefix your code can parse. Detecting a token is far easier to test than asking a model to "be honest" — match the prefix, open a ticket, and never send the generated text to the customer.
Keep POLICY in version control and review edits like code, because the bot's behaviour changes the moment that text does.
Step 2: Give It Live Data with Tool Calls
Policy answers are static; order status is not. Tool calling lets the model ask your backend for facts instead of guessing, and it keeps database access in your code rather than in the prompt.
import json, os
from openai import OpenAI
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
ORDERS = {
'A1001': {'status': 'shipped', 'carrier': 'DHL', 'eta': 'two business days'},
'A1002': {'status': 'processing', 'carrier': None, 'eta': 'ships within 24 hours'},
}
TOOLS = [{
'type': 'function',
'function': {
'name': 'get_order',
'description': 'Look up an order by its ID.',
'parameters': {
'type': 'object',
'properties': {
'order_id': {'type': 'string', 'description': 'e.g. A1001'},
},
'required': ['order_id'],
},
},
}]
def get_order(order_id):
return ORDERS.get(order_id.upper(), {'error': 'order not found'})
def run(user_message):
messages = [
{'role': 'system', 'content': (
'You are a support agent. Ask for the order ID if the customer '
'did not provide one. Only state facts returned by get_order.'
)},
{'role': 'user', 'content': user_message},
]
for _ in range(4):
response = client.chat.completions.create(
model='deepseek-v4-flash',
messages=messages,
tools=TOOLS,
temperature=0,
)
msg = response.choices[0].message
messages.append(msg)
if not msg.tool_calls:
return (msg.content or '').strip()
for call in msg.tool_calls:
args = json.loads(call.function.arguments or '{}')
messages.append({
'role': 'tool',
'tool_call_id': call.id,
'content': json.dumps(get_order(**args)),
})
return 'ESCALATE: too many tool steps'
print(run('Where is order A1001?'))
The loop cap (for _ in range(4)) is not decoration — it's what stops a confused model from calling get_order forever. When the cap is reached, escalate rather than returning a half-finished answer. Note also that the tool result goes back as JSON, including the error case: if the order isn't found, the model sees that and asks the customer to check the number instead of inventing a shipment.
Step 3: Keep Context Cheap and Cache-Friendly
Every request re-sends your system prompt, policy block, and conversation history. Two habits stop that from growing without limit: keep the static prefix byte-identical across requests so cached input can be reused (cache hits cost less than fresh tokens), and trim history instead of letting it accumulate.
MAX_TURNS = 8
def trim(history, keep=MAX_TURNS):
'''Keep recent turns; fold older ones into a single summary line.'''
if len(history) <= keep:
return history
older, recent = history[:-keep], history[-keep:]
summary = 'Earlier in this conversation: ' + ' | '.join(
(m.get('role') or '?') + ': ' + (m.get('content') or '')[:80]
for m in older
)
return [{'role': 'system', 'content': summary}] + recent
Append that summary block after the static policy block, never before it. Reordering or rewording the prefix invalidates the cache for the whole request, which is the opposite of what you wanted. Off-peak requests also cost less, so schedule transcript backfills and analytics jobs outside peak hours — nobody is waiting on those, and the savings are free.
Step 4: Write Escalation Rules Before Launch
The model returned
ESCALATE— send it to a human queue. Don't silently retry with a heavier model first.The customer asked for a human twice. Detect it with a keyword or intent check and skip straight to handoff.
The request touches money above a threshold you're comfortable with — that number comes from your finance team, not from a prompt.
A tool returned an error or an empty result more than once in a single conversation.
The topic is legal, compliance, or an active complaint. The bot should never improvise here.
Log every ticket with the retrieved context and the model's raw output. You cannot debug a support bot without the inputs that produced the reply.
Step 5: Test with a Golden Set, Not Vibes
Collect 30-50 real tickets — the awkward ones: partial order IDs, questions about a policy you don't have, a message that's just an angry paragraph. Run them through your pipeline before any prompt change ships, and score three things per case: grounded (is the answer actually supported by the policy or a tool result?), safe (no invented commitments), and routed (did it escalate when it should?). A CSV plus a for-loop over the API is a perfectly good harness. The point isn't tooling sophistication — it's that a prompt edit is a code change and deserves the same gate.
None of the model-facing decisions here are exotic: flash by default, pro for exceptions, a static cached prefix, off-peak batch work. What makes a support bot shippable happens outside the model call — a policy block someone owns, a tool layer that reports errors honestly, and escalation rules written down before launch. AiCredits supplies the DeepSeek credits for all of it (card or PayPal, from anywhere) and also ships code-linting tools if you want a second pass over the integration before it touches customer inboxes. Current rates by model, cache hits, and time of day live at aicreditsapi.com/pricing.
FAQ
Yes. The DeepSeek API is OpenAI-compatible: set base_url='https://api.aicreditsapi.com/v1' and pass model='deepseek-v4-flash'. Tools, streaming, and multi-turn messages behave the same, so most existing OpenAI SDK code needs only those two changes.
Ground it in a short, owned policy document, keep temperature low, parse for an explicit escalation token, and never let it commit to amounts or dates the policy doesn't state. Then add those exact cases to your golden set so a future prompt edit can't quietly regress them.
Usually not. Flash handles the high-volume path — policy Q&A, order status, tone fixes. Reserve pro for multi-step exceptions where a wrong answer costs more than the extra reasoning does, and route to it from your own code based on the ticket, not the customer.
No. AiCredits sells DeepSeek API credits to international developers and accepts card or PayPal, so you can get a key and deploy the bot without a local entity or a Chinese payment method.