大模型主流推理范式详解

本文系统详解大语言模型(LLM)主流推理范式,涵盖静态链式推理(CoT、Self-Consistency)、智能体交互推理(ReAct)、自我反思迭代(Reflexion)、流式动态推理(InFlow)及进阶思维树(ToT)。重点剖析各范式核心原理、执行闭环、优缺点及可运行Python代码实现,并提供工程选型建议,强调ReAct为工业Agent基石,Reflexion提升纠错能力,InFlow适配低延迟实时场景。

大模型主流推理范式详解(含代码实现)

一、推理范式概述

大模型推理范式是 大语言模型(LLM)完成复杂问题求解、决策、工具调用、自我纠错 的核心思维架构。传统单次生成式推理无法解决多步骤、需外部信息、存在错误迭代的复杂任务,因此业界衍生出多种结构化推理范式。

推理范式核心演进逻辑:单次静态推理 → 链式分步推理 → 思考+行动联动推理 → 自我反思迭代推理 → 流式动态推理。

本文详细讲解当前工业界与学术界主流范式:CoT 思维链、ReAct 推理行动范式、Reflexion 自我反思范式、InFlow 流式推理范式,同时补充基础 Self-Consistency、Tree of Thoughts 进阶范式,全文无图片,纯文字 + 可运行代码。

二、基础推理范式(静态链式推理)

2.1 CoT(Chain of Thought 思维链)

2.1.1 核心原理

CoT 是最基础的多步骤推理范式,打破大模型「直接输出答案」的单次生成模式。强制模型输出中间思考过程,将复杂问题拆解为多步简单子问题,逐步推导最终结果,适配数学推理、逻辑题、常识推理场景。

核心特性:

  1. 自然语言形式记录推理草稿
  2. 无外部工具调用、无环境交互
  3. 单向线性推理,无反向纠错
2.1.2 优缺点
  • 优势:极低接入成本、大幅提升复杂推理准确率、适配所有 LLM
  • 劣势:无法调用外部工具、无法修正推理错误、长链条易遗忘上下文
2.1.3 代码实现(原生 CoT)
# 简易 CoT 思维链推理实现
def cot_inference(llm, question: str) -> str:
    """
    标准 CoT 推理:引导模型分步思考再作答
    :param llm: 大模型调用对象
    :param question: 待推理问题
    :return: 推理过程+最终答案
    """
    # CoT 专属提示词,强制分步推理
    cot_prompt = f"""
    请一步步思考并解答问题,输出详细推理过程,最后给出答案。
    问题:{question}
    推理过程:
    """
    result = llm.invoke(cot_prompt)
    return result


# 模拟大模型对象(演示用)
class MockLLM:
    def invoke(self, prompt: str) -> str:
        if "买苹果" in prompt:
            return """
            第一步:初始有5个苹果
            第二步:吃掉2个,剩余5-2=3个
            第三步:又购买3个,最终3+3=6个
            最终答案:6个
            """
        return "推理完成"


# 测试运行
if __name__ == "__main__":
    llm = MockLLM()
    res = cot_inference(llm, "小明买了5个苹果,吃了2个,又买了3个,现在有几个?")
    print(res)

2.2 Self-Consistency(自一致性推理)

2.2.1 核心原理

基于 CoT 的优化范式,摒弃单次推理,让模型生成多条不同的推理路径,通过投票筛选出现频率最高、最合理的答案,解决 CoT 单路径推理的偶然性错误。

2.2.2 代码实现
import random
from collections import Counter


def sc_inference(llm, question: str, sample_num: int = 5) -> str:
    """
    自一致性推理:生成多路径推理,投票选最优答案
    """
    prompt = f"一步步推理解答:{question},最后仅输出答案数字"
    # 生成多条推理结果
    results = [llm.invoke(prompt) for _ in range(sample_num)]
    # 提取答案并投票
    answers = [res.strip()[-1] for res in results]
    best_answer = Counter(answers).most_common(1)[0][0]
    return f"多路径投票最优答案:{best_answer}"


# 复用模拟模型测试
if __name__ == "__main__":
    llm = MockLLM()
    print(sc_inference(llm, "3*5+10等于多少?"))

三、主流智能体推理范式(核心重点)

3.1 ReAct 推理行动范式

3.1.1 核心原理

ReAct 是目前 工业界 Agent 最通用 的推理范式,核心公式:ReAct = Reason(思考) + Act(行动)。

解决了 CoT「只能空想、无法实操」的痛点,实现 推理思考、外部行动、结果观察 的闭环循环:

  1. Thought:基于当前信息,思考下一步需要做什么
  2. Action:执行具体操作(调用工具、搜索、计算、接口请求)
  3. Observation:获取行动返回的外部真实数据
  4. 循环迭代:基于新观察继续思考,直至任务完成

ReAct 是所有工具调用 Agent 的底层基础,广泛应用于知识库问答、联网搜索、自动化任务。

3.1.2 执行闭环

思考推理 → 工具行动 → 结果观测 → 迭代更新

