上周我花了整个周末时间做了一个有趣的实验:对比测试两个当前最热门的AI代理框架——LangChain和CrewAI在金融数据分析场景下的表现。这个实验源于我在分析上市公司财务报表时遇到的效率问题,传统方法需要反复编写Pandas代码查询不同表格,而AI代理理论上应该能自动完成这些繁琐工作。
我选择了Cohere的command-r-plus模型驱动LangChain,而CrewAI则使用GPT-3.5。这个选择本身就存在不对等性——command-r-plus在理解复杂指令方面确实更胜一筹。但我的主要目的是学习CrewAI的实际应用,性能对比只是副产品。
开发环境配置如下:
bash复制# 核心依赖版本
cohere==5.5.8
langchain==0.2.6
pandas==2.0.3
使用了苹果公司2017-2020年的真实财务数据:
数据加载代码:
python复制import pandas as pd
income_statement = pd.read_csv('income_statement.csv', index_col=0)
balance_sheet = pd.read_csv('balance_sheet.csv', index_col=0)
核心是创建一个安全的Python代码执行环境:
python复制from langchain_experimental.utilities import PythonREPL
from langchain.agents import Tool
python_repl = PythonREPL()
python_tool = Tool(
name="python_interpreter",
description="Executes python code in a sandbox",
func=python_repl.run
)
设计了一个支持多步工具调用的代理函数:
python复制def cohere_agent(message, preamble, tools, verbose=False):
response = co.chat(
model='command-r-plus',
message=message,
preamble=preamble,
tools=tools
)
while response.tool_calls:
tool_results = []
for tool_call in response.tool_calls:
output = functions_map[tool_call.name](**tool_call.parameters)
tool_results.append({"call": tool_call, "outputs": [output]})
response = co.chat(
model='command-r-plus',
message="",
tool_results=tool_results,
tools=tools
)
return response.text
查询利润表中的关键指标:
python复制preamble = """你是一个财务分析专家,正在使用Python处理利润表数据。
以下是数据预览:{head_df}""".format(head_df=income_statement.head(3).to_markdown())
questions = {
'q1': '最高销售成本是多少?',
'q2': '最大毛利率是多少?',
'q3': '营业利润与非营业支出的最小比率?'
}
for q in questions.values():
print(cohere_agent(q, preamble, tools))
执行过程显示,代理能够正确:
更复杂的跨表查询:
python复制preamble = """你正在同时处理利润表和资产负债表。
利润表预览:{income_head}
资产负债表预览:{balance_head}""".format(
income_head=income_statement.head(3).to_markdown(),
balance_head=balance_sheet.head(3).to_markdown()
)
question = "股东权益最大值与收入最小值的比率是多少?"
print(cohere_agent(question, preamble, tools))
代理成功执行了以下步骤:
当不提供数据预览时,代理会因列名猜测错误而失败:
python复制# 错误示例:尝试访问不存在的列名
preamble = "你正在处理利润表数据"
question = "最高销售成本是多少?"
output = cohere_agent(question, preamble, tools) # 报错KeyError
通过修改prompt让代理自主纠错:
python复制preamble = """如果遇到错误,请检查数据后重试。"""
output = cohere_agent(question, preamble, tools)
# 代理执行流程:
# 1. 首次尝试失败
# 2. 自动执行df.columns查看列名
# 3. 使用正确的列名重新查询
更可靠的解决方案是增加专门的数据预览工具:
python复制def view_csv_data(path):
df = pd.read_csv(path)
return {
"head": df.head().to_string(),
"tail": df.tail().to_string(),
"shape": str(df.shape)
}
tools.append({
"name": "view_csv_data",
"description": "查看CSV文件的结构",
"parameters": {"path": {"type": "string"}}
})
使用效果:
python复制preamble = """始终先查看数据再编写代码。"""
output = cohere_agent(question, preamble, tools)
# 执行流程:
# 1. 调用view_csv_data查看数据结构
# 2. 确认列名后编写正确查询
# 3. 一次执行成功
python复制question = "请计算所有数值列的平均值并解释其含义"
output = cohere_agent(question, preamble, tools)
# 输出示例:
"""
Revenue平均:1580亿美元
GrossProfit平均:610亿美元
OperatingIncome平均:480亿美元
这些指标反映了公司常态化的经营水平...
"""
python复制question = "评估这份数据是否适合分析?"
output = cohere_agent(question, preamble, tools)
# 输出包含:
# - 缺失值情况分析
# - 数据一致性检查
# - 时间跨度是否足够
python复制question = "基于此数据可以提出哪些分析问题?"
output = cohere_agent(question, preamble, tools)
# 建议的问题包括:
# - 季度收入增长趋势
# - 各项成本占比变化
# - 利润率与行业对比
经过这个深度实验,我认为AI代理在财务分析领域已经展现出实用价值,特别是对于需要反复查询多张报表的场景。虽然当前系统还有改进空间,但已经能够将常规分析任务的效率提升3-5倍。