!LangChain代理决策架构与源码深度剖析(75)

部署运行你感兴趣的模型镜像

LangChain代理决策架构与源码深度剖析

一、LangChain代理决策架构概述

1.1 代理决策架构的核心组件

LangChain代理的决策架构是其智能交互的核心,主要由大语言模型(LLM)工具集(Tools)提示模板(Prompt Template)规划器(Planner)执行器(Executor)反馈机制六大组件构成。这些组件通过协同工作,实现从用户输入解析到最终结果输出的完整决策流程。

在LangChain源码中,这些核心组件分别对应不同的类与模块。大语言模型接口定义在langchain.llms.base.py文件中,其抽象基类LLM定义了模型调用的基础方法:

from abc import ABC, abstractmethod

class LLM(ABC):
    """大语言模型抽象基类"""
    @abstractmethod
    def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
        """执行模型调用,返回生成文本"""
        pass

    def __call__(self, prompt: str, stop: Optional[List[str]] = None) -> str:
        return self._call(prompt, stop)

工具集的实现则分布在langchain.tools目录下,每个工具类继承自BaseTool,并实现具体的run方法。例如,文件读取工具的定义:

from langchain.tools.base import BaseTool

class FileReaderTool(BaseTool):
    name = "file_reader"
    description = "用于读取指定路径的文件内容"

    def run(self, file_path: str) -> str:
        try:
            with open(file_path, 'r') as f:
                return f.read()
        except FileNotFoundError:
            return f"文件 {file_path} 未找到"

提示模板通过langchain.prompts模块管理,PromptTemplate类允许用户定义动态填充的提示内容:

from langchain.prompts import PromptTemplate

prompt = PromptTemplate(
    input_variables=["question"],
    template="请回答这个问题:{question}"
)

1.2 决策架构的整体工作流程

LangChain代理的决策流程可概括为输入解析→规划决策→工具执行→结果整合→反馈优化的循环。当用户输入任务后,代理首先通过大语言模型解析意图,结合提示模板构建规划提示;接着规划器生成执行步骤和工具调用方案;执行器按方案调用工具获取信息;最后将工具结果与模型输出整合,并通过反馈机制优化后续决策。

核心控制逻辑在langchain.agents.Agent类中实现:

class Agent:
    def __init__(self, llm, tools, prompt_template):
        self.llm = llm
        self.tools = tools
        self.prompt_template = prompt_template

    def run(self, input):
        while True:
            # 规划阶段
            plan = self._plan(input)
            if self._is_finished(plan):
                return self._extract_final_answer(plan)
            
            # 执行阶段
            action_result = self._execute(plan.action)
            input = self._update_input(input, action_result)

该架构通过不断迭代决策与执行,逐步逼近问题的最优解,适应复杂任务需求。

1.3 决策架构与其他LangChain模块的关系

代理决策架构与LangChain其他模块紧密耦合。例如,与内存模块(langchain.memory)结合可实现多轮对话的上下文管理,通过ConversationBufferMemory类存储历史对话:

from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory()
memory.save_context({"input": "你好"}, {"output": "您好!有什么可以帮助您?"})

在与向量数据库(如ChromaFAISS)集成时,代理可通过检索增强生成(RAG)模式,从知识库中提取相关信息辅助决策:

from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings

embeddings = OpenAIEmbeddings()
vectorstore = Chroma(persist_directory="db", embedding_function=embeddings)

这种模块化设计使得代理决策架构具备高度扩展性,能够灵活适配不同应用场景。

二、输入解析与意图理解

2.1 自然语言输入的初步处理

用户输入的自然语言文本需经过预处理才能被代理理解。LangChain首先对输入进行清洗,去除多余的空格、特殊字符,并统一大小写。在langchain.utilities.text.py中,提供了基础文本处理工具:

def clean_text(text: str) -> str:
    """清洗文本,去除首尾空格,统一大小写"""
    return text.strip().lower()

分词与关键词提取是意图理解的关键步骤。虽然LangChain未内置复杂的NLP库,但可通过集成spaCyNLTK实现。例如,使用spaCy提取名词短语作为关键信息:

import spacy

nlp = spacy.load("en_core_web_sm")