3.1.3 优缺点
  • 优势:支持外部环境交互、适配动态任务、推理落地性强、工业成熟度高
  • 劣势:无自我纠错能力、单次错误行动会导致后续推理偏差、无记忆复盘
3.1.4 完整代码实现(ReAct 闭环 Agent)
# ReAct 完整推理行动闭环实现
import re


class ReActAgent:
    def __init__(self, llm):
        self.llm = llm
        # 注册可用工具
        self.tools = {
            "calculator": self.calc_tool,
            "search": self.search_tool
        }

    # 工具1:计算器
    def calc_tool(self, expr: str) -> str:
        try:
            return f"计算结果:{eval(expr)}"
        except:
            return "计算失败,表达式错误"

    # 工具2:简易搜索
    def search_tool(self, keyword: str) -> str:
        db = {"2026年GDP": "136万亿", "Python发明者": "吉多·范罗苏姆"}
        return db.get(keyword, "暂无搜索结果")

    # 解析模型输出的行动指令
    def parse_action(self, output: str):
        pattern = r"工具:(.+?)\|参数:(.+?)"
        res = re.search(pattern, output)
        if res:
            return res.group(1).strip(), res.group(2).strip()
        return None, None

    # ReAct 核心循环
    def run(self, task: str, max_loop: int = 5) -> str:
        context = f"任务:{task}\n请按格式输出:【思考】推理过程\n【工具】工具名|参数\n无工具则直接输出答案"
        for i in range(max_loop):
            # 1. Reason 思考
            llm_out = self.llm.invoke(context)
            context += f"\n本轮推理:{llm_out}"

            # 2. 解析行动
            tool_name, param = self.parse_action(llm_out)
            if not tool_name:
                return f"任务完成:{llm_out}"

            # 3. Act 执行行动
            action_res = self.tools[tool_name](param)

            # 4. Observation 观察结果,更新上下文
            context += f"\n【观测结果】{action_res}"

        return "任务超出最大迭代次数,执行终止"


# 模拟增强版大模型
class MockReActLLM:
    def invoke(self, prompt: str) -> str:
        if "GDP" in prompt:
            return "【思考】需要搜索2026年GDP数据\n【工具】search|2026年GDP"
        if "3*8+20" in prompt:
            return "【思考】需要计算数学表达式\n【工具】calculator|3*8+20"
        return "任务已完成"


# 测试 ReAct 闭环
if __name__ == "__main__":
    agent = ReActAgent(MockReActLLM())
    print(agent.run("查询2026年GDP数据"))
    print("-" * 50)
    print(agent.run("计算3*8+20的结果"))

3.2 Reflexion 自我反思迭代范式

3.2.1 核心原理

Reflexion 是 带记忆、可自我纠错、迭代进化 的高阶推理范式,区别于 ReAct 的核心:新增反思复盘机制。

核心架构:

  1. Responder(应答器):生成初始推理结果 / 行动方案
  2. Executor(执行器):执行任务,接收错误反馈
  3. Revisor(反思修订器):复盘失败原因,生成反思日志存入记忆
  4. 迭代重试:下一轮推理复用历史反思经验,规避重复错误

Reflexion 属于 语言强化学习,无需微调模型权重,仅通过自然语言记忆实现能力迭代。

3.2.2 核心特性
  1. 持久化反思记忆,跨任务复用经验
  2. 支持失败复盘、错误归因、策略优化
  3. 多轮迭代重试,持续提升任务成功率
3.2.3 优缺点
  • 优势:具备自我进化能力、大幅降低重复错误、适配高精准任务
  • 劣势:迭代耗时更长、资源消耗更高
3.2.4 代码实现(Reflexion 反思 Agent)
# Reflexion 自我反思迭代推理实现
class ReflexionAgent:
    def __init__(self, llm):
        self.llm = llm
        self.reflection_memory = []  # 反思记忆库

    def task_execute(self, task) -> tuple[str, bool]:
        """模拟任务执行,返回结果和是否成功"""
        if "除法" in task and "0" in task:
            return "执行失败:除零错误", False
        return "执行成功:任务完成", True

    def reflect(self, task, result) -> str:
        """自我反思:错误归因+经验总结"""
        reflect_prompt = f"""
        任务:{task}
        执行结果:{result}
        请分析失败原因,总结一条可复用的经验:
        """
        reflection = self.llm.invoke(reflect_prompt)
        self.reflection_memory.append(reflection)
        return reflection

    def run(self, task, max_trials=3) -> str:
        """多轮迭代重试"""
        for trial in range(1, max_trials + 1):
            print(f"===== 第{trial}轮尝试 =====")
            # 带入历史反思经验
            context = f"历史经验:{self.reflection_memory}\n当前任务:{task}"
            self.llm.invoke(context)

            # 执行任务
            res, success = self.task_execute(task)
            print(f"执行结果:{res}")

            if success:
                return f"任务成功,累计反思经验:{self.reflection_memory}"

            # 失败则反思复盘
            reflect_res = self.reflect(task, res)
            print(f"本轮反思:{reflect_res}")

        return "达到最大重试次数,任务失败"


# 模拟反思 LLM
class MockReflexionLLM:
    def invoke(self, prompt):
        if "除零错误" in prompt:
            return "经验总结:执行除法运算前,必须检查除数是否为0,规避除零异常"
        return "正常执行任务"


# 测试 Reflexion 迭代推理
if __name__ == "__main__":
    agent = ReflexionAgent(MockReflexionLLM())
    print(agent.run("计算100/0的结果"))

3.3 InFlow 流式动态推理范式

3.3.1 核心原理

InFlow(Incremental Flow 增量流式推理)是 新一代动态连续推理范式,针对传统范式「分段阻塞、固定步骤」的缺陷设计。

传统推理:一次性规划所有步骤,静态执行,无法适配动态变化的任务。

InFlow 推理:增量式、流式持续思考,边推理、边更新、边执行,实时适配上下文变化,无固定循环次数限制。

核心特点:

  1. 无固定 Thought / Action 拆分边界,推理流式连续
  2. 实时增量更新推理逻辑,适配动态任务变更
  3. 轻量化低延迟,适合实时对话、流式输出场景
3.3.2 适用场景

实时人机对话、长文本续写、动态任务编排、低延迟实时推理服务

3.3.3 优缺点
  • 优势:推理流畅无阻塞、动态适配任务、延迟极低、贴合人类实时思考模式
  • 劣势:复杂精准推理能力弱于 ReAct / Reflexion、可控性较低
3.3.4 代码实现(InFlow 流式增量推理)
# InFlow 流式增量推理实现
def inflow_inference(llm, task: str, stream_chunk: int = 3):
    """
    增量流式推理:分块逐步推理,实时输出增量结果
    :param stream_chunk: 分块推理次数
    """
    context = task
    final_result = ""
    print("【InFlow 流式推理启动,增量输出中】")

    for i in range(1, stream_chunk + 1):
        # 增量推理提示词
        flow_prompt = f"""
        基于已有上下文,继续增量推理,只输出本次新增推理内容:
        上下文:{context}
        新增推理:
        """
        chunk = llm.invoke(flow_prompt)
        final_result += chunk
        context += chunk
        print(f"第{i}轮增量推理:{chunk}")

    return f"【最终流式推理结果】{final_result}"


# 模拟流式 LLM
class MockInFlowLLM:
    def invoke(self, prompt):
        if "初始规划" in prompt:
            return "1. 梳理任务目标:完成月度开销统计"
        elif "拆解统计维度" in prompt:
            return "\n2. 拆解统计维度:餐饮、交通、购物"
        else:
            return "\n3. 汇总数据,计算总开销并生成总结"


# 测试 InFlow 流式推理
if __name__ == "__main__":
    llm = MockInFlowLLM()
    res = inflow_inference(llm, "帮我完成个人月度开销统计任务")
    print(res)

四、进阶推理范式补充

4.1 ToT(Tree of Thoughts 思维树)

核心原理

将线性推理升级为 树状分支推理,模型同时生成多条推理分支,对每条分支进行推演、剪枝、择优,解决多分支复杂决策问题(奥数、博弈、方案决策)。

核心代码片段
# ToT 分支推理简易实现
def tot_inference(llm, question, branch_num=3):
    # 生成多分支推理
    branches = [llm.invoke(f"推理分支{i}:{question}") for i in range(branch_num)]
    # 择优剪枝
    best_branch = max(branches, key=lambda x: len(x))
    return f"最优推理分支:{best_branch}"

五、主流推理范式横向对比

推理范式核心机制外部交互自我反思迭代能力适用场景
CoT 思维链线性分步推理无无无基础数学、逻辑推理
ReAct思考+行动闭环支持无有限迭代工具调用、联网 Agent
Reflexion行动+反思+记忆迭代支持有强迭代高精度任务、纠错场景
InFlow流式增量推理轻量支持无实时增量实时对话、流式输出
ToT 思维树多分支树状推理无无分支择优复杂决策、博弈推理

六、范式选型工程建议

  1. 简单问答、数学题:优先 CoT + Self-Consistency,成本最低
  2. 工具调用、自动化 Agent:标准 ReAct 范式,工业首选
  3. 高精准、低容错任务:Reflexion 反思迭代范式
  4. 实时流式对话、长文本生成:InFlow 增量流式范式
  5. 复杂多路径决策:ToT 思维树范式

七、总结

  1. 推理范式的核心演进方向:静态推理 → 交互推理 → 反思进化推理 → 动态流式推理
  2. ReAct 是工业界 Agent 的基石,Reflexion 解决 Agent「不会改错」的核心痛点
  3. InFlow 适配实时低延迟场景,是当前轻量化推理服务的主流方向
  4. 工程落地中,可 多范式组合使用(如 ReAct + Reflexion 工具 Agent,兼具交互能力与纠错能力)
深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值