Quick Outline
This post will demonstrate the following:
- How to Create Custom Functions with OpenAI Agent in LangChain
- Installing Frameworks
- Setting OpenAI Environment
- Creating a Custom Function
- Testing the Custom Function
- Configuring Custom Tools
- Creating the Agent
- Testing the Agent
- Conclusion
How to Create Custom Functions with OpenAI Agent in LangChain?
Agents are an important aspect of the language model as they contain all the information about how the model works. It contains all the activities or steps to build the conversation application. The agents also have an understanding of when each process will be executed. To learn the process of creating a custom function with an OpenAI agent in LangChain, simply follow this guide:
Step 1: Installing Frameworks
First of all, install the OpenAI agent i.e. “yfinance” (Yahoo finance) contains an amazing range of stocks, bonds, market data, etc. LangChain is the major framework for this process that contains the OpenAI and finance libraries in its dependencies:
After that, simply install the OpenAI module to build the language model and OpenAI agent:
Step 2: Setting OpenAI Environment
The next step is about setting up the OpenAI environment using its API key from the OpenAI account:
import getpass
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
Step 3: Creating a Custom Function
Importing the “yfinance” library is required to build the customized function to get the current stock prices using the “datetime” library:
from datetime import datetime, timedelta
def get_current_stock_price(ticker):
"""It is the method for getting the current stock price"""
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):
"""It is the method for getting the change in stock price"""
past_date = datetime.today() - timedelta(days=days)
#Ticker is the name of the company to get the price of its stocks
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}
- “Yfinance” is the library that has huge data about the market rate, currency, stock information
- “Datetime” is the library to get the time-stamped data like the current stock prices or opening or closing market rate on a particular day
- “get_current_stock_price()” method is configured to get the price of the stock using the ticker. It returns the closing price and the currency of the stock
- The “get_stock_performance()” method is defined to calculate the percentage change in the price of the stock and currency. The ticker symbol is used to understand the timestamp for the change in the price to return the percentage change:
Step 4: Testing the Custom Function
Test the custom function by calling the “get_current_stock_price()” method with the MSFT stock price. The “MSFT” is the Microsoft Corporation stocks and calling this function returns the price of stocks at the closing time:
Call the “get_stock_performance()” with the Microsoft Corporation stocks and the number of days in the argument. Running this method returns the percentage change in the last 30 days in the Microsoft stocks price:
Step 5: Configuring Custom Tools
To build the OpenAI agent, it is required to build the tools for using the agents with all the activities to complete the process:
from pydantic import BaseModel, Field
from langchain.tools import BaseTool
class CurrentStockPriceInput(BaseModel):
#getting the input for using the stock price values
ticker: str = Field(description="Ticker symbol of the stock")
class CurrentStockPriceTool(BaseTool):
name = "get_current_stock_price"
description = """
enter the stock ticker symbol to get the current stock price that can be recognized by 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 does not support async")
class StockPercentChangeInput(BaseModel):
#getting the input for using the stock performance
ticker: str = Field(description="Ticker symbol of the stock")
days: int = Field(description="Timedelta days to get past date from current date")
class StockPerformanceTool(BaseTool):
name = "get_stock_performance"
description = """
enter days as the number of days from today from which performance needs to be checked output will be the change in the stock price and enter the stock ticker symbol to get the performance of the stock
"""
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 does not support async")
The code suggests:
- The CurrentStockPriceInput() method is used to get the current price of the stocks at the end
- The CurrentStockPriceTool() method returns the value of the stock using the ticker name included in the Yahoo finance library.
- Also, configure two methods which are “StockPercentChangeInput()” and “StockPerformanceTool()” to get the percentage change of the stocks:
Step 6: Creating the Agent
Once the tools are configured, simply build the agent using the OPENAI_FUNCTIONS type after configuring the llm using the ChatOpenAI() method:
from langchain.agents import initialize_agent
from langchain.chat_models import ChatOpenAI
llm = ChatOpenAI(model="gpt-3.5-turbo-0613", temperature=0)
tools = [CurrentStockPriceTool(), StockPerformanceTool()]
agent = initialize_agent(tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True)
Step 7: Testing the Agent
Finally, test the agent by calling the run() method with the input question in its argument:
"What is the current price of Microsoft stock and how has it performed over the past 6 months"
)
The agent has extracted the current value of Microsoft stock and also the performance of its stock in the last six months to get the percentage change:
Ask for other ticker names like Google and Meta stocks as we have extracted the Microsoft stocks in the previous question:
That’s all about the process of creating custom functions with the OpenAI agent in LangChain.
Conclusion
To learn the process of creating a custom function with an OpenAI agent in LangChain, install the required modules like Yahoo Finance (yfinance). Set up the environment using the OpenAI API from its account to build the custom functions to get the stock prices and the percentage change. Build the tools for the agents to perform the required activities and use the OPENAI_FUNCTIONS as the type of agent. Ultimately, simply test the agent by calling the run() method with inputs as its argument.