Технології AI Написано практикуючими розробниками

Hybrid Reasoning: Chain-of-Thought + Формальна верифікація

Оновлено: 14 хв читання 4 переглядів

«Покажи свою роботу» — казала вчителька математики. Виявляється, вона була права. Chain-of-Thought prompting змусив LLM показувати reasoning steps — і accuracy злетіла. Від 17% до 58% на GSM8K. Просто від "Let's think step by step".


«Покажи свою роботу» — казала вчителька математики. Виявляється, вона була права. Chain-of-Thought prompting змусив LLM показувати reasoning steps — і accuracy злетіла. Від 17% до 58% на GSM8K. Просто від "Let's think step by step".

Але є проблема. LLM може показати красивий reasoning і прийти до неправильної відповіді. Кожен крок виглядає логічно. Стиль впевнений. Формулювання гладкі. А десь посередині — помилка. І ти її не помітиш, бо читаєш красивий текст, а не перевіряєш кожну операцію.

Формальна верифікація — це коли математика перевіряє математику. Автоматично. Без людської суб'єктивності. Без втомленості. Без bias. Комбінація CoT + formal verification — це hybrid reasoning для критичних застосувань. Для систем, де помилка — не просто незручність.


Chain-of-Thought: анатомія прориву

Історичний контекст:

До 2022 року LLM відповідали "in one shot" — питання → відповідь. Ніякого проміжного reasoning. Результати на математичних задачах були жахливими. GPT-3 на GSM8K (grade school math) — 17%. Це рівень третьокласника, який вгадує.

Breakthrough Wei et al. (2022):

Додавання "Let's think step by step" до prompt змінило все:

# Без Chain-of-Thought
DIRECT_PROMPT = """
Q: Roger has 5 tennis balls. He buys 2 more cans of tennis balls.
   Each can has 3 tennis balls. How many tennis balls does he have now?
A: 11
"""

# З Chain-of-Thought
COT_PROMPT = """
Q: Roger has 5 tennis balls. He buys 2 more cans of tennis balls.
   Each can has 3 tennis balls. How many tennis balls does he have now?
A: Roger started with 5 balls.
   He bought 2 cans with 3 balls each = 2 × 3 = 6 balls.
   Total: 5 + 6 = 11 balls.
   The answer is 11.
"""

Чому це працює — гіпотези:

class ChainOfThoughtMechanisms:
    """Теоретичні пояснення ефективності CoT"""

    HYPOTHESES = {
        "decomposition": """
            Складна задача розбивається на простіші.
            Кожен step — в межах working memory capacity моделі.
            Замість O(n!) — O(n) простих операцій.
        """,

        "intermediate_representations": """
            Кожен step генерує проміжний результат.
            Модель "бачить" цей результат у контексті.
            Наступний step будується на попередньому.
        """,

        "implicit_program_execution": """
            CoT — це implicit program.
            Кожен step — instruction.
            Модель "виконує" program у natural language.
        """,

        "error_localization": """
            Помилки локалізовані до конкретного step.
            Легше виявити, де пішло не так.
            Можна regenerate тільки проблемний step.
        """
    }

Taxonomy of Reasoning Errors

Систематичний аналіз помилок CoT:

from enum import Enum
from dataclasses import dataclass

class ErrorType(Enum):
    ARITHMETIC = "arithmetic"           # 7 × 8 = 54
    LOGICAL = "logical"                 # invalid inference
    FACTUAL = "factual"                 # wrong premises
    MISSING_STEP = "missing_step"       # skipped operation
    WRONG_OPERATION = "wrong_operation" # + замість ×
    CIRCULAR = "circular"               # A бо B, B бо A
    UNIT_ERROR = "unit"                 # метри vs кілометри
    SIGN_ERROR = "sign"                 # + замість -

@dataclass
class ReasoningStep:
    step_number: int
    text: str
    operation: str
    inputs: list
    output: str
    confidence: float