def extract_key_phrases(text: str) -> List[str]:
    doc = nlp(text)
    return [chunk.text for chunk in doc.noun_chunks]

这些预处理操作能有效减少噪声,突出用户意图的核心要素。

2.2 大语言模型的意图识别

LangChain通过向大语言模型发送精心设计的提示,实现意图识别。例如,使用以下提示模板解析用户输入的任务类型:

intent_prompt = PromptTemplate(
    input_variables=["user_input"],
    template="""
    分析用户输入:{user_input}
    请判断任务类型(如问答、翻译、计算等),仅输出类型名称。
    """
)

def identify_intent(user_input, llm):
    prompt = intent_prompt.format(user_input=user_input)
    return llm(prompt)

在实际应用中,模型可能输出模糊结果。为此,LangChain引入意图置信度评估机制,通过二次提问或对比预设意图库来验证结果。例如:

def validate_intent(intent, user_input, llm):
    validation_prompt = PromptTemplate(
        input_variables=["intent", "user_input"],
        template="""
        你判断用户输入“{user_input}”的意图是“{intent}”。
        请确认该判断是否准确?如果不准确,请给出正确意图。
        """
    )
    return llm(validation_prompt.format(intent=intent, user_input=user_input))

这种交互式验证机制可显著提升意图识别的准确性。

2.3 上下文信息的整合与利用

在多轮对话场景中,代理需整合历史对话信息辅助意图理解。ConversationBufferMemory类将对话历史拼接为提示前缀,示例如下:

from langchain.chains import ConversationChain

conversation = ConversationChain(
    llm=llm, 
    memory=ConversationBufferMemory()
)

# 第一轮对话
response_1 = conversation.predict(input="今天天气如何?")
# 第二轮对话(自动包含第一轮上下文)
response_2 = conversation.predict(input="那明天呢?")

对于长对话历史,LangChain采用上下文压缩策略,通过摘要生成或关键词提取减少冗余信息。例如,使用RecursiveCharacterTextSplitter将长文本分割并摘要:

from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains.summarize import load_summarize_chain

text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_text(long_history_text)
chain = load_summarize_chain(llm, chain_type="map_reduce")
summary = chain.run(texts)

通过上下文整合与优化,代理能够更好地理解用户在复杂场景下的真实意图。

三、规划器:从意图到执行方案

3.1 规划器的核心功能与设计

规划器是LangChain代理的“大脑中枢”,负责将用户意图转化为可执行的步骤序列。其核心功能包括任务分解工具匹配步骤编排。在langchain.agents.planners目录下,规划器基类BasePlanner定义了通用接口:

from abc import ABC, abstractmethod

class BasePlanner(ABC):
    """规划器抽象基类"""
    @abstractmethod
    def plan(self, intermediate_steps, **kwargs) -> Union[List[ToolAction], str]:
        """生成执行计划,返回工具动作列表或文本"""
        pass

实际应用中,常见的规划器如LLMPlanner依赖大语言模型生成计划。其核心逻辑是将任务描述与工具信息组合成提示,请求模型输出步骤:

class LLMPlanner(BasePlanner):
    llm: LLM
    tools: List[BaseTool]

    def plan(self, intermediate_steps, **kwargs):
        tool_descriptions = "\n".join([f"{tool.name}: {tool.description}" for tool in self.tools])
        prompt = self.prompt.format(
            intermediate_steps=intermediate_steps,
            tools=tool_descriptions,
            **kwargs
        )
        return self.llm(prompt)

3.2 任务分解与步骤生成

复杂任务需分解为多个子任务。LangChain通过递归调用规划器实现分层分解,例如:

def decompose_task(task, llm, tools, max_depth=3):
    planner = LLMPlanner(llm=llm, tools=tools)
    steps = []
    depth = 0

    def _recursive_plan(sub_task):
        nonlocal depth
        if depth >= max_depth:
            steps.append(sub_task)
            return
        plan = planner.plan(intermediate_steps=[], user_input=sub_task)
        for step in plan.split("\n"):
            if "使用" in step:  # 识别工具调用步骤
                steps.append(step)
            else:  # 继续分解子任务
                _recursive_plan(step)
        depth += 1

    _recursive_plan(task)
    return steps

生成的步骤需具备明确的前置条件后置条件,以确保执行顺序的合理性。例如,“读取文件”步骤需在“文件存在”的前提下执行,执行后需更新文件内容已读取的状态。

3.3 工具匹配与优先级排序

规划器根据任务需求从工具集中筛选合适的工具。匹配过程基于工具描述与任务关键词的语义相似度,可通过嵌入向量计算实现。在langchain.agents中,工具匹配逻辑如下:

import numpy as np
from langchain.embeddings import OpenAIEmbeddings

embeddings = OpenAIEmbeddings()

def match_tools(task, tools):
    task_embedding = embeddings.embed_query(task)
    scores = []
    for tool in tools:
        tool_embedding = embeddings.embed_query(tool.description)
        score = np.dot(task_embedding, tool_embedding) / (
            np.linalg.norm(task_embedding) * np.linalg.norm(tool_embedding)
        )
        scores.append(score)
    sorted_indices = np.argsort(scores)[::-1]
    return [tools[i] for i in sorted_indices]

对于多个匹配工具,规划器通过优先级规则排序。例如,优先选择执行速度快、资源消耗低的工具,或根据历史使用频率进行排序。最终生成的执行方案将按优先级依次调用工具。

四、执行器:工具调用与结果处理

4.1 执行器的工作流程与机制

执行器负责按规划器生成的方案调用工具,并处理返回结果。其核心流程包括工具实例化参数传递异常处理结果解析。在langchain.agents.executor.py中,基础执行器类BaseExecutor定义如下:

class BaseExecutor:
    def __init__(self, tools):
        self.tools = {tool.name: tool for tool in tools}

    def execute(self, action):
        tool = self.tools.get(action.tool)
        if not tool:
            raise ValueError(f"工具 {action.tool} 未找到")
        try:
            result = tool.run(**action.args)
            return result
        except Exception as e:
            return f"工具执行失败:{str(e)}"

执行器支持并行执行多个独立工具,通过asyncio库实现异步调用。例如,同时调用天气查询与新闻检索工具:

import asyncio
from langchain.tools import BaseTool

class WeatherTool(BaseTool):
    # 天气查询工具实现

class NewsTool(BaseTool):
    # 新闻检索工具实现

async def parallel_execute(tools, actions):
    tasks = [tool.run(**action.args) for tool, action in zip(tools, actions)]
    return await asyncio.gather(*tasks)

4.2 工具调用的参数处理

工具调用需确保参数格式正确。LangChain通过参数校验机制避免错误传递,例如使用pydantic库定义工具输入模型:

from pydantic import BaseModel
from langchain.tools import BaseTool

class FileReadInput(BaseModel):
    file_path: str

class FileReaderTool(BaseTool):
    name = "file_reader"
    description = "用于读取指定路径的文件内容"

    def _run(self, file_path: str) -> str:
        # 工具逻辑

    def _arun(self, file_path: str) -> Awaitable[str]:
        # 异步工具逻辑

    args_schema = FileReadInput

当执行器调用工具时,会自动验证参数是否符合模型定义:

from langchain.agents import AgentExecutor

executor = AgentExecutor(tools=[FileReaderTool()])
action = {"tool": "file_reader", "args": {"file_path": "/path/to/file.txt"}}
try:
    executor.execute(action)
except ValueError as e:
    # 参数校验失败处理

4.3 执行结果的解析与整合

工具返回的结果需解析为代理可处理的格式。对于结构化数据(如JSON),执行器直接解析;对于非结构化文本,通过正则表达式或大语言模型提取关键信息。例如,解析天气查询结果中的温度数据:

import re

def parse_weather_result(result):
    match = re.search(r"温度:(\d+)℃", result)
    if match:
        return int(match.group(1))
    return None

多个工具的结果需整合为统一输出。LangChain提供结果合并策略,如简单拼接、摘要生成或基于规则的筛选。例如,将新闻标题与天气信息合并:

def merge_results(weather_result, news_results):
    weather_summary = f"天气:{weather_result}"
    news_summary = ", ".join([r.title for r in news_results])
    return f"{weather_summary};新闻:{news_summary}"

通过灵活的结果处理机制,执行器确保信息能有效支持后续决策。

五、反馈机制:决策优化与迭代

5.1 反馈信号的收集与分析

