Last active
June 16, 2023 10:03
-
-
Save arekt/3ddb990dc825409561e98fb707a91acb to your computer and use it in GitHub Desktop.
Example how to use function call in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# gem "ruby-openai", "~> 4.1" | |
# https://openai.com/blog/function-calling-and-other-api-updates | |
require 'openai' | |
require 'json' | |
require 'dotenv' | |
Dotenv.load("../.env") | |
ACCESS_TOKEN = ENV["OPENAI_API_KEY"] | |
MODEL_NAME = "gpt-3.5-turbo-0613" | |
def get_current_weather(location, unit = "fahrenheit") | |
# Get the current weather in a given location | |
if unit == nil || unit == "" | |
unit = "fahrenheit" | |
end | |
weather_info = { | |
"location" => location, | |
"temperature" => unit == "fahrenheit" ? 72 : 22, | |
"unit" => unit, | |
"forecast" => ["sunny", "windy"] | |
} | |
puts "GETTING: #{weather_info}" | |
return weather_info.to_json | |
end | |
def query(content) | |
client = OpenAI::Client.new(access_token: ACCESS_TOKEN) | |
response = client.chat(parameters: { | |
model: MODEL_NAME, | |
messages: [{ role: 'user', content: content }], | |
functions: [{ | |
name: 'get_current_weather', | |
description: 'Get the current weather in a given location', | |
parameters: { | |
type: 'object', | |
properties: { | |
location: { | |
type: 'string', | |
description: 'The city and state, e.g. San Francisco, CA' | |
}, | |
unit: { type: 'string', enum: %w[celsius fahrenheit] } | |
}, | |
required: ['location'] | |
} | |
}], | |
function_call: 'auto' | |
}) | |
message = response.dig("choices", 0, "message") | |
if message.key?("function_call") | |
function_name = message["function_call"]["name"] | |
function_args = JSON.parse(message["function_call"]["arguments"]) | |
location = function_args["location"] | |
unit = function_args["unit"] | |
function_response = get_current_weather(location, unit) | |
second_response = client.chat( | |
parameters: { | |
model: MODEL_NAME, | |
messages: [ | |
{ role: "user", content: content }, | |
message, # { role: "function_call", name: function_name, arguments: function_args} | |
{ role: "function", name: function_name, content: function_response } | |
] | |
} | |
) | |
# puts second_response | |
second_response.dig("choices", 0, "message", "content") | |
end | |
end | |
puts query("What's the weather like in Boston?") | |
puts query("What's the weather like in Warsaw? (celsius)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment