[ad_1]
Calling an OpenAI function
OpenAI recently released a new feature called “Function Calling” that allows developers to create more interactive and dynamic applications. With the function call feature, developers can describe functions on an OpenAI model, and the model will output a JSON object containing the arguments to call those functions. Function calls allow developers to return structured data from a model. Some common use cases for the “function call” feature are:
- To call external APIs.
- Converting natural language queries into API calls or database calls
- Extract structured data from text
In this blog post, we’ll create a small application that uses OpenAI’s function call function to call external APIs. This API provides the current stock price of a company listed in the United States and the current exchange rate between the two countries.
To get the current share price of a US-listed company, we use Finnhub. Finnhub offers a free API key that can be obtained by following these steps:
It will provide you with an API key that we will use to retrieve stock prices.
We will use Alphavantage to get the current exchange rate between the two countries. Alpha Vantage also offers a free API key that can be obtained by following these steps:
It will provide you with an API key that we will use to retrieve currency exchange rates between the 2 countries.
Now that we have the Finnhub and Alpha Vantage API keys, we can start building the app. Below is a step-by-step guide you can follow to create an app:
Step 1:
To get started, you need to install two packages, openai and finnhub-python, using the following commands:
pip install openai
pip install finnhub-python
After the installation is complete, you can import the necessary libraries into your code with the following lines:
import json
import requests
import finnhub
Step 2:
First, we’re building a utility that makes it easy to make requests to the Chat Completions API. The utility function takes four parameters: messages, functions, function_call, and model. The purpose of each parameter is as follows:
Notifications: It requires a request that will be used when making a ChatGPT API call.
Functions: It will get a specification list of available functions that can be called by ChatGPT.
function_call: This parameter allows us to provide either the name of a specific function or set as “none”. When a function name is specified, the API will be directed to call that particular function. If we want to force the OpenAI model not to use any function, then we should cast this argument as None.
model: t will take the name of the model we want to use, here we use the model “gpt-3.5-turbo-0613”. You can also use “gpt-4-0613”.
This function will call the OpenAI Chat Completion endpoint with the appropriate parameters and return a response.
GPT_MODEL = "gpt-3.5-turbo-0613"
def chat_completion_request(messages, functions=None, function_call=None, model=GPT_MODEL):
headers =
"Content-Type": "application/json",
"Authorization": "Bearer " + "<your_openai_key>",
json_data = "model": model, "messages": messages
if functions is not None:
json_data.update("functions": functions)
if function_call is not None:
json_data.update("function_call": function_call)
try:
response = requests.post(
"https://api.openai.com/v1/chat/completions",
headers=headers,
json=json_data,
)
return response
except Exception as e:
print("Unable to generate ChatCompletion response")
print(f"Exception: e")
return e
Step 3:
Next, we’ll develop a function to call the Finnhub API to get the current stock price of a US-listed company. First, you need to create a finnhub client by going through your finnhub API. Then we can write our function as follows:
finnhub_client = finnhub.Client(api_key="<Your_finnhub_API_key>")
def get_current_stock_price(arguments):
try:
arguments = json.loads(arguments)['ticker_symbol']
price_data=finnhub_client.quote(arguments)
stock_price = price_data.get('c', None)
if stock_price == 0:
return "This company is not listed within USA, please provide another name."
else:
return stock_price
except:
return "This company is not listed within USA, please provide another name."
Step 4:
Next, we’ll create a function that will call the Alpha Vantage API to find the exchange rate between two countries. To implement the function, you need to add the below lines of code.
def currency_exchange_rate(arguments):
try:
from_country_currency = json.loads(arguments)['from_country_currency']
to_country_currency = json.loads(arguments)['to_country_currency']
url = f'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=from_country_currency&to_currency=to_country_currency&apikey='<your_Alphavantage_api_key>''
r = requests.get(url)
data = r.json()
return data['Realtime Currency Exchange Rate']['5. Exchange Rate']
except:
return "I am unable to parse this, please try something new."
Step 5:
Now we need to create function specifications to interact with the Finnhub API and the Alpha Vantage API. We pass these function specifications to the Chat Completions API to generate function arguments that match the specification. In this function specification, you must specify the name and description of the function and its parameters. You can describe the functional specification as follows:
functions = [
"name": "get_current_stock_price",
"description": "It will get the current stock price of the US company.",
"parameters":
"type": "object",
"properties":
"ticker_symbol":
"type": "string",
"description": "This is the symbol of the company.",
,
"required": ["ticker_symbol"],
,
,
"name": "currency_exchange_rate",
"description": "It will get the currency exchange rate between 2 countries.",
"parameters":
"type": "object",
"properties":
"from_country_currency":
"type": "string",
"description": "This is the currency of the country whose we need to map.",
,
"to_country_currency":
"type": "string",
"description": "This is the currency of the country to which we need to map.",
,
"required": ["from_country_currency","to_country_currency"],
,
]
Step 6:
Now we can use OpenAI’s function calling capability. We need to call the chat completion API with prompt and function specifications. It will call ChatGPT and generate JSON that we can use to call the function in our code. You can use the code below to generate the JSON that will later be used to call the local function.
user_input = input("Please enter your question here: ")
# prompt
messages = ["role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."]
messages.append("role": "user", "content": user_input)
# calling chat_completion_request to call ChatGPT completion endpoint
chat_response = chat_completion_request(
messages, functions=functions
)
# fetch response of ChatGPT and call the function
assistant_message = chat_response.json()["choices"][0]["message"]
print(assistant_message)
Output:
We asked, “What is Apple’s stock price?”, ChatGPT recognized that you need to call the ‘get_current_stock_price’ function with the ‘AAPL’ parameter to access the Finnhub API. So it generated a JSON response containing the function name and the corresponding parameter needed to execute the local function.
Please enter your question here: What is the stock price of Apple?
'role': 'assistant', 'content': None, 'function_call': 'name': 'get_current_stock_price', 'arguments': '\n "ticker_symbol": "AAPL"\n'
Step 7:
Now we can call the local function ‘get_current_stock_price’ using the JSON generated by ChatGPT as below:
if assistant_message['content']:
print("Response is: ", assistant_message['content'])
else:
fn_name = assistant_message["function_call"]["name"]
arguments = assistant_message["function_call"]["arguments"]
function = locals()[fn_name]
result = function(arguments)
print("Response is: ", result)
Output:
Please enter your question here: What is the stock price of Apple?
'role': 'assistant', 'content': None, 'function_call': 'name': 'get_current_stock_price', 'arguments': '\n "ticker_symbol": "AAPL"\n'
Response is: 184.92
Step 8:
Now, we can combine the above 2 steps to generate JSON using ChatGPT and call a local function using the generated JSON and put them in a loop as below:
user_input = input("Please enter your question here: (if you want to exit then write 'exit' or 'bye'.) ")
while user_input.strip().lower() != "exit" and user_input.strip().lower() != "bye":
# prompt
messages = ["role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."]
messages.append("role": "user", "content": user_input)
# calling chat_completion_request to call ChatGPT completion endpoint
chat_response = chat_completion_request(
messages, functions=functions
)
# fetch response of ChatGPT and call the function
assistant_message = chat_response.json()["choices"][0]["message"]
if assistant_message['content']:
print("Response is: ", assistant_message['content'])
else:
fn_name = assistant_message["function_call"]["name"]
arguments = assistant_message["function_call"]["arguments"]
function = locals()[fn_name]
result = function(arguments)
print("Response is: ", result)
user_input = input("Please enter your question here: ")
results:
Please enter your question here: (if you want to exit then write 'exit' or 'bye'.) 1 dollar is equal to what rs?
Response is: 81.94000000
Please enter your question here: What is the current stock price of Amazon?
Response is: 125.4902
Please enter your question here: Currency exchange rate between india and canada?
Response is: 0.01606000
Please enter your question here: Stock price of Tesla?
Response is: 260.54
You can also use the collab below to run the above code.
https://colab.research.google.com/drive/1Ki1gDUfF8bWw8Z-pr0IDHtLrGXM2G7NL?usp=sharing
[ad_2]
Source link