LLM Technology9 min read

Draft Customer Support Replies with an LLM

Build an LLM pipeline that drafts support replies from help-centre articles, returns a schema-checked escalation flag and posts drafts as internal notes.

By AI Agents DirectoryLast checked
Abstract illustration of a glowing digital brain on a dark background

Letting a language model answer customers on its own is a big step. Letting it write a first draft that a human agent checks is a much smaller one, and it is where most teams should start. This guide builds that smaller version: pull the relevant help-centre articles, ask the model for a reply in a fixed JSON shape that includes an escalation flag, post the draft to the ticket as an internal note, and measure how often agents can send it as written. The code uses the Claude API and the Zendesk API, and every API detail is checked against Anthropic’s documentation and Zendesk’s developer docs.

The pipeline at a glance

StepWhat happensTool
1. RetrieveFind help-centre articles that match the ticketZendesk Help Center API plus your own search index
2. PromptRole and policy rules in the system prompt; articles and ticket in the user turnClaude Messages API
3. StructureModel returns reply text, cited article IDs, confidence and an escalation flagStructured outputs (output_config.format)
4. ReviewDraft lands on the ticket as an internal note for an agent to editZendesk Tickets API, public: false
5. Hand offEscalated tickets are routed to a person with the reason attachedZendesk ticket fields such as group_id and priority
6. EvaluateCompare drafts with what agents actually sentYour test set plus graders

Step 1: retrieve from your help centre

The model should answer from your documentation, not from whatever it learned in training. Zendesk’s Articles API lets you list every article (GET /api/v2/help_center/articles), fetch one by ID, and pull only the articles whose metadata changed after a given time through GET /api/v2/help_center/incremental/articles. That incremental endpoint is the one to schedule, because it keeps your index current without re-downloading the whole knowledge base.

Each article object carries an id, a title, an HTML body, its locale, and an html_url pointing at the public page. Keep the ID and URL alongside each chunk you index so the model can name its sources and your code can check them. Note that the list only returns articles the calling user is allowed to view, so use an account whose permissions match the audience you are answering.

How you search the index is up to you. Anthropic’s support guide suggests embedding the content and retrieving per query once your knowledge base is too large to fit in every prompt, since stuffing it all in raises cost, slows responses and can hit the context window. For live facts such as order status or account balance, retrieval over articles is the wrong tool; the same guide recommends tool use to look those up. Our post on managing the RAG context window covers chunk size and how many passages to send.

Step 2: write the prompt

Anthropic’s guidance splits the prompt in two. Use the system prompt for the role (who the assistant is and for which company) and put most of the content, including documents and examples, in the user turn. Inside that turn:

  • Wrap each article in XML tags such as <document> with <source> and <document_content> sub-tags. The prompting guide says tags reduce confusion when a prompt mixes instructions, context and input, and recommends putting long documents above the question.
  • State policy rules plainly. The support guide’s own guardrail list is a good template: answer only about products you sell, never speculate about future plans, never promise refunds or terms the assistant has no authority to grant, and do not mention competitors.
  • Say why a rule matters. Anthropic notes that giving the motivation behind an instruction tells the model more about your goals, which leads to better-targeted replies.
  • Give it permission to not know. The hallucination guide recommends telling the model it may say the information is missing, and restricting it to the supplied documents rather than general knowledge.
  • Add a few example replies in <example> tags. The prompting guide suggests three to five, chosen to cover different situations, as a reliable way to fix tone and length.

More general prompting technique is in our prompt engineering best practices post.

Step 3: get the draft back as structured data

A free-text reply is hard to route. You want fields your code can act on. Claude’s structured outputs feature constrains the response to a JSON schema you supply, so the result parses every time and required fields are present. In Python, client.messages.parse() takes a Pydantic model, sends its schema as output_config.format, and returns the validated object in parsed_output.

The example below follows the pattern in Anthropic’s structured outputs page and the update-ticket example in Zendesk’s reference. It drafts a reply and posts it as a private note.

from typing import Literal
import os, requests
from anthropic import Anthropic
from pydantic import BaseModel

class Draft(BaseModel):
    reply: str
    cited_article_ids: list[int]
    confidence: Literal["high", "low"]
    escalate: bool
    escalation_reason: str

SYSTEM = "You are a support agent for Acme. Draft replies an agent will review."

def draft_reply(ticket_text: str, articles: list[dict]) -> Draft:
    docs = "\n".join(
        f"<document><source>{a['id']}</source>"
        f"<document_content>{a['body']}</document_content></document>"
        for a in articles
    )
    prompt = (
        f"<documents>\n{docs}\n</documents>\n"
        "<rules>Use only the documents above. If they do not answer the "
        "question, or the customer asks for a refund, legal action or account "
        "deletion, set escalate to true and explain why.</rules>\n"
        f"<ticket>{ticket_text}</ticket>"
    )
    client = Anthropic()
    response = client.messages.parse(
        model="claude-opus-5-5",
        max_tokens=1024,
        system=SYSTEM,
        messages=[{"role": "user", "content": prompt}],
        output_format=Draft,
    )
    return response.parsed_output

def post_internal_note(ticket_id: int, draft: Draft) -> None:
    sub = os.environ["ZENDESK_SUBDOMAIN"]
    note = f"AI draft (confidence: {draft.confidence})\n\n{draft.reply}"
    if draft.escalate:
        note = f"ESCALATE: {draft.escalation_reason}\n\n" + note
    requests.put(
        f"https://{sub}.zendesk.com/api/v2/tickets/{ticket_id}",
        json={"ticket": {"comment": {"body": note, "public": False}}},
        auth=(f"{os.environ['ZENDESK_EMAIL']}/token", os.environ["ZENDESK_API_TOKEN"]),
        timeout=30,
    ).raise_for_status()

A few details from the docs are worth building in from day one:

  • Check stop_reason before trusting the object. The schema is not guaranteed when the model refuses ("refusal") or runs out of tokens ("max_tokens"). Treat either case as an escalation.
  • Compare enum values case-insensitively. Anthropic warns that structured outputs do not guarantee the capitalisation of enum strings, so "High" can come back for "high".
  • Do not ask for step-by-step reasoning in a schema field. The docs say such a field can trigger a refusal; ask for a short reason, as escalation_reason does here.
  • Citations and structured outputs do not mix. The API rejects requests that enable both, which is why the schema asks for cited_article_ids instead. Check in code that every cited ID was one you actually retrieved, and escalate if not.
  • The first call with a new schema is slower while the grammar compiles. Compiled grammars are then cached for 24 hours after last use.

Treat confidence as a hint, not a measurement. It is the model’s own label, so decide routing with rules you can test (no retrieved article, an uncited answer, a sensitive topic) and use the label as one more input.

Step 4: keep a human between the draft and the customer

In Zendesk, comments are created through the Tickets API by sending a comment object inside a ticket update; the Ticket Comments API has no create endpoint. The public flag is what makes this safe: false produces an internal note that agents see and the requester does not. Zendesk’s reference adds that the first comment’s public setting carries over to later comments unless you change it, so always send the flag explicitly.

Two more Zendesk behaviours matter for an automated writer:

  • Collisions. An agent may update the ticket while your job runs. Zendesk supports safe updates: send safe_update: true with the updated_stamp you last read, and the API flags a conflict instead of silently overwriting.
  • Tags. On a single ticket update, the tags field replaces the existing tags. To add a marker like ai_drafted without wiping others, use additional_tags through the bulk update endpoint.

Once the agent edits and sends the reply, the final public comment is your ground truth for evaluation.

Step 5: hand off cleanly

When escalate is true, do more than write a note. Set fields the routing rules already understand: group_id to move the ticket to the right team and priority ("urgent", "high", "normal" or "low") to change its place in the queue. Put the model’s reason at the top of the note so the next person knows why it landed with them. Anthropic’s guide lists escalation accuracy as one of the metrics to track: how often the assistant escalates conversations that need a person, and how often it misses one.

Step 6: evaluate before and after launch

Anthropic’s testing guide starts with success criteria that are specific and measurable, then builds a test set that reflects real traffic, including the awkward cases: missing data, very long messages, hostile or irrelevant input, and questions where even your team would disagree. For support drafts, useful checks include:

CheckHow to grade
Escalation flag correctCode: compare with a labelled set of past tickets
Cited IDs exist and support the replyCode for existence; LLM grader for support
Policy rules followed (no promises, no competitors)LLM grader with a strict rubric
Tone matches your brandLLM grader on a 1 to 5 scale, as in Anthropic’s customer service example
Agent sent the draft unchanged or lightly editedCompare the draft with the final public comment

The guide ranks grading methods: code-based checks are fastest and most dependable, LLM grading is flexible but should be validated before you scale it, and human grading is the slowest. It also favours many automatically graded cases over a few hand-graded ones. Write a detailed rubric for each LLM grader and let the grader think before scoring. If you prefer an existing harness, OpenAI Evals and the tools in our evaluation and monitoring hub can run these test sets.

Honest limits

None of this removes hallucination. Anthropic’s own guide says its techniques reduce made-up content but do not eliminate it, and advises checking critical information. Keep the draft-and-review step until your evaluation data shows which ticket types are safe to automate further, and keep personal data out of drafts unless the reply truly needs it.

#Customer support#Claude API#Structured outputs#RAG#Zendesk
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.