Practical Examples

Three examples: a knowledge FAQ bot, a classify-then-answer flow, and a Python Service API client. Finish Quick Start and at least one model provider first.


Example 1: FAQ bot on a knowledge base

Goal: Colleagues ask policy questions in natural language. Answers must point at the doc, not at the model’s vibes.

Prepare faq.md (sample):

# Travel reimbursement
- Local transit: e-receipt required, 80 per day cap.
- High-speed rail 2nd class: actual cost. 1st class needs written director approval.
# Equipment
- New hires collect a laptop at the IT desk within 3 business days; bring your employee id.

Steps:

  1. Knowledge: create a dataset, upload faq.md, General or Parent-child chunks, High Quality + hybrid retrieval
  2. Retrieval test: “What is the daily local-transit cap?” should hit the “80” passage
  3. Create a Chatbot and bind that dataset
  4. Freeze evidence rules in the prompt, for example:
Answer travel and equipment questions only from the knowledge base. Quote the supporting line.
If retrieval is empty, reply: Not found in policy—ask HR. Never invent amounts.
  1. In preview, ask something absent (meal overtime). Expect refusal, not a made-up number
  2. Publish a Web App and open it in another browser

Compare LangChain’s doc Q&A: there you build a retriever; here the knowledge base replaces that indexing code.


Example 2: Classify, then answer (Workflow / Chatflow)

Goal: Policy questions retrieve; chit-chat and off-topic get a fixed refusal—do not scan the whole corpus for “hi.”

Create a Chatflow (chat UI) or Workflow (one-shot API). Canvas:

  1. User Input — user text as query
  2. Question Classifierpolicy (travel / devices / receipts), chitchat, other
  3. policyKnowledge Retrieval (example 1 dataset) → LLM (answer only from hits)
  4. chitchatLLM (short greeting + “I only answer policy”)
  5. otherLLM or Template (fixed: “Please rephrase as a policy question”)
  6. Join edges on Answer (Chatflow) or Output (Workflow)

Label 15 questions and watch the classifier. If it flaps, rewrite class descriptions (“asks about amounts, invoices, badge pickup”) instead of a single word policy. More compliance-friendly than a lone Agent: the path is on the graph.


Example 3: Python backend integration

Goal: Your site takes the question; the server calls Dify; the browser never sees the key.

import os
from typing import Any

import requests

class DifyChat:
    def __init__(self) -> None:
        self.base = os.environ.get("DIFY_API_BASE", "http://localhost/v1").rstrip("/")
        self.key = os.environ["DIFY_API_KEY"]

    def ask(self, query: str, user: str, conversation_id: str = "") -> dict[str, Any]:
        payload = {
            "inputs": {},
            "query": query,
            "response_mode": "blocking",
            "user": user,
        }
        if conversation_id:
            payload["conversation_id"] = conversation_id
        r = requests.post(
            f"{self.base}/chat-messages",
            headers={"Authorization": f"Bearer {self.key}"},
            json=payload,
            timeout=90,
        )
        r.raise_for_status()
        return r.json()

if __name__ == "__main__":
    client = DifyChat()
    first = client.ask("What is the local transit reimbursement cap?", user="staff-7")
    print(first.get("answer"))
    cid = first.get("conversation_id", "")
    second = client.ask("What about first-class rail?", user="staff-7", conversation_id=cid)
    print(second.get("answer"))

Use a stable id from your login system as user. The second turn must send conversation_id or “that” has no antecedent. Chat apps use /v1/chat-messages; a pure Workflow uses the run endpoint on that app’s API page and passes inputs.


Anti-patterns

Anti-patternDo this instead
Dump unscanned PDFs and skip retrieval testTest retrieval before users
One Agent, 30 tools, max iterationsSplit a Workflow; group tools
Key in the frontend or a public repoBFF + env vars
Swap embeddings, skip rebuildRe-process the corpus

Next steps

评论