Skip to content

Commit b01ca38

Browse files
committed
Add functions example
1 parent 3a33b24 commit b01ca38

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

README.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,65 @@ client.chat(
149149
# => "Anna is a young woman in her mid-twenties, with wavy chestnut hair that falls to her shoulders..."
150150
```
151151

152+
### Function Calling
153+
154+
Developers can describe functions and have the model intelligently choose to output a JSON object containing arguments to call those functions.
155+
156+
```ruby
157+
def get_current_weather(location:, unit: "fahrenheit")
158+
# use a weather api to fetch weather
159+
end
160+
161+
response =
162+
client.chat(
163+
parameters: {
164+
model: "gpt-3.5-turbo-0613",
165+
messages: [
166+
{
167+
"role": "user",
168+
"content": "What is the weather like in San Francisco?",
169+
},
170+
],
171+
functions: [
172+
{
173+
name: "get_current_weather",
174+
description: "Get the current weather in a given location",
175+
parameters: {
176+
type: :object,
177+
properties: {
178+
location: {
179+
type: :string,
180+
description: "The city and state, e.g. San Francisco, CA",
181+
},
182+
unit: {
183+
type: "string",
184+
enum: %w[celsius fahrenheit],
185+
},
186+
},
187+
required: ["location"],
188+
},
189+
},
190+
],
191+
},
192+
)
193+
194+
message = response.dig("choices", 0, "message")
195+
196+
if message["role"] == "assistant" && message["function_call"]
197+
function_name = message.dig("function_call", "name")
198+
args =
199+
JSON.parse(
200+
message.dig("function_call", "arguments"),
201+
{ symbolize_names: true },
202+
)
203+
204+
case function_name
205+
when "get_current_weather"
206+
get_current_weather(**args)
207+
end
208+
end
209+
```
210+
152211
### Completions
153212

154213
Hit the OpenAI API for a completion using other GPT-3 models:

0 commit comments

Comments
 (0)