Skip to main content

使用OpenAI Functions Agent的自定义函数

本笔记本介绍了如何将自定义函数与OpenAI Functions agent集成。

安装运行此示例笔记本所需的库

pip install -q openai langchain yfinance

定义自定义函数

import yfinance as yf
from datetime import datetime, timedelta


def get_current_stock_price(ticker):
"""获取当前股票价格的方法"""

ticker_data = yf.Ticker(ticker)
recent = ticker_data.history(period="1d")
return {"price": recent.iloc[0]["Close"], "currency": ticker_data.info["currency"]}


def get_stock_performance(ticker, days):
"""获取股票价格变化百分比的方法"""

past_date = datetime.today() - timedelta(days=days)
ticker_data = yf.Ticker(ticker)
history = ticker_data.history(start=past_date)
old_price = history.iloc[0]["Close"]
current_price = history.iloc[-1]["Close"]
return {"percent_change": ((current_price - old_price) / old_price) * 100}

创建自定义工具

from typing import Type
from pydantic import BaseModel, Field
from langchain.tools import BaseTool


class CurrentStockPriceInput(BaseModel):
"""get_current_stock_price的输入"""

ticker: str = Field(description="股票的代码")


class CurrentStockPriceTool(BaseTool):
name = "get_current_stock_price"
description = """
当您想要获取当前股票价格时有用。
您应该输入由Yahoo Finance识别的股票代码。
"""
args_schema: Type[BaseModel] = CurrentStockPriceInput

def _run(self, ticker: str):
price_response = get_current_stock_price(ticker)
return price_response

def _arun(self, ticker: str):
raise NotImplementedError("get_current_stock_price不支持异步")


class StockPercentChangeInput(BaseModel):
"""get_stock_performance的输入"""

ticker: str = Field(description="股票的代码")
days: int = Field(description="从当前日期开始计算过去日期的天数")


class StockPerformanceTool(BaseTool):
name = "get_stock_performance"
description = """
当您想要检查股票的表现时有用。
您应该输入由Yahoo Finance识别的股票代码。
您应该输入从今天开始计算的天数,以检查表现。
输出将以百分比表示股票价格的变化。
"""
args_schema: Type[BaseModel] = StockPercentChangeInput

def _run(self, ticker: str, days: int):
response = get_stock_performance(ticker, days)
return response

def _arun(self, ticker: str):
raise NotImplementedError("get_stock_performance不支持异步")

API参考:

创建Agent

from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI
from langchain.agents import initialize_agent

llm = ChatOpenAI(model="gpt-3.5-turbo-0613", temperature=0)

tools = [CurrentStockPriceTool(), StockPerformanceTool()]

agent = initialize_agent(tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True)

API参考:

agent.run(
"微软股票的当前价格是多少?过去6个月的表现如何?"
)
agent.run("给我谷歌和Meta的最近股票价格。")
agent.run(
"在过去的3个月中,微软和谷歌之间哪只股票表现最好?"
)