反馈机制是代理优化决策的关键。LangChain从多个维度收集反馈信号:

  1. 用户评价:用户对结果的满意度评分或文本反馈;
  2. 结果准确性:通过与标准答案对比或外部验证服务评估;
  3. 执行效率:工具调用耗时、资源消耗等指标。

langchain.agents中,反馈收集接口定义如下:

class FeedbackCollector:
    def collect(self, user_input, result, user_feedback=None):
        """收集反馈信息"""
        data = {
            "user_input": user_input,
            "result": result,
            "user_feedback": user_feedback
        }
        self._save_to_log(data)

    def _save_to_log(self, data):
        # 保存反馈数据到日志或数据库
        pass

收集到的反馈需经过分析提炼,转化为可操作的优化信号。例如,通过情感分析判断用户反馈的褒贬倾向:

from transformers import pipeline

sentiment_analyzer = pipeline("sentiment-analysis")

def analyze_feedback(feedback):
    result = sentiment_analyzer(feedback)[0]
    if result["label"] == "POSITIVE":
        return "positive"
    elif result["label"] == "NEGATIVE":
        return "negative"
    return "neutral"

5.2 基于反馈的决策调整

根据反馈信号,代理通过多种方式调整决策:

  1. 提示优化:修改提示模板的措辞、结构或示例,引导模型生成更好的结果;
  2. 工具替换:将低效或错误的工具替换为更合适的选项;
  3. 规划策略调整:改变任务分解方式或步骤优先级。

例如,当用户反馈结果不完整时,代理可在提示中增加补充说明:

def enhance_prompt(prompt, feedback):
    if "不完整" in feedback:
        new_prompt = f"{prompt}\n请确保回答涵盖所有关键信息。"
        return new_prompt
    return prompt

对于频繁失败的工具调用,代理可将其从工具集中临时移除,并记录原因:

