实战案例
你是一位金融分析师,日常工作中需要频繁获取股票信息并进行简单的数据处理 。比如,你需要了解英伟达(NVIDIA)的当前股价,并且可能还需要基于这个股价进行一些简单的数学运算,如计算购买一定数量股票所需的资金,或者根据股价涨幅计算投资收益等。传统方式下,你可能需要手动打开金融数据网站,查找英伟达的股价,然后再使用计算器进行数学运算,过程繁琐且容易出错。
本案例中,我们借助 Llama Index 构建了一个智能工作流系统,它能够直接响应用户的自然语言查询,比如 "Nvidia目前的股票价格是多少?",并快速准确地返回英伟达的当前股价。不仅如此,该系统还可以进行基本的数学运算功能,如加法和乘法,这意味着你可以进一步询问它 "如果我要买 100 股 NVIDIA 股票,需要多少钱?" 之类的问题,系统会利用获取到的股价和乘法运算功能,快速给出答案。
我们需要使用Llama Index来构建一个Agent,同时它能够调用工具来实现查询股价和进行简单数学计算的功能。
关键知识点讲解
-
环境变量加载:本例中会使用到加载环境变量,这在使用需要密钥的服务(如 OpenAI API)时非常重要,能将敏感信息(如 API 密钥)存储在环境变量中,而不是直接写在代码里,提高代码安全性。
-
语言模型初始化:在Llama Index中我们可以选择不同的大语言模型,无论是在线API的还是本地部署的,我们将学习如何配置和使用默认的OpenAI模型 。
-
工具定义与使用 我们会在本例中使用到两种工具:自定义的函数和现成的YahooFiance工具。
- 自定义函数:multiply 和 add 是自定义的数学运算函数,用于乘法和加法运算,这展示了如何将自定义函数集成到 Llama Index 工作流中,拓展系统功能。
- YahooFinanceToolSpec 工具:from llama_index.tools.yahoo_finance import YahooFinanceToolSpec 导入雅虎财经工具规范,YahooFinanceToolSpec().to_tool_list() 将其转换为工具列表,用于获取金融数据,如股票价格。通过将这些工具和自定义函数组合,系统能完成复杂任务,如获取股价并进行数学运算。
-
AgentWorkflow 工作流 在 Llama Index 中,Agent 是一个智能体,它能够利用 Llama Index 提供的工具和知识图谱,自主地进行推理、决策和任务执行。Agent 可以理解用户的自然语言查询,然后根据预定义的策略和可用的资源,选择合适的工具和数据来生成回答。它结合了语言模型的自然语言处理能力和索引结构的高效信息检索能力,从而实现更复杂的问答和任务解决。例如,在处理复杂的问题时,Agent 可以动态地决定是从知识图谱中检索信息,还是调用外部 API 获取数据,然后综合这些信息给出全面准确的答案,为用户提供更加智能和灵活的交互体验。这里我们将讨论如何使用AgentWorkflow 类来构建workfow,它是 Llama Index 中构建智能工作流的核心组件。
-
异步执行:程序中还应该使用异步编程来提高程序执行效率,尤其在处理 I/O 操作(如获取金融数据)时,避免线程阻塞 。
完整代码
根据本案例的需求,我们的完整代码如下:
python
from dotenv import load_dotenv
load_dotenv()
from llama_index.llms.openai import OpenAI
from llama_index.core.agent.workflow import AgentWorkflow
from llama_index.tools.yahoo_finance import YahooFinanceToolSpec
def multiply(a: float, b: float) -> float:
"""Multiply two numbers and returns the product"""
return a * b
def add(a: float, b: float) -> float:
"""Add two numbers and returns the sum"""
return a + b
llm = OpenAI(model="gpt-4o-mini")
finance_tools = YahooFinanceToolSpec().to_tool_list()
finance_tools.extend([multiply, add])
workflow = AgentWorkflow.from_tools_or_functions(
finance_tools,
llm=llm,
system_prompt="You are an agent that can perform basic mathematical operations using tools."
)
async def main():
response = await workflow.run(user_msg="What's the current stock price of NVIDIA?")
print(response)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
代码逐行解析
接下来,我们对案例代码进行逐行解析,进一步掌握 Llama Index Agent的构建与使用方式。
定义数学运算函数
python
def multiply(a: float, b: float) -> float:
"""Multiply two numbers and returns the product"""
return a * b
def add(a: float, b: float) -> float:
"""Add two numbers and returns the sum"""
return a + b
上述代码定义了两个简单的数学运算函数:multiply 和 add 。multiply 函数接受两个浮点数参数 a 和 b ,将它们相乘并返回结果;add 函数同理,接受两个浮点数参数并返回它们的和。这些函数在后续被集成到智能代理的工具列表中,使智能代理能够执行基本数学运算,满足用户在处理金融数据时可能的计算需求,如计算购买股票的总金额。
初始化大模型与工具
ini
from llama_index.llms.openai import OpenAI
from llama_index.tools.yahoo_finance import YahooFinanceToolSpec
llm = OpenAI(model="gpt-4o-mini")
finance_tools = YahooFinanceToolSpec().to_tool_list()
finance_tools.extend([multiply, add])
首先,从 llama_index.llms.openai 导入 OpenAI 类,从 llama_index.tools.yahoo_finance 导入 YahooFinanceToolSpec 类。然后,使用 OpenAI 类初始化语言模型,指定模型为 gpt-4o-mini ,该模型将负责理解用户输入和生成回复。接着,通过 YahooFinanceToolSpec().to_tool_list() 获取雅虎财经工具列表,这个列表包含了与金融数据获取相关的工具,如获取股票价格、公司财务报表等信息的功能。最后,将之前定义的 multiply 和 add 函数添加到金融工具列表中,扩展了智能代理可使用的工具范围,使其既能获取金融数据,又能进行基本数学运算。
创建智能工作流
ini
from llama_index.core.agent.workflow import AgentWorkflow
workflow = AgentWorkflow.from_tools_or_functions(
finance_tools,
llm=llm,
system_prompt="You are an agent that can perform basic mathematical operations using tools."
)
从 llama_index.core.agent.workflow 导入 AgentWorkflow 类,这是创建智能工作流的核心类。使用 AgentWorkflow.from_tools_or_functions 方法创建一个智能工作流实例。该方法接受三个主要参数:finance_tools 是前面准备好的包含金融工具和数学运算函数的工具列表;llm 是初始化好的语言模型;system_prompt 是一个系统提示,它设定了智能代理的角色和任务,这里表明智能代理可以使用工具执行基本数学运算,为智能代理的行为提供指导。
运行与测试
css
import asyncio
async def main():
response = await workflow.run(user_msg="What's the current stock price of NVIDIA?")
print(response)
if __name__ == "__main__":
asyncio.run(main())
定义一个异步函数 main ,在这个函数中,使用 await workflow.run(user_msg="What's the current stock price of NVIDIA?") 来运行智能工作流,向智能代理发送用户问题 "What's the current stock price of NVIDIA?" ,智能代理会利用工具和语言模型处理这个问题并返回响应。await 关键字用于等待异步操作完成,确保在获取到响应后继续执行后续代码。然后,使用 print(response) 打印智能代理返回的响应,即英伟达当前股价。最后,通过 if name == "main": 条件判断,在脚本直接运行时,使用 asyncio.run(main()) 来启动异步事件循环,执行异步函数 main ,完成整个智能代理的测试流程 。
发散练习
在本案例基础上,为了进一步加深对 Llama Index 的理解和应用,我们这里给出一个发散练习。假设你不仅需要获取股票价格,还想获取某公司的市值和市盈率数据,并计算如果以当前股价购买一定数量股票,占该公司总市值的百分比 。请在现有代码基础上进行修改,实现这一功能。
解题思路
-
首先,需要扩展雅虎财经工具的功能,使其能够获取市值和市盈率数据。
-
然后,定义新的函数用于计算购买股票占总市值的百分比。
-
最后,将新的工具和函数集成到 AgentWorkflow 中,并修改用户问题和系统提示,以适应新的功能需求。
参考代码
python
from dotenv import load_dotenv
import asyncio
load_dotenv()
from llama_index.llms.openai import OpenAI
from llama_index.core.agent.workflow import AgentWorkflow
from llama_index.tools.yahoo_finance import YahooFinanceToolSpec
def multiply(a: float, b: float) -> float:
"""Multiply two numbers and returns the product"""
return a * b
def add(a: float, b: float) -> float:
"""Add two numbers and returns the sum"""
return a + b
# 新增函数:获取市值
def get_market_cap(ticker: str) -> float:
from yfinance import Ticker
ticker_info = Ticker(ticker).info
return ticker_info.get('marketCap', 0)
# 新增函数:获取市盈率
def get_pe_ratio(ticker: str) -> float:
from yfinance import Ticker
ticker_info = Ticker(ticker).info
return ticker_info.get('trailingPE', 0)
# 新增函数:计算购买股票占总市值的百分比
def calculate_percentage_of_market_cap(ticker: str, num_shares: float) -> float:
market_cap = get_market_cap(ticker)
current_price = get_stock_price(ticker)
investment = multiply(current_price, num_shares)
return multiply(100, divide(investment, market_cap))
def divide(a: float, b: float) -> float:
"""Divide two numbers and returns the quotient"""
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
llm = OpenAI(model="gpt-4o-mini")
finance_tools = YahooFinanceToolSpec().to_tool_list()
# 获取股票价格函数,假设已有
def get_stock_price(ticker: str) -> float:
from yfinance import Ticker
return Ticker(ticker).info.get('currentPrice', 0)
finance_tools.extend([multiply, add, get_market_cap, get_pe_ratio, calculate_percentage_of_market_cap, divide, get_stock_price])
workflow = AgentWorkflow.from_tools_or_functions(
finance_tools,
llm=llm,
system_prompt="You are an agent that can perform financial data retrieval and calculations using tools."
)
async def main():
response = await workflow.run(user_msg="What's the market cap, PE ratio and if I buy 100 shares of NVIDIA, what percentage of the market cap does it represent?")
print(response)
if __name__ == "__main__":
asyncio.run(main())
在上述代码中:
-
定义了 get_market_cap 和 get_pe_ratio 函数,分别用于获取公司市值和市盈率 。
-
calculate_percentage_of_market_cap 函数用于计算购买一定数量股票占总市值的百分比,它调用了 get_market_cap、get_stock_price(假设已有获取股价函数)以及之前定义的 multiply 和新定义的 divide 函数。
-
将这些新函数添加到 finance_tools 工具列表中,并修改 system_prompt 以准确描述代理的功能 。
-
在 main 函数中修改用户问题,以测试新功能 。
案例总结
在本次 Llama Index 案例教学中,我们围绕金融数据处理场景,构建了一个强大的智能工作流系统。通过加载环境变量保障安全,初始化 OpenAI 语言模型提供智能交互能力,结合雅虎财经工具和自定义数学运算函数,创建了能够理解自然语言、获取股票价格并进行数学计算的智能代理 。
在代码解析过程中,我们详细了解了每个部分的功能和作用,从函数定义到工具集成,再到工作流创建与运行,每一步都为实现高效金融数据分析奠定基础。此外,通过发散练习,进一步拓展了智能代理的功能,使其能够获取更多金融数据并进行复杂计算 。
希望通过本案例教学,你能对 Llama Index如何构建AgentWorkflow有一个初步的认识。 关注本系列教程的下一篇文章,我们将继续深入探索 Llama Index 的更多高级应用。