@@ -402,7 +402,8 @@ You can describe and pass in functions and the model will intelligently choose t
402402``` ruby
403403
404404def get_current_weather (location: , unit: " fahrenheit" )
405- # use a weather api to fetch weather
405+ # Here you could use a weather api to fetch the weather.
406+ " The weather in #{ location } is nice 🌞 #{ unit } "
406407end
407408
408409messages = [
@@ -448,7 +449,7 @@ response =
448449message = response.dig(" choices" , 0 , " message" )
449450
450451if message[" role" ] == " assistant" && message[" tool_calls" ]
451- messages [" tool_calls" ].each do |tool_calls |
452+ message [" tool_calls" ].each do |tool_call |
452453 tool_call_id = tool_call.dig(" id" )
453454 function_name = tool_call.dig(" function" , " name" )
454455 function_args = JSON .parse(
@@ -457,17 +458,20 @@ if message["role"] == "assistant" && message["tool_calls"]
457458 )
458459 function_response = case function_name
459460 when " get_current_weather"
460- get_current_weather(** args ) # => "The weather is nice 🌞"
461+ get_current_weather(** function_args ) # => "The weather is nice 🌞"
461462 else
462463 # decide how to handle
463464 end
464465
465- messages << [{
466+ # For a subsequent message with the role "tool", OpenAI requires the preceding message to have a tool_calls argument.
467+ messages << message
468+
469+ messages << {
466470 tool_call_id: tool_call_id,
467471 role: " tool" ,
468472 name: function_name,
469473 content: function_response
470- }] # Extend the conversation with the results of the functions
474+ } # Extend the conversation with the results of the functions
471475 end
472476
473477 second_response = client.chat(
@@ -476,9 +480,12 @@ if message["role"] == "assistant" && message["tool_calls"]
476480 messages: messages
477481 })
478482
483+ puts second_response.dig(" choices" , 0 , " message" , " content" )
484+
479485 # At this point, the model has decided to call functions, you've called the functions
480486 # and provided the response back, and the model has considered this and responded.
481487end
488+ # => "It looks like the weather is nice and sunny in San Francisco! If you're planning to go out, it should be a pleasant day."
482489```
483490
484491### Completions
0 commit comments