class ToolManager:
    def __init__(self, tools):
        self.tools = tools
        self.disabled_tools = []

    def disable_tool(self, tool_name, reason):
        tool = next((t for t in self.tools if t.name == tool

LangChain代理决策架构与源码深度剖析(续)

六、多轮对话中的决策延续性管理

6.1 对话历史的存储与检索

在多轮对话场景中,LangChain代理需要维护完整的对话历史以理解上下文,从而做出连贯决策。ConversationBufferMemory类是管理对话历史的核心组件,其源码定义于langchain/memory/conversation_buffer.py。该类通过chat_memory属性存储对话消息列表,每条消息包含role(用户或代理)和content字段:

from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory()
memory.chat_memory.add_user_message("今天有什么新闻?")
memory.chat_memory.add_ai_message("今日科技新闻:OpenAI发布新模型...")

当需要检索历史信息时,可通过load_memory_variables方法获取完整对话内容,该方法会将历史消息格式化为适合大语言模型输入的文本:

memory_variables = memory.load_memory_variables({})
formatted_history = memory_variables["history"]
# 输出:"Human: 今天有什么新闻?\nAI: 今日科技新闻:OpenAI发布新模型..."

对于长对话历史,ConversationTokenBufferMemory类提供了基于Token数量的动态截断机制,确保输入不超过模型上下文长度限制:

from langchain.memory import ConversationTokenBufferMemory
from langchain.llms import OpenAI

llm = OpenAI()
memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=1000)

6.2 上下文感知的决策调整

代理在多轮对话中需根据历史信息调整决策。当用户提出后续问题时,代理会将对话历史作为上下文融入提示模板。例如,在ConversationChain类中,历史消息会被自动添加到新提示前:

from langchain.chains import ConversationChain

conversation = ConversationChain(llm=llm, memory=memory)
response_1 = conversation.predict(input="推荐一部科幻电影")
# 输出:《星际穿越》是一部经典科幻电影...
response_2 = conversation.predict(input="导演是谁?")
# 输出:《星际穿越》的导演是克里斯托弗·诺兰

若历史对话包含模糊信息,代理可通过追问澄清。源码中,ConversationChain_call方法会检查输入与历史的关联性,必要时生成追问提示:

class ConversationChain(Chain):
    def _call(self, inputs: Dict[str, Any]) -> Dict[str, Any]:
        input_text = inputs[self.input_key]
        history = self.memory.load_memory_variables(inputs)[self.memory.key]
        if not self._is_related(input_text, history):
            clarifying_prompt = self._generate_clarify_prompt(input_text)
            input_text = f"{clarifying_prompt}\n{input_text}"
        prompt = self.prompt.format(input=input_text, history=history)
        return {self.output_key: self.llm(prompt)}

6.3 跨对话的知识复用与迁移

为提升决策效率,LangChain支持跨对话的知识复用。ConversationSummaryMemory类通过定期生成对话摘要,将关键信息持久化。例如,在对话结束后,代理可将摘要存储到知识库:

from langchain.memory import ConversationSummaryMemory

summary_memory = ConversationSummaryMemory(llm=llm)
summary_memory.chat_memory.add_user_message("解释量子力学")
summary_memory.chat_memory.add_ai_message("量子力学是研究微观粒子...")
summary = summary_memory.load_memory_variables({})["summary"]
# 输出:对话讨论了量子力学的基本概念...

当下次遇到相似问题时,代理可检索历史摘要辅助决策。VectorDBQAWithSourcesChain类实现了基于向量数据库的检索增强机制,将历史摘要与新问题进行语义匹配:

from langchain.chains import VectorDBQAWithSourcesChain
from langchain.vectorstores import Chroma

vectorstore = Chroma(persist_directory="knowledge_db", embedding_function=embeddings)
chain = VectorDBQAWithSourcesChain.from_llm(llm=llm, vectorstore=vectorstore)
response = chain({"question": "量子纠缠是什么?"})
# 结合历史摘要与知识库生成回答

七、复杂任务的分层决策策略

7.1 任务树的构建与管理

对于复杂任务,LangChain通过构建任务树实现分层决策。LLMChainSequentialChain的组合使用可将任务分解为子链。例如,处理“撰写市场分析报告”任务时,可拆分为数据收集、数据分析、报告撰写三个子任务:

from langchain.chains import LLMChain, SequentialChain
from langchain.prompts import PromptTemplate

data_prompt = PromptTemplate(input_variables=["topic"], template="收集{topic}的市场数据")
analysis_prompt = PromptTemplate(input_variables=["data"], template="分析{data}并总结趋势")
report_prompt = PromptTemplate(input_variables=["analysis"], template="根据{analysis}撰写报告")

data_chain = LLMChain(llm=llm, prompt=data_prompt, output_key="data")
analysis_chain = LLMChain(llm=llm, prompt=analysis_prompt, output_key="analysis")
report_chain = LLMChain(llm=llm, prompt=report_prompt, output_key="report")

sequential_chain = SequentialChain(
    chains=[data_chain, analysis_chain, report_chain],
    input_variables=["topic"],
    output_variables=["report"]
)
result = sequential_chain({"topic": "智能手机市场"})

任务树的节点包含任务描述、依赖关系和执行状态,通过TaskNode类管理:

class TaskNode:
    def __init__(self, task_id, description, dependencies=[]):
        self.task_id = task_id
        self.description = description
        self.dependencies = dependencies
        self.status = "pending"
        self.children = []

    def add_child(self, child_node):
        self.children.append(child_node)

    def is_ready(self):
        return all([d.status == "completed" for d in self.dependencies])

7.2 子任务的协同与调度

子任务的执行顺序由依赖关系决定。TaskScheduler类负责遍历任务树,按拓扑序调度子任务:

from collections import deque

class TaskScheduler:
    def __init__(self, root_task):
        self.root_task = root_task

    def schedule(self):
        queue = deque([self.root_task])
        executed_tasks = []
        while queue:
            current_task = queue.popleft()
            if current_task.is_ready():
                self._execute_task(current_task)
                executed_tasks.append(current_task)
                for child in current_task.children:
                    queue.append(child)
            else:
                queue.append(current_task)
        return executed_tasks

    def _execute_task(self, task):
        # 调用LangChain链执行任务
        pass

对于可并行的子任务,AsyncSequentialChain支持异步并发执行。例如,同时进行数据收集与行业调研:

from langchain.chains import AsyncSequentialChain

data_chain = LLMChain(llm=llm, prompt=data_prompt, output_key="data")
research_chain = LLMChain(llm=llm, prompt=research_prompt, output_key="research")
async_chain = AsyncSequentialChain(
    chains=[data_chain, research_chain],
    input_variables=["topic"],
    output_variables=["data", "research"]
)
results = asyncio.run(async_chain.acall({"topic": "新能源汽车市场"}))

7.3 异常情况下的任务回滚与重试

当子任务执行失败时,LangChain支持任务回滚与重试机制。RetryLogic类实现了指数退避重试策略:

import time

class RetryLogic:
    def __init__(self, max_retries=3, base_delay=1):
        self.max_retries = max_retries
        self.base_delay = base_delay

    def retry(self, task_func):
        retries = 0
        while retries < self.max_retries:
            try:
                return task_func()
            except Exception as e:
                delay = self.base_delay * (2 ** retries)
                time.sleep(delay)
                retries += 1
        raise Exception("达到最大重试次数")

若任务失败导致后续任务无法继续,TaskRollback类负责撤销已执行的子任务:

class TaskRollback:
    def __init__(self, executed_tasks):
        self.executed_tasks = executed_tasks

    def rollback(self):
        for task in reversed(self.executed_tasks):
            self._undo_task(task)

    def _undo_task(self, task):
        # 执行撤销操作(如删除临时文件)
        pass

八、决策架构的安全与合规性设计

8.1 输入内容的安全校验

为防止恶意输入攻击,LangChain在代理入口处实施严格的内容校验。InputValidator类通过正则表达式和关键词过滤非法内容:

import re

class InputValidator:
    def __init__(self, blacklist=[]):
        self.blacklist = blacklist

    def validate(self, input_text):
        if any(re.search(word, input_text) for word in self.blacklist):
            raise ValueError("输入包含非法内容")
        return input_text

针对大语言模型可能生成的有害内容,OutputFilter类采用OpenAI的内容安全API进行检测:

import openai

class OutputFilter:
    def __init__(self, api_key):
        openai.api_key = api_key

    def filter(self, output_text):
        response = openai.Moderation.create(input=output_text)
        if response["results"][0]["flagged"]:
            raise ValueError("输出内容违反安全政策")
        return output_text

8.2 数据隐私保护机制

在处理用户数据时,LangChain遵循最小化原则。DataMasker类对敏感信息进行脱敏处理:

import re

class DataMasker:
    def mask_email(self, text):
        return re.sub(r'[\w\.-]+@[\w\.-]+\.\w+', '***@***.***', text)

    def mask_phone(self, text):
        return re.sub(r'\d{11}', '138******1234', text)

对于本地存储的对话数据,EncryptionManager类使用AES加密算法保障安全:

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad

class EncryptionManager:
    def __init__(self, key):
        self.key = key.encode('utf-8')
        self.cipher = AES.new(self.key, AES.MODE_CBC)

    def encrypt(self, data):
        padded_data = pad(data.encode('utf-8'), AES.block_size)
        ciphertext = self.cipher.encrypt(padded_data)
        iv = self.cipher.iv
        return iv + ciphertext

    def decrypt(self, encrypted_data):
        iv = encrypted_data[:AES.block_size]
        ciphertext = encrypted_data[AES.block_size:]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        decrypted_data = unpad(cipher.decrypt(ciphertext), AES.block_size)
        return decrypted_data.decode('utf-8')

8.3 合规性约束与审计日志

为满足合规要求,LangChain内置策略引擎控制代理行为。PolicyEngine类定义了可执行操作的白名单:

class PolicyEngine:
    def __init__(self, allowed_tools=[]):
        self.allowed_tools = allowed_tools

    def is_operation_allowed(self, tool_name):
        return tool_name in self.allowed_tools

所有决策操作均记录审计日志,AuditLogger类负责存储时间戳、用户ID、操作内容等信息:

import logging

class AuditLogger:
    def __init__(self, log_file):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(message)s')
        file_handler = logging.FileHandler(log_file)
        file_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)

    def log_operation(self, user_id, operation, details):
        self.logger.info(f"用户ID: {user_id}, 操作: {operation}, 详情: {details}")

