tp_voice/scripts
timur 02e139e7e6 test 1c 2026-10-08 02:15:26 +05:00
..
README.md test 1c 2026-10-08 02:15:26 +05:00
inbound_support.toml fix begin analize with activity 2026-06-26 21:47:33 +05:00
outbound_sales.toml fix begin analize with activity 2026-06-26 21:47:33 +05:00

README.md

scripts/ — Call compliance script definitions

Выгрузка документов клиента из 1С

Утилита tools/fetch_1c_client_documents.py находит контрагента по ИНН и выгружает документы за последние 150 дней, включая опубликованные табличные части. Пароль передаётся только через переменную окружения или интерактивный ввод:

export ONEC_ODATA_PASSWORD='секрет'
python tools/fetch_1c_client_documents.py \
  --inn 1234567890 \
  --output /var/lib/voice-pipeline/1c/1234567890.json

Период можно изменить через --days или точную дату --from-date YYYY-MM-DD. --limit N ограничивает число документов каждого типа; по умолчанию ограничения нет. JSON содержит краткую сводку, хронологию, полные поля документов, табличные части и задание для последующего LLM-анализа.


Each .toml file in this directory defines one compliance script. The analyzer loads whichever files are listed in config.toml under [analyzer] script_files.


Registering scripts in config.toml

[analyzer]
script_files = [
  "scripts/inbound_support.toml",
  "scripts/outbound_sales.toml",
]

Paths are resolved relative to the config file's directory. Absolute paths also work.

When a call arrives, analyzer.script_check.select_script() picks the first script whose directions list contains the call's direction ("inbound", "outbound", or "unknown"). Order the list with your most specific scripts first.


TOML schema

# Required
script_id  = "unique_snake_case_id"   # used in analysis.json artifacts
name       = "Human-readable name"    # shown in HTML reports

# Which call directions this script applies to.
# Values: "inbound" | "outbound" | "unknown"
# "unknown" catches Asterisk calls where direction was not detected.
directions = ["inbound"]

# One [[checklist]] block per item.
[[checklist]]
item        = "Short label (shown in report and passed to LLM)"
description = """
Optional. Longer guidance for the LLM explaining what evidence to look
for and how to judge this item. Wrap in triple-quotes for multi-line.
Mark critical items with КРИТИЧНО / CRITICAL in the description —
the LLM scoring prompt instructs it to weight described items more heavily.
"""

Field reference

Field Required Notes
script_id yes Unique. Used as the key in analysis.json. Changing it breaks historical report comparisons.
name no Defaults to script_id. Shown in HTML reports.
directions no Defaults to ["inbound", "outbound"] (matches all calls).
checklist[].item yes Short, unambiguous label. The LLM copies this verbatim into its JSON response.
checklist[].description no Detailed guidance for the LLM. Has no effect on the report UI — for LLM accuracy only.

Included scripts

File script_id Directions Items
inbound_support.toml inbound_support_v1 inbound, unknown 11
outbound_sales.toml outbound_sales_v1 outbound 12

inbound_support_v1 — item summary

# Item Critical
1 Приветствие с названием компании / Greeting with company name ✓
2 Представление оператора / Agent self-introduction
3 Предложение помощи / Offer of assistance
4 Уточнение имени клиента / Asking customer's name
5 Выяснение сути обращения / Understanding the issue
6 Подтверждение понимания / Confirming understanding
7 Решение вопроса или эскалация / Issue resolved or escalated ✓
8 Информирование о сроках / Timeline or next step communicated
9 Проверка удовлетворённости клиента / Checking customer satisfaction
10 Благодарность за обращение / Thanking the customer
11 Прощание / Farewell
12 Отсутствие грубости или раздражения / No rudeness or irritation
13 Чёткость и понятность речи / Clear and understandable speech

outbound_sales_v1 — item summary

# Item Critical
1 Представление агента и компании / Agent and company introduction ✓
2 Проверка удобства разговора / Checking if it's a good time
3 Чёткое обозначение цели звонка / Clear statement of call purpose
4 Квалификация клиента / Customer qualification
5 Выявление потребности / Identifying a pain point or need
6 Презентация под потребность клиента / Tailored value proposition
7 Упоминание ключевого УТП или выгоды / Key differentiator or benefit stated
8 Работа с возражением / Handling at least one objection ✓
9 Отсутствие давления или спора / No pressure tactics or arguing
10 Попытка закрытия или фиксация следующего шага / Closing attempt or next-step agreement ✓
11 Подтверждение договорённостей / Confirming what was agreed
12 Вежливое завершение звонка / Polite closing
13 Соблюдение регламента в отношении записи / Compliance with call recording notice
14 Профессиональный тон на протяжении звонка / Professional tone throughout

Versioning

When you revise a script, increment the version suffix in script_id (v1 → v2) and add the new file to script_files instead of editing the existing one. Historical analysis.json artifacts embed the script_id they were evaluated against, so old reports remain comparable.

# config.toml — keep both versions so you can compare
[analyzer]
script_files = [
  "scripts/inbound_support_v2.toml",   # new calls
  "scripts/outbound_sales.toml",
]

Writing a new script

  1. Copy inbound_support.toml as a starting point.
  2. Set a unique script_id and the correct directions.
  3. Write checklist items as observable, verifiable behaviours — things the LLM can confirm from the transcript text.
    • Good: "Agent stated the customer's name at least once"
    • Bad: "Agent was empathetic" (too subjective, low LLM accuracy)
  4. Mark 2–4 items as КРИТИЧНО / CRITICAL in their description. These anchor the scoring — if any critical item fails, the score should not exceed ~70 regardless of the rest.
  5. Keep the total checklist under 15 items. Beyond that, LLM accuracy on individual items degrades and scores become noisy.
  6. Register the file in config.toml and run a test call through the analyzer to verify the output shape.

Testing a script without real calls

Use the integration test fixture:

# tests/test_integration.py already patches call_llm_json.
# To test your script parsing specifically, run:

from analyzer.script_check import load_script_definitions, select_script
import os

os.environ["VOICE_PIPELINE_CONFIG"] = "config/config.toml"

definitions = load_script_definitions()
for d in definitions:
    print(d.script_id, d.directions, len(d.checklist), "items")