Документация

Маршрутизация по намерению

Классифицируйте входящие запросы и направляйте каждый к оптимальному обработчику: детерминированной логике, специализированной LLM или человеку.

Не каждый запрос пользователя требует одинакового обработчика. На некоторые можно ответить поиском в базе данных. Некоторым нужна LLM с контекстом предметной области. Некоторые требуют человека. TypeSafe может стоять перед всеми ними как быстрый дешёвый классификатор, определяющий, какой обработчик вызвать.

Пример: маршрутизация в службе поддержки

Представьте, что вы создаёте систему поддержки клиентов. Приходят сообщения, и их нужно направлять правильному обработчику. Вместо того чтобы прогонять каждое сообщение через дорогую LLM, чтобы понять, что это за запрос, вы сначала классифицируете, а затем маршрутизируете соответственно.

%%{init: {"fontFamily": "Inter, sans-serif", "flowchart": {"rankSpacing": 35, "wrappingWidth": 300, "subGraphTitleMargin": {"top": 12, "bottom": 36}}}}%%
flowchart LR
    message["customer message"]

    subgraph req["TypeSafe evaluates questions<br/>in parallel"]
        direction TB
        intent["<b>Choice:</b> intent"]
        complexity["<b>Score:</b> complexity"]
        %% Invisible links stack the questions; they are answered in parallel.
        intent ~~~ complexity
    end

    message -- "one request<br/>message + 2 questions" --> req
    req -- "one response<br/>2 answers with<br/>confidence" --> confidence{"<b>intent confidence<br/>≥ 0.5?</b><br/>your code"}
    confidence -- "no" --> human["human agent"]
    confidence -- "yes" --> route{"<b>which intent?</b><br/>"}
    route -- "order_status" --> order["order lookup<br/>deterministic code"]
    route -- "product_question" --> product["product specialist LLM"]
    route -- "return_exchange" --> returns["returns specialist LLM"]
    route -- "complaint" --> escalate{"<b>complexity > 1<br/>or its confidence < 0.5?</b><br/>"}
    escalate -- "yes" --> human
    escalate -- "no" --> complaint["complaint resolution LLM"]

Шаг 1: классифицируйте намерение и сложность

questions
{
  "intent": {
    "type": "choice",
    "instructions": "The primary intent of this customer message",
    "criteria": {
      "order_status": "Asking about an existing order",
      "product_question": "Asking about a product before buying",
      "return_exchange": "Wants to return or exchange something",
      "complaint": "Unhappy with experience, wants resolution"
    }
  },
  "complexity": {
    "type": "score",
    "instructions": "How complex is this request to resolve",
    "criteria": [
      "Simple lookup or standard procedure",
      "Requires some judgment or multi-step process",
      "Unusual situation, edge case, or escalation needed"
    ]
  }
}

Шаг 2: направьте к оптимальному обработчику

routing.py

def route_ticket(ticket_id, response):
    intent = response.answers["intent"]
    complexity = response.answers["complexity"]

    if intent.confidence < 0.5:
        # If we don't have enough confidence to classify, route to a human agent
        return route_to_human_agent(ticket_id)

    if intent.choice == "order_status":
        handle_order_status(ticket_id)

    elif intent.choice == "product_question":
        handle_with_llm(ticket_id, PRODUCT_SPECIALIST)

    elif intent.choice == "return_exchange":
        handle_with_llm(ticket_id, RETURNS_SPECIALIST)

    elif intent.choice == "complaint":
        low_confidence = complexity.confidence < 0.5
        # A higher complexity.score leans toward the "escalation needed" end of the scale.
        if complexity.score > 1 or low_confidence:
            # Too complex for safe automation, or we're not sure about the complexity; route to a human.
            route_to_human_agent(ticket_id)
        else:
            handle_with_llm(ticket_id, COMPLAINT_RESOLUTION)

Одно намерение направляется в детерминированный код без участия LLM. Два — к разным специализированным LLM, каждая из которых загружена своим контекстом. Одно использует оценку сложности, чтобы выбрать между LLM и человеком. TypeSafe выполняет всю классификацию за один быстрый вызов; дорогие ресурсы задействуются только для запросов, которым они действительно нужны.

Обратите внимание на дополнительную проверку уверенности для оценки сложности. Как обсуждается в разделе Уверенность, всегда важно учитывать смысл низкой уверенности в контексте системы и ставок решения.