class ReasoningErrorDetector:
    """Детектор помилок у reasoning chains"""

    def __init__(self, arithmetic_verifier, logic_verifier):
        self.arith = arithmetic_verifier
        self.logic = logic_verifier

    def parse_chain(self, cot_text: str) -> list[ReasoningStep]:
        """Парсить CoT у структуровані steps"""
        steps = []
        lines = cot_text.strip().split('\n')

        for i, line in enumerate(lines):
            # Витягуємо операцію
            operation = self.extract_operation(line)
            inputs = self.extract_inputs(line)
            output = self.extract_output(line)

            steps.append(ReasoningStep(
                step_number=i,
                text=line,
                operation=operation,
                inputs=inputs,
                output=output,
                confidence=0.0  # буде обчислено
            ))

        return steps

    def verify_step(self, step: ReasoningStep) -> tuple[bool, ErrorType | None]:
        """Верифікує окремий step"""

        # Арифметична верифікація
        if step.operation in ['+', '-', '*', '/', '^']:
            try:
                expected = self.arith.compute(step.operation, step.inputs)
                if str(expected) != step.output:
                    return False, ErrorType.ARITHMETIC
            except:
                return False, ErrorType.WRONG_OPERATION

        # Логічна верифікація
        if step.operation in ['implies', 'and', 'or', 'not']:
            if not self.logic.verify_inference(step):
                return False, ErrorType.LOGICAL

        return True, None

    def verify_chain(self, steps: list[ReasoningStep]) -> dict:
        """Верифікує весь reasoning chain"""
        results = {
            "valid": True,
            "errors": [],
            "first_error_step": None
        }

        for step in steps:
            valid, error = self.verify_step(step)
            if not valid:
                results["valid"] = False
                results["errors"].append({
                    "step": step.step_number,
                    "type": error,
                    "text": step.text
                })
                if results["first_error_step"] is None:
                    results["first_error_step"] = step.step_number

        return results

Формальна верифікація: математичні гарантії

Що таке формальна верифікація:

Формальна верифікація — доведення коректності за допомогою математичних методів. Не тестування (кінцева кількість випадків), а доказ (всі можливі випадки).

Ландшафт інструментів:

class FormalVerificationTools:
    """Огляд інструментів формальної верифікації"""

    SMT_SOLVERS = {
        "Z3": {
            "developer": "Microsoft Research",
            "strengths": ["General purpose", "Well documented", "Python bindings"],
            "use_cases": ["Arithmetic", "Bit-vectors", "Arrays", "Quantifiers"]
        },
        "CVC5": {
            "developer": "Stanford/Iowa",
            "strengths": ["Strong theory support", "Finite model finding"],
            "use_cases": ["Strings", "Datatypes", "Sequences"]
        },
        "Yices2": {
            "developer": "SRI",
            "strengths": ["Fast for linear arithmetic"],
            "use_cases": ["Optimization", "Unsat cores"]
        }
    }

    THEOREM_PROVERS = {
        "Lean4": {
            "type": "Interactive",
            "strengths": ["Modern syntax", "Metaprogramming", "mathlib"],
            "learning_curve": "Medium"
        },
        "Coq": {
            "type": "Interactive",
            "strengths": ["Mature", "Dependent types", "Extraction"],
            "learning_curve": "High"
        },
        "Isabelle": {
            "type": "Interactive",
            "strengths": ["Automation", "Archive of proofs"],
            "learning_curve": "High"
        }
    }

    MODEL_CHECKERS = {
        "Spin": {
            "target": "Concurrent systems",
            "approach": "Explicit state"
        },
        "NuSMV": {
            "target": "Hardware verification",
            "approach": "Symbolic (BDD)"
        },
        "TLA+": {
            "target": "Distributed systems",
            "approach": "Temporal logic"
        }
    }

Z3 для верифікації reasoning:

from z3 import *

