前言
在金融场景下,大模型常出现计算幻觉或无法准确绘图的问题。单纯的 RAG 缺乏严谨的计算能力,而 Prompt 工程难以处理复杂长链条任务。本文基于 LangGraph + Qwen-7B,构建一套架构级的 Multi-Agent 金融系统,集成 Python 代码解释器、Cross-Encoder 重排序及 Supervisor 多智能体协作模式。
一、为什么金融场景更需要 Agent 而不是 Chatbot?
通用大模型在垂直领域落地存在三大硬伤:
- 算不准:概率生成的先天缺陷。大模型本质是文字接龙,无法进行确定性逻辑运算。
- 查不准:模糊语义干扰。传统向量检索易混淆相似专有名词(如股票代码)。
- 理不清:长链条任务的上下文污染。单体 Agent 难以维持复杂任务的状态一致性。
破局之道:从 Chatbot 进化为 Agent 团队。引入 Python 代码解释器保证计算准确,利用 Rerank 机制提升检索精度,通过多智能体分工管理上下文。
二、拒绝胡乱计算:给大模型装上 Python 代码解释器
LLM 擅长语义理解而非精确运算。引入 Python 代码解释器可将数学题转化为代码执行。
1. 破局思路:从'基于概率'到'基于逻辑'
借助 LangChain 的 PythonREPL 工具,Agent 工作流变为:理解需求 -> 编写代码 -> 执行代码 -> 总结回复。从 Probabilistic Generation 转向 Deterministic Execution。
2. 核心代码与工程踩坑:如何优雅地拦截绘图流?
本地运行绘图代码时,plt.show() 会阻塞进程。需自定义工具拦截绘图流并强制保存。
import os
import matplotlib.pyplot as plt
from langchain_core.tools import tool
from langchain_experimental.utilities import PythonREPL
python_repl = PythonREPL()
python_repl.globals.update({"pd": pd, "plt": plt, "np": np})
SAVE_DIR = r"./output"
@tool
def financial_code_interpreter(code: str) -> str:
"""【金融代码解释器 / 绘图工具】用于执行 Python 代码。Agent 只需负责 plt.plot(),系统会自动处理保存。"""
print(f"\n🐍 [Agent 正在真正执行代码] ...\n{code}")
# === 核心工程 Hack:代码清洗与劫持 ===
code = code.replace("plt.show()", "")
code = code.replace("plt.close()", )
code = code.replace(, )
:
result = python_repl.run(code)
plt.get_fignums():
file_path = os.path.join(SAVE_DIR, )
:
plt.savefig(file_path, dpi=, bbox_inches=)
plt.close()
image_msg =
Exception img_err:
image_msg =
:
image_msg =
result image_msg:
Exception e:

