@@ -421,7 +421,7 @@ response =
421421 function: {
422422 name: " get_current_weather" ,
423423 description: " Get the current weather in a given location" ,
424- parameters: {
424+ parameters: { # Format: https://json-schema.org/understanding-json-schema
425425 type: :object ,
426426 properties: {
427427 location: {
@@ -438,31 +438,46 @@ response =
438438 },
439439 }
440440 ],
441- tool_choice: {
442- type: " function" ,
443- function: {
444- name: " get_current_weather"
445- }
446- }
441+ tool_choice: " required" # Optional, defaults to "auto"
442+ # Can also put "none" or specific functions, see docs
447443 },
448444 )
449445
450446message = response.dig(" choices" , 0 , " message" )
447+ function_messages = []
451448
452449if message[" role" ] == " assistant" && message[" tool_calls" ]
453- function_name = message.dig(" tool_calls" , 0 , " function" , " name" )
454- args =
455- JSON .parse(
456- message.dig(" tool_calls" , 0 , " function" , " arguments" ),
450+ messages[" tool_calls" ].each do |tool_calls |
451+ tool_call_id = tool_call.dig(" id" )
452+ function_name = tool_call.dig(" function" , " name" )
453+ function_args = JSON .parse(
454+ tool_call.dig(" function" , " arguments" ),
457455 { symbolize_names: true },
458456 )
457+ function_response = case function_name
458+ when " get_current_weather"
459+ get_current_weather(** args) # => "The weather is nice 🌞"
460+ else
461+ # decide how to handle
462+ end
459463
460- case function_name
461- when " get_current_weather"
462- get_current_weather(** args)
464+ function_messages << [{
465+ tool_call_id: tool_call_id,
466+ role: " tool" ,
467+ name: function_name,
468+ content: function_response
469+ }]
463470 end
471+
472+ second_response = client.chat(
473+ parameters: {
474+ model: " gpt-4o" ,
475+ messages: function_messages
476+ })
477+
478+ # At this point, the model has decided to call functions, you've called the functions
479+ # and provided the response back, and the model has considered this and responded.
464480end
465- # => "The weather is nice 🌞"
466481```
467482
468483### Completions
0 commit comments