class Z3ReasoningVerifier:
    """Верифікація reasoning з використанням Z3"""

    def __init__(self):
        self.solver = Solver()
        self.variables = {}

    def declare_variable(self, name: str, type_: str):
        """Декларує змінну"""
        if type_ == 'int':
            self.variables[name] = Int(name)
        elif type_ == 'real':
            self.variables[name] = Real(name)
        elif type_ == 'bool':
            self.variables[name] = Bool(name)
        return self.variables[name]

    def add_constraint(self, constraint_str: str):
        """Додає constraint з текстового представлення"""
        # Парсить і додає constraint
        constraint = eval(constraint_str, {"__builtins__": {}}, self.variables)
        self.solver.add(constraint)

    def verify_arithmetic_step(self, equation: str) -> dict:
        """Верифікує арифметичний step"""
        # Приклад: "5 + 6 = 11"
        left, right = equation.split('=')

        # Створюємо verification constraint
        lhs = self.parse_expression(left.strip())
        rhs = self.parse_expression(right.strip())

        self.solver.push()
        # Перевіряємо чи НЕ рівні (якщо SAT — знайшли контрприклад)
        self.solver.add(lhs != rhs)

        result = self.solver.check()
        self.solver.pop()

        if result == unsat:
            return {"valid": True, "message": "Equation verified"}
        else:
            model = self.solver.model()
            return {"valid": False, "counterexample": str(model)}

    def verify_implication(self, premises: list, conclusion: str) -> dict:
        """Верифікує логічну імплікацію"""
        # premises => conclusion
        # Перевіряємо чи можливо: premises AND NOT conclusion

        premise_constraints = [self.parse_constraint(p) for p in premises]
        conclusion_constraint = self.parse_constraint(conclusion)

        self.solver.push()

        for p in premise_constraints:
            self.solver.add(p)

        self.solver.add(Not(conclusion_constraint))

        result = self.solver.check()
        self.solver.pop()

        if result == unsat:
            return {"valid": True, "message": "Implication verified"}
        else:
            return {"valid": False, "message": "Counterexample found"}

    def verify_word_problem(self, problem: dict) -> dict:
        """Верифікує рішення word problem"""
        # problem = {
        #     "variables": {"balls": "int", "cans": "int"},
        #     "constraints": ["balls >= 0", "cans >= 0"],
        #     "steps": ["initial = 5", "bought = 2 * 3", "total = initial + bought"],
        #     "answer": "total == 11"
        # }

        # Декларуємо змінні
        for name, type_ in problem["variables"].items():
            self.declare_variable(name, type_)

        # Додаємо constraints
        for c in problem["constraints"]:
            self.add_constraint(c)

        # Виконуємо steps (як додаткові constraints)
        for step in problem["steps"]:
            self.add_constraint(step)

        # Верифікуємо answer
        return self.verify_arithmetic_step(problem["answer"])

# Приклад використання
verifier = Z3ReasoningVerifier()

# Верифікація: "Roger has 5 balls, buys 2 cans of 3, total = 11"
result = verifier.verify_word_problem({
    "variables": {"initial": "int", "cans": "int", "per_can": "int", "bought": "int", "total": "int"},
    "constraints": ["initial == 5", "cans == 2", "per_can == 3"],
    "steps": ["bought == cans * per_can", "total == initial + bought"],
    "answer": "total == 11"
})
print(result)  # {"valid": True, "message": "Equation verified"}

Hybrid Architecture: CoT + Verification Pipeline

Повна архітектура системи:

import json
from typing import Optional
from dataclasses import dataclass
from enum import Enum

class VerificationStatus(Enum):
    VERIFIED = "verified"
    FAILED = "failed"
    TIMEOUT = "timeout"
    CANNOT_FORMALIZE = "cannot_formalize"

@dataclass
class VerifiedAnswer:
    answer: str
    reasoning: str
    verification_status: VerificationStatus
    formal_proof: Optional[str]
    attempts: int
    confidence: float