九、决策架构的性能优化策略

9.1 大语言模型调用的优化

减少模型调用次数是性能优化的关键。PromptCombiner类将多个小提示合并为批量请求:

class PromptCombiner:
    def combine(self, prompts):
        combined_prompt = "\n".join([f"问题{i}: {p}" for i, p in enumerate(prompts)])
        return combined_prompt

    def split_results(self, combined_result, num_prompts):
        results = combined_result.split("\n")
        return [r.split(": ", 1)[1] for r in results[:num_prompts]]

针对高频问题,PromptCache类使用LRU缓存机制复用历史结果:

from functools import lru_cache

class PromptCache:
    @lru_cache(maxsize=128)
    def get_cached_result(self, prompt):
        return self._call_llm(prompt)

    def _call_llm(self, prompt):
        # 实际调用大语言模型
        pass

9.2 工具执行的效率提升

对于I/O密集型工具,LangChain采用异步非阻塞调用。以aiohttp实现异步HTTP请求工具为例:

import aiohttp
import asyncio

class AsyncHTTPClient:
    async def get(self, url):
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                return await response.text()

async def batch_fetch(urls):
    client = AsyncHTTPClient()
    tasks = [client.get(url) for url in urls]
    return await asyncio.gather(*tasks)

对于CPU密集型任务,ProcessPoolExecutor将计算负载分发到多个进程:

import concurrent.futures
import asyncio

def cpu_intensive_task(n):
    # 复杂计算逻辑
    pass

async def run_cpu_task(n):
    loop = asyncio.get_running_loop()
    with concurrent.futures.ProcessPoolExecutor() as executor:
        return await loop.run_in_executor(executor, cpu_intensive_task, n)

9.3 动态资源分配与负载均衡

ResourceAllocator类根据任务优先级动态分配计算资源:

class ResourceAllocator:
    def __init__(self, max_tokens=1000):
        self.available_tokens = max_tokens

    def allocate_tokens(self, task):
        required_tokens = self._estimate_tokens(task)
        if required_tokens <= self.available_tokens:
            self.available_tokens -= required_tokens
            return True
        return False

    def _estimate_tokens(self, task):
        # 根据任务复杂度估算Token数量
        pass

在分布式环境中,LoadBalancer类通过哈希算法将任务分发到不同节点:

class LoadBalancer:
    def __init__(self, nodes=[]):
        self.nodes = nodes

    def route_task(self, task):
        node_index = hash(task) % len(self.nodes)
        return self.nodes[node_index]

十、决策架构的可扩展性设计

10.1 插件式工具集成机制

LangChain采用插件架构支持工具扩展。ToolRegistry类管理工具的注册与发现:

class ToolRegistry:
    def __init__(self):
        self.tools = {}

    def register_tool(self, tool):
        self.tools[tool.name] = tool

    def get_tool(self, tool_name):
        return self.tools.get(tool_name)

    def list_tools(self):
        return list(self.tools.values())

自定义工具只需继承BaseTool类并实现run方法即可接入:

class CustomTool(BaseTool):
    name = "custom_tool"
    description = "自定义功能描述"

    def run(self, input_str):
        # 自定义工具逻辑
        return f"处理结果: {input_str}"

10.2 提示模板的动态生成

PromptGenerator类支持根据任务类型自动生成提示模板:

class PromptGenerator:
    def generate(self, task_type, context):
        if task_type == "问答":
            return f"请回答问题:{context}"
        elif task_type == "翻译":
            return f"将以下内容翻译成英文:{context}"
        return context

通过jinja2模板引擎实现更复杂的动态渲染:

from jinja2 import Template

template_str = "根据{data}生成{type}报告"
template = Template(template_str)
generated_prompt = template.render(data="市场数据", type="年度")

10.3 多模型协作与热插拔

ModelRouter类实现大语言模型的动态切换:

class ModelRouter:
    def __init__(self, models={}):
        self.models = models

    def route(self, task):
        if "复杂计算" in task:
            return self.models["math_model"]
        return self.models["default

您可能感兴趣的与本文相关的镜像

Qwen3-VL-30B

Qwen3-VL-30B

图文对话
Qwen3-VL

Qwen3-VL是迄今为止 Qwen 系列中最强大的视觉-语言模型,这一代在各个方面都进行了全面升级:更优秀的文本理解和生成、更深入的视觉感知和推理、扩展的上下文长度、增强的空间和视频动态理解能力,以及更强的代理交互能力

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Android 小码蜂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值