run_llm_direct_benchmark.py 6.57 KB
"""Direct LLM Intent Recognition Benchmark for GLSX.

Usage:
    python benchmarks/run_llm_direct_benchmark.py
"""

from __future__ import annotations

import argparse
import asyncio
import csv
import json
import logging
import os
import re
import sys
from pathlib import Path
import yaml

# Avoid UnicodeEncodeError on Windows stdout
sys.stdout.reconfigure(encoding='utf-8', errors='backslashreplace')

_ROOT = Path(__file__).resolve().parents[1]
if str(_ROOT) not in sys.path:
    sys.path.insert(0, str(_ROOT))

from intent_fusion.calibration import load_cases_from_yaml
from intent_fusion.tree import OpenAIAdapter

_HERE = Path(__file__).parent
_GLSX = _HERE / "glsx"

# Set default env values if not present
os.environ.setdefault("DASHSCOPE_API_KEY", "sk-107dd26bca184e39bd1744af7d634488")
os.environ.setdefault("INTENT_FUSION_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
os.environ.setdefault("INTENT_FUSION_MODEL", "deepseek-v4-flash")

# Load intents and format them into the prompt
def load_intents_info(yaml_path: Path) -> list[dict[str, str]]:
    with open(yaml_path, encoding="utf-8") as f:
        data = yaml.safe_load(f)
    intents = []
    for item in data.get("intents", []):
        intents.append({
            "name": item["name"],
            "tree_text": item.get("tree_text", "")
        })
    return intents

def build_llm_prompt(intents: list[dict[str, str]], message: str) -> str:
    # Build tree text representation containing names and tree_texts
    tree_lines = []
    for item in intents:
        tree_lines.append(f"- {item['name']}: {item['tree_text']}")
    tree_text = "\n".join(tree_lines)
    
    prompt = f"""你是一个意图识别分类器。请根据给出的意图类别定义,识别出用户消息所包含的意图。
如果是多意图(消息中包含多个互相独立的意图),请使用 '|' 分隔,按顺序输出所有匹配的意图,例如:'意图1 | 意图2'。

可选的意图列表及其定义如下:
{tree_text}

请直接输出匹配的意图名称(如果是多意图,用 '|' 分隔,如 '意图A | 意图B'),不要包含任何其他解释、前缀、Markdown标记或标点符号。

用户消息:"{message}"
意图识别结果:"""
    return prompt

def _normalize_multi_intent(text: str) -> str:
    parts = [p.strip() for p in (text or "").split("|")]
    parts = [p for p in parts if p]
    return "|".join(parts)

def _format_multi_intent(text: str) -> str:
    parts = [p.strip() for p in (text or "").split("|")]
    parts = [p for p in parts if p]
    return " | ".join(parts)

async def test_case(llm: OpenAIAdapter, intents: list[dict[str, str]], case, semaphore: asyncio.Semaphore):
    async with semaphore:
        prompt = build_llm_prompt(intents, case.message)
        messages = [{"role": "user", "content": prompt}]
        # Using a very low temperature for deterministic intent recognition
        try:
            response = await llm.chat(messages, temperature=0.0, max_tokens=100)
            predicted = response.strip().strip("'").strip('"').strip()
            # Clean up potential markdown formatting or prefix response
            if ":" in predicted and not any(intent["name"] in predicted.split(":")[0] for intent in intents):
                predicted = predicted.split(":", 1)[1].strip()
            if ":" in predicted and not any(intent["name"] in predicted.split(":")[0] for intent in intents):
                predicted = predicted.split(":", 1)[1].strip()
            # If the response contains markdown code block, extract it
            if "```" in predicted:
                predicted = predicted.replace("```", "").strip()
        except Exception as e:
            predicted = f"ERROR: {e}"
        
        is_correct = _normalize_multi_intent(predicted) == _normalize_multi_intent(case.expected_intent)
        return case, predicted, is_correct

async def main():
    parser = argparse.ArgumentParser(description="Run LLM direct intent recognition benchmark")
    parser.add_argument("--concurrency", type=int, default=5, help="Number of concurrent LLM requests")
    parser.add_argument("--output-csv", default=str(_GLSX / "llm_direct_benchmark_results.csv"))
    args = parser.parse_args()

    intents_path = _GLSX / "intents.yaml"
    cases_path = _GLSX / "cases.yaml"

    print(f"Loading intents from: {intents_path}")
    intents = load_intents_info(intents_path)
    print(f"Loaded {len(intents)} intents.")

    print(f"Loading cases from: {cases_path}")
    cases = load_cases_from_yaml(cases_path)
    print(f"Loaded {len(cases)} cases.")

    # Print tree_text to verify the formatted intents
    sample_prompt = build_llm_prompt(intents, "test")
    # Extract tree_text from prompt or rebuild it
    tree_lines = [f"- {item['name']}: {item['tree_text']}" for item in intents]
    tree_text = "\n".join(tree_lines)
    print("\n=================== Generated Tree Text ===================")
    print(tree_text)
    print("===========================================================\n")

    # Initialize LLM Adapter using env configurations
    llm = OpenAIAdapter(enable_thinking=False) # Direct LLM response doesn't strictly need thinking extraction enabled if we want immediate direct answer, but we can keep it standard. Let's disable thinking for direct parsing to get clean output if using compatible mode.
    
    semaphore = asyncio.Semaphore(args.concurrency)
    tasks = [test_case(llm, intents, case, semaphore) for case in cases]
    
    print("\nRunning benchmark cases...")
    results = []
    correct = 0
    
    for idx, future in enumerate(asyncio.as_completed(tasks), 1):
        case, predicted, is_correct = await future
        if is_correct:
            correct += 1
        
        mark = "OK" if is_correct else "FAIL"
        expected_display = _format_multi_intent(case.expected_intent)
        got_display = _format_multi_intent(predicted)
        print(f"[{idx}/{len(cases)}] [{mark}] {case.message:<45} expected={expected_display:<25} got={got_display}")
        
        results.append({
            "ok": "1" if is_correct else "0",
            "message": case.message,
            "expected": expected_display,
            "got": got_display,
        })

    accuracy = correct / len(cases) if cases else 0
    print(f"\nResult: {correct}/{len(cases)} ({accuracy:.1%})")

    output_csv = args.output_csv
    with open(output_csv, "w", encoding="utf-8-sig", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=["ok", "message", "expected", "got"])
        writer.writeheader()
        writer.writerows(results)
    print(f"Saved CSV: {output_csv}")

if __name__ == "__main__":
    asyncio.run(main())