class HybridReasoningSystem:
    """Повна система hybrid reasoning"""

    def __init__(self, llm, formalizer, verifier, max_attempts=3):
        self.llm = llm
        self.formalizer = formalizer  # NL → Formal
        self.verifier = verifier      # Z3/Lean
        self.max_attempts = max_attempts

    def generate_cot(self, problem: str) -> str:
        """Генерує Chain-of-Thought reasoning"""
        prompt = f"""Solve this problem step by step.
        Show your work clearly.
        Format each step on a new line.
        End with "The answer is: [answer]"

        Problem: {problem}
        """

        response = self.llm.generate(prompt)
        return response

    def formalize_reasoning(self, cot: str, problem: str) -> dict:
        """Перетворює CoT у формальне представлення"""
        prompt = f"""Convert this reasoning to formal logic.

        Problem: {problem}

        Reasoning:
        {cot}

        Return JSON with:
        - variables: dict of variable names to types
        - premises: list of formal constraints
        - steps: list of formal steps
        - conclusion: formal statement of the answer

        Use Z3-compatible syntax.
        """

        response = self.llm.generate(prompt)

        try:
            return json.loads(response)
        except:
            return None

    def verify_formal(self, formal: dict) -> tuple[bool, str]:
        """Верифікує формальне представлення"""
        try:
            result = self.verifier.verify_word_problem(formal)
            return result["valid"], result.get("message", "")
        except Exception as e:
            return False, str(e)

    def generate_feedback(self, cot: str, error: str) -> str:
        """Генерує feedback для regeneration"""
        prompt = f"""The following reasoning has an error:

        {cot}

        Error: {error}

        Explain what went wrong and how to fix it.
        """

        return self.llm.generate(prompt)

    def solve(self, problem: str) -> VerifiedAnswer:
        """Повний pipeline: generate → formalize → verify → iterate"""

        for attempt in range(self.max_attempts):
            # 1. Generate CoT
            cot = self.generate_cot(problem)

            # 2. Extract answer
            answer = self.extract_answer(cot)

            # 3. Formalize
            formal = self.formalize_reasoning(cot, problem)

            if formal is None:
                # Не вдалось формалізувати — спробуємо простіший reasoning
                continue

            # 4. Verify
            valid, message = self.verify_formal(formal)

            if valid:
                return VerifiedAnswer(
                    answer=answer,
                    reasoning=cot,
                    verification_status=VerificationStatus.VERIFIED,
                    formal_proof=json.dumps(formal),
                    attempts=attempt + 1,
                    confidence=1.0
                )

            # 5. Generate feedback і regenerate
            feedback = self.generate_feedback(cot, message)
            problem = f"{problem}\n\nPrevious attempt had error: {feedback}"

        # Не вдалось верифікувати за max_attempts
        return VerifiedAnswer(
            answer=answer,
            reasoning=cot,
            verification_status=VerificationStatus.FAILED,
            formal_proof=None,
            attempts=self.max_attempts,
            confidence=0.5
        )

    def extract_answer(self, cot: str) -> str:
        """Витягує фінальну відповідь з CoT"""
        if "The answer is:" in cot:
            return cot.split("The answer is:")[-1].strip()
        # Fallback: остання лінія
        return cot.strip().split('\n')[-1]

Lean 4 для математичних доведень

Інтеграція LLM з Lean:

import subprocess
import tempfile
from pathlib import Path

class LeanProver:
    """Інтерфейс до Lean 4 theorem prover"""

    def __init__(self, lean_path: str = "lake"):
        self.lean_path = lean_path

    def verify_proof(self, proof_code: str) -> dict:
        """Верифікує Lean proof"""

        # Створюємо temp file
        with tempfile.NamedTemporaryFile(mode='w', suffix='.lean', delete=False) as f:
            f.write(proof_code)
            temp_path = f.name

        try:
            # Запускаємо Lean
            result = subprocess.run(
                [self.lean_path, "env", "lean", temp_path],
                capture_output=True,
                text=True,
                timeout=60
            )

            if result.returncode == 0:
                return {"valid": True, "message": "Proof verified"}
            else:
                return {
                    "valid": False,
                    "error": result.stderr,
                    "message": "Proof failed"
                }

        except subprocess.TimeoutExpired:
            return {"valid": False, "message": "Timeout"}
        finally:
            Path(temp_path).unlink()

    def generate_proof_template(self, theorem: str) -> str:
        """Генерує template для proof"""
        return f"""
import Mathlib

theorem problem : {theorem} := by
  sorry  -- LLM заповнить
"""

class LLMLeanProver:
    """LLM генерує Lean proofs, Lean верифікує"""

    def __init__(self, llm, lean_prover):
        self.llm = llm
        self.prover = lean_prover

    def formalize_to_lean(self, problem: str) -> str:
        """Формалізує задачу в Lean"""
        prompt = f"""Convert this math problem to a Lean 4 theorem statement.
        Use standard mathlib notation.

        Problem: {problem}

        Return only the theorem statement, e.g.:
        theorem problem (n : ℕ) : n + 0 = n
        """

        return self.llm.generate(prompt)

    def generate_proof(self, theorem: str) -> str:
        """LLM генерує proof"""
        prompt = f"""Prove this Lean 4 theorem:

        {theorem}

        Use tactics like:
        - simp, ring, linarith for arithmetic
        - intro, apply, exact for logic
        - induction for recursive proofs

        Return complete proof code.
        """

        return self.llm.generate(prompt)

    def prove(self, problem: str, max_attempts: int = 5) -> dict:
        """Повний цикл: formalize → prove → verify"""

        # 1. Formalize
        theorem = self.formalize_to_lean(problem)

        for attempt in range(max_attempts):
            # 2. Generate proof
            proof = self.generate_proof(theorem)

            # 3. Verify
            result = self.prover.verify_proof(proof)

            if result["valid"]:
                return {
                    "success": True,
                    "theorem": theorem,
                    "proof": proof,
                    "attempts": attempt + 1
                }

            # 4. Feedback для наступної спроби
            error = result.get("error", "Unknown error")
            theorem = f"""
            {theorem}

            Previous proof attempt failed with error:
            {error}

            Try a different approach.
            """

        return {
            "success": False,
            "theorem": theorem,
            "last_attempt": proof,
            "attempts": max_attempts
        }

Self-Consistency: статистична верифікація

Ідея: Генеруємо багато reasoning paths, вибираємо найконсистентнішу відповідь.

from collections import Counter
import numpy as np

class SelfConsistencyVerifier:
    """Self-consistency через majority voting"""

    def __init__(self, llm, num_samples: int = 10, temperature: float = 0.7):
        self.llm = llm
        self.num_samples = num_samples
        self.temperature = temperature

    def generate_samples(self, problem: str) -> list[tuple[str, str]]:
        """Генерує кілька reasoning samples"""
        samples = []

        for _ in range(self.num_samples):
            cot = self.llm.generate(
                f"Solve step by step: {problem}",
                temperature=self.temperature
            )
            answer = self.extract_answer(cot)
            samples.append((cot, answer))

        return samples

    def compute_consistency(self, samples: list[tuple[str, str]]) -> dict:
        """Обчислює consistency score"""
        answers = [s[1] for s in samples]
        counter = Counter(answers)

        total = len(answers)
        most_common = counter.most_common(1)[0]

        return {
            "best_answer": most_common[0],
            "frequency": most_common[1],
            "consistency_score": most_common[1] / total,
            "distribution": dict(counter),
            "entropy": self.compute_entropy(counter, total)
        }

    def compute_entropy(self, counter: Counter, total: int) -> float:
        """Обчислює entropy розподілу відповідей"""
        probs = [count / total for count in counter.values()]
        return -sum(p * np.log2(p) for p in probs if p > 0)

    def solve_with_consistency(self, problem: str) -> dict:
        """Вирішує з self-consistency"""
        samples = self.generate_samples(problem)
        consistency = self.compute_consistency(samples)

        # Знаходимо reasoning для найкращої відповіді
        best_answer = consistency["best_answer"]
        best_reasoning = None

        for cot, answer in samples:
            if answer == best_answer:
                best_reasoning = cot
                break

        return {
            "answer": best_answer,
            "reasoning": best_reasoning,
            "confidence": consistency["consistency_score"],
            "entropy": consistency["entropy"],
            "samples": len(samples)
        }

    def extract_answer(self, cot: str) -> str:
        """Нормалізує та витягує відповідь"""
        # Витягуємо числову відповідь
        lines = cot.strip().split('\n')
        for line in reversed(lines):
            # Шукаємо числа
            import re
            numbers = re.findall(r'[-+]?\d*\.?\d+', line)
            if numbers:
                return numbers[-1]
        return "unknown"

Застосування в критичних доменах

Medical Diagnosis Verification:

class MedicalReasoningVerifier:
    """Верифікація медичного reasoning"""

    def __init__(self, llm, medical_kb, drug_checker):
        self.llm = llm
        self.kb = medical_kb
        self.drugs = drug_checker

    def verify_diagnosis(self, symptoms: list, diagnosis: str, reasoning: str) -> dict:
        """Верифікує діагностичне reasoning"""

        checks = {
            "symptom_coverage": self.check_symptom_coverage(symptoms, reasoning),
            "logical_consistency": self.check_logical_consistency(reasoning),
            "kb_alignment": self.check_kb_alignment(diagnosis, symptoms),
            "differential_considered": self.check_differential(diagnosis, symptoms)
        }

        # Загальна оцінка
        all_passed = all(c["passed"] for c in checks.values())

        return {
            "verified": all_passed,
            "checks": checks,
            "recommendations": self.generate_recommendations(checks)
        }

    def check_symptom_coverage(self, symptoms: list, reasoning: str) -> dict:
        """Перевіряє чи всі симптоми враховані"""
        covered = []
        uncovered = []

        for symptom in symptoms:
            if symptom.lower() in reasoning.lower():
                covered.append(symptom)
            else:
                uncovered.append(symptom)

        return {
            "passed": len(uncovered) == 0,
            "covered": covered,
            "uncovered": uncovered
        }

    def check_kb_alignment(self, diagnosis: str, symptoms: list) -> dict:
        """Перевіряє узгодженість з knowledge base"""
        expected_symptoms = self.kb.get_symptoms(diagnosis)
        matching = set(symptoms) & set(expected_symptoms)
        missing = set(expected_symptoms) - set(symptoms)

        return {
            "passed": len(matching) / len(expected_symptoms) > 0.5,
            "matching_symptoms": list(matching),
            "missing_typical_symptoms": list(missing)
        }


class LegalContractVerifier:
    """Верифікація юридичного reasoning"""

    def __init__(self, llm, legal_rules):
        self.llm = llm
        self.rules = legal_rules

    def verify_contract_analysis(self, contract: str, analysis: str) -> dict:
        """Верифікує аналіз контракту"""

        checks = []

        # Перевіряємо кожне твердження в аналізі
        claims = self.extract_claims(analysis)

        for claim in claims:
            # Знаходимо релевантні clause в контракті
            relevant_clauses = self.find_relevant_clauses(contract, claim)

            # Перевіряємо чи claim підтримується
            supported = self.verify_claim(claim, relevant_clauses)

            checks.append({
                "claim": claim,
                "relevant_clauses": relevant_clauses,
                "supported": supported
            })

        return {
            "verified": all(c["supported"] for c in checks),
            "checks": checks
        }

Challenges та обмеження

Проблема формалізації:

class FormalizationChallenges:
    """Виклики перетворення NL → Formal"""

    CHALLENGES = {
        "ambiguity": """
            Natural language неоднозначна.
            "All students passed or failed" —
            ∀x(passed(x) ∨ failed(x)) чи
            (∀x passed(x)) ∨ (∀x failed(x))?
        """,

        "implicit_knowledge": """
            Багато assumptions не explicified.
            "John is taller than Mary who is taller than Sue"
            Implicit: transitivity of height
        """,

        "context_dependency": """
            Значення залежить від контексту.
            "bank" — фінансова установа чи берег річки?
        """,

        "world_knowledge": """
            Потрібні факти про світ.
            "Paris is the capital of France"
            Звідки verifier це знає?
        """,

        "quantifier_scope": """
            "Every student likes some teacher"
            ∀s∃t likes(s,t) чи ∃t∀s likes(s,t)?
        """
    }

class ScalabilityLimitations:
    """Обмеження масштабованості"""

    LIMITATIONS = {
        "verification_complexity": """
            SMT solving — NP-complete в загальному випадку.
            Для деяких queries — PSPACE.
            Timeout неминучий для складних проблем.
        """,

        "proof_search": """
            Theorem proving — undecidable.
            Потрібна guidance від LLM.
            Але LLM може вести в глухий кут.
        """,

        "formalization_bottleneck": """
            Formalization потребує людських зусиль.
            Auto-formalization неповна.
            Багато domains не формалізовані.
        """
    }

Metrics та Benchmarks

Оцінка hybrid reasoning систем:

class HybridReasoningMetrics:
    """Метрики для hybrid reasoning"""

    def compute_metrics(self, results: list[dict]) -> dict:
        """Обчислює всі метрики"""

        return {
            "accuracy": self.accuracy(results),
            "verification_rate": self.verification_rate(results),
            "formalization_success": self.formalization_success(results),
            "avg_attempts": self.avg_attempts(results),
            "trustworthiness": self.trustworthiness(results)
        }

    def accuracy(self, results: list[dict]) -> float:
        """Частка правильних відповідей"""
        correct = sum(1 for r in results if r["correct"])
        return correct / len(results)

    def verification_rate(self, results: list[dict]) -> float:
        """Частка верифікованих відповідей"""
        verified = sum(1 for r in results
                      if r["status"] == "verified")
        return verified / len(results)

    def trustworthiness(self, results: list[dict]) -> dict:
        """Trustworthiness analysis"""
        verified_correct = sum(1 for r in results
                              if r["status"] == "verified" and r["correct"])
        verified_total = sum(1 for r in results
                            if r["status"] == "verified")

        unverified_correct = sum(1 for r in results
                                if r["status"] != "verified" and r["correct"])
        unverified_total = sum(1 for r in results
                              if r["status"] != "verified")

        return {
            "verified_accuracy": verified_correct / verified_total if verified_total else 0,
            "unverified_accuracy": unverified_correct / unverified_total if unverified_total else 0,
            "verification_lift": (verified_correct / verified_total -
                                 unverified_correct / unverified_total)
                                 if verified_total and unverified_total else 0
        }

Ідеї для дослідження

Для бакалаврської роботи:

  • LLM + Z3 для верифікації арифметичних word problems
  • Pipeline для перевірки логічних задач (syllogisms)
  • Порівняння CoT з/без формальної верифікації на GSM8K

Для магістерської:

  • Automatic formalization: NL → Z3/Lean для specific domain
  • Hybrid system для юридичного або медичного reasoning
  • Оптимізація verification speed через incremental solving
  • Self-consistency + formal verification: ensemble methods

Для PhD:

  • Theoretical foundations: які класи задач можна верифікувати efficiently
  • Learning to formalize: end-to-end differentiable formalization
  • Probabilistic verification для uncertain domains
  • Human-AI collaboration в proof construction

Чому це критично важливо

AI в критичних системах — неминуче. Медицина використовує LLM для діагностики. Юриспруденція — для аналізу контрактів. Фінанси — для compliance. Авіація вже має AI copilots.

Але «AI сказав» — не аргумент. Не в суді. Не в лікарні. Не на борту літака. Потрібні гарантії. Формальні. Математичні. Такі, що їх можна перевірити.

Hybrid reasoning — це міст між flexibility LLM і rigor formal methods. Це не компроміс — це синергія. LLM генерує, formal methods верифікують. Кожен робить те, що вміє найкраще.

Для тих, хто готує наукову роботу з hybrid reasoning — від курсової до дисертації — фахівці SKP-Degree на skp-degree.com.ua готові допомогти з дослідженням, імплементацією та оформленням. Пишіть у Telegram: @kursovi_diplomy — команда має досвід супроводу проєктів на стику LLM, формальних методів та верифікації.

Ключові слова: hybrid reasoning, Chain-of-Thought, CoT, формальна верифікація, Z3, SMT solver, Lean, theorem prover, LLM reasoning, trustworthy AI, критичні системи, наукова робота, дипломна, магістерська, дисертація.

Про автора

Команда SKP-Degree

Верифікований автор

Розробники та дослідники AI · Python, TensorFlow, PyTorch · Досвід у промисловій розробці

Команда SKP-Degree — професійні розробники з досвідом 7+ років у промисловій розробці. Виконали 1000+ проєктів для студентів з України, Польщі та країн Балтії.

Python Django Java ML/AI React C# / .NET JavaScript

Потрібна допомога з роботою?

Замовте курсову чи дипломну роботу з програмування. Оплата після демонстрації!

Без передоплати Відеодемонстрація Автономна робота 24/7
Написати в Telegram