Examples and guides for using the OpenAI API
[How to call function with chat model] Pretty printing applied + gpt-4o instead of gpt-5 for one failing cell (#2105)
tgregoir-openaic2d225dd720d
diff --git a/examples/How_to_call_functions_with_chat_models.ipynb b/examples/How_to_call_functions_with_chat_models.ipynbindex 5732d5bf..af5cda94 100644--- a/examples/How_to_call_functions_with_chat_models.ipynb+++ b/examples/How_to_call_functions_with_chat_models.ipynb@@ -51,7 +51,7 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 2,"id": "dab872c5","metadata": {"ExecuteTime": {@@ -134,9 +134,9 @@" print(colored(f\"system: {message['content']}\\n\", role_to_color[message[\"role\"]]))\n"," elif message[\"role\"] == \"user\":\n"," print(colored(f\"user: {message['content']}\\n\", role_to_color[message[\"role\"]]))\n",- " elif message[\"role\"] == \"assistant\" and message.get(\"function_call\"):\n",- " print(colored(f\"assistant: {message['function_call']}\\n\", role_to_color[message[\"role\"]]))\n",- " elif message[\"role\"] == \"assistant\" and not message.get(\"function_call\"):\n",+ " elif message[\"role\"] == \"assistant\" and message.get(\"tool_calls\"):\n",+ " print(colored(f\"assistant: {message['tool_calls']}\\n\", role_to_color[message[\"role\"]]))\n",+ " elif message[\"role\"] == \"assistant\" and not message.get(\"tool_calls\"):\n"," print(colored(f\"assistant: {message['content']}\\n\", role_to_color[message[\"role\"]]))\n"," elif message[\"role\"] == \"function\":\n"," print(colored(f\"function ({message['name']}): {message['content']}\\n\", role_to_color[message[\"role\"]]))\n"@@ -181,7 +181,7 @@" \"format\": {\n"," \"type\": \"string\",\n"," \"enum\": [\"celsius\", \"fahrenheit\"],\n",- " \"description\": \"The temperature unit to use. Infer this from the users location.\",\n",+ " \"description\": \"The temperature unit to use. Infer this unit from the forecast location.\",\n"," },\n"," },\n"," \"required\": [\"location\", \"format\"],\n",@@ -203,7 +203,7 @@" \"format\": {\n"," \"type\": \"string\",\n"," \"enum\": [\"celsius\", \"fahrenheit\"],\n",- " \"description\": \"The temperature unit to use. Infer this from the users location.\",\n",+ " \"description\": \"The temperature unit to use. Infer this unit from the forecast location.\",\n"," },\n"," \"num_days\": {\n"," \"type\": \"integer\",\n",@@ -238,14 +238,16 @@},"outputs": [{- "data": {- "text/plain": [- "ChatCompletionMessage(content='Sure, can you please provide me with the name of your city and state?', role='assistant', function_call=None, tool_calls=None)"- ]- },- "execution_count": 60,- "metadata": {},- "output_type": "execute_result"+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[31msystem: Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\n",+ "\u001b[0m\n",+ "\u001b[32muser: What's the weather like today\n",+ "\u001b[0m\n",+ "\u001b[34massistant: Sure—what city and state (or country) should I check? Also, do you prefer Celsius or Fahrenheit?\n",+ "\u001b[0m\n"+ ]}],"source": [@@ -255,9 +257,8 @@"chat_response = chat_completion_request(\n"," messages, tools=tools\n",")\n",- "assistant_message = chat_response.choices[0].message\n",- "messages.append(assistant_message)\n",- "assistant_message\n"+ "messages.append(chat_response.choices[0].message.to_dict())\n",+ "pretty_print_conversation(messages)\n"]},{@@ -281,14 +282,20 @@},"outputs": [{- "data": {- "text/plain": [- "ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_xb7QwwNnx90LkmhtlW0YrgP2', function=Function(arguments='{\"location\":\"Glasgow, Scotland\",\"format\":\"celsius\"}', name='get_current_weather'), type='function')])"- ]- },- "execution_count": 61,- "metadata": {},- "output_type": "execute_result"+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[31msystem: Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\n",+ "\u001b[0m\n",+ "\u001b[32muser: What's the weather like today\n",+ "\u001b[0m\n",+ "\u001b[34massistant: Sure—what city and state (or country) should I check? Also, do you prefer Celsius or Fahrenheit?\n",+ "\u001b[0m\n",+ "\u001b[32muser: I'm in Glasgow, Scotland.\n",+ "\u001b[0m\n",+ "\u001b[34massistant: [{'id': 'call_k2QgGc9GT9WjxD76GvR0Ot8q', 'function': {'arguments': '{\"location\": \"Glasgow, Scotland\", \"format\": \"celsius\"}', 'name': 'get_current_weather'}, 'type': 'function'}, {'id': 'call_RtnXV5t49lqbWwhvGoEPZ7KY', 'function': {'arguments': '{\"location\": \"Glasgow, Scotland\", \"format\": \"celsius\", \"num_days\": 1}', 'name': 'get_n_day_weather_forecast'}, 'type': 'function'}]\n",+ "\u001b[0m\n"+ ]}],"source": [@@ -296,9 +303,8 @@"chat_response = chat_completion_request(\n"," messages, tools=tools\n",")\n",- "assistant_message = chat_response.choices[0].message\n",- "messages.append(assistant_message)\n",- "assistant_message\n"+ "messages.append(chat_response.choices[0].message.to_dict())\n",+ "pretty_print_conversation(messages)\n"]},{@@ -322,14 +328,16 @@},"outputs": [{- "data": {- "text/plain": [- "ChatCompletionMessage(content='To provide you with the weather forecast for Glasgow, Scotland, could you please specify the number of days you would like the forecast for?', role='assistant', function_call=None, tool_calls=None)"- ]- },- "execution_count": 62,- "metadata": {},- "output_type": "execute_result"+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[31msystem: Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\n",+ "\u001b[0m\n",+ "\u001b[32muser: what is the weather going to be like in Glasgow, Scotland over the next x days\n",+ "\u001b[0m\n",+ "\u001b[34massistant: How many days would you like the forecast for in Glasgow, Scotland? For example: 3, 5, 7, 10, or 14.\n",+ "\u001b[0m\n"+ ]}],"source": [@@ -339,9 +347,8 @@"chat_response = chat_completion_request(\n"," messages, tools=tools\n",")\n",- "assistant_message = chat_response.choices[0].message\n",- "messages.append(assistant_message)\n",- "assistant_message\n"+ "messages.append(chat_response.choices[0].message.to_dict())\n",+ "pretty_print_conversation(messages)\n"]},{@@ -365,14 +372,20 @@},"outputs": [{- "data": {- "text/plain": [- "Choice(finish_reason='tool_calls', index=0, logprobs=None, message=ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_34PBraFdNN6KR95uD5rHF8Aw', function=Function(arguments='{\"location\":\"Glasgow, Scotland\",\"format\":\"celsius\",\"num_days\":5}', name='get_n_day_weather_forecast'), type='function')]))"- ]- },- "execution_count": 63,- "metadata": {},- "output_type": "execute_result"+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[31msystem: Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\n",+ "\u001b[0m\n",+ "\u001b[32muser: what is the weather going to be like in Glasgow, Scotland over the next x days\n",+ "\u001b[0m\n",+ "\u001b[34massistant: How many days would you like the forecast for in Glasgow, Scotland? For example: 3, 5, 7, 10, or 14.\n",+ "\u001b[0m\n",+ "\u001b[32muser: 5 days\n",+ "\u001b[0m\n",+ "\u001b[34massistant: [{'id': 'call_lNzOVLrNSaSVjL3O3bN110af', 'function': {'arguments': '{\"location\":\"Glasgow, Scotland\",\"format\":\"celsius\",\"num_days\":5}', 'name': 'get_n_day_weather_forecast'}, 'type': 'function'}]\n",+ "\u001b[0m\n"+ ]}],"source": [@@ -380,7 +393,8 @@"chat_response = chat_completion_request(\n"," messages, tools=tools\n",")\n",- "chat_response.choices[0]\n"+ "messages.append(chat_response.choices[0].message.to_dict())\n",+ "pretty_print_conversation(messages)\n"]},{@@ -413,14 +427,16 @@},"outputs": [{- "data": {- "text/plain": [- "ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_FImGxrLowOAOszCaaQqQWmEN', function=Function(arguments='{\"location\":\"Toronto, Canada\",\"format\":\"celsius\",\"num_days\":7}', name='get_n_day_weather_forecast'), type='function')])"- ]- },- "execution_count": 64,- "metadata": {},- "output_type": "execute_result"+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[31msystem: Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\n",+ "\u001b[0m\n",+ "\u001b[32muser: Give me a weather report for Toronto, Canada.\n",+ "\u001b[0m\n",+ "\u001b[34massistant: [{'id': 'call_3hoMjl55OQ7LxfwhFyjxwv1T', 'function': {'arguments': '{\"location\":\"Toronto, Canada\",\"format\":\"celsius\",\"num_days\":5}', 'name': 'get_n_day_weather_forecast'}, 'type': 'function'}]\n",+ "\u001b[0m\n"+ ]}],"source": [@@ -431,7 +447,8 @@"chat_response = chat_completion_request(\n"," messages, tools=tools, tool_choice={\"type\": \"function\", \"function\": {\"name\": \"get_n_day_weather_forecast\"}}\n",")\n",- "chat_response.choices[0].message"+ "messages.append(chat_response.choices[0].message.to_dict())\n",+ "pretty_print_conversation(messages)"]},{@@ -446,14 +463,16 @@},"outputs": [{- "data": {- "text/plain": [- "ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_n84kYFqjNFDPNGDEnjnrd2KC', function=Function(arguments='{\"location\": \"Toronto, Canada\", \"format\": \"celsius\"}', name='get_current_weather'), type='function'), ChatCompletionMessageToolCall(id='call_AEs3AFhJc9pn42hWSbHTaIDh', function=Function(arguments='{\"location\": \"Toronto, Canada\", \"format\": \"celsius\", \"num_days\": 3}', name='get_n_day_weather_forecast'), type='function')])"- ]- },- "execution_count": 65,- "metadata": {},- "output_type": "execute_result"+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[31msystem: Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\n",+ "\u001b[0m\n",+ "\u001b[32muser: Give me a weather report for Toronto, Canada.\n",+ "\u001b[0m\n",+ "\u001b[34massistant: [{'id': 'call_wv5mdjEQJnBPuSci3xw09Tom', 'function': {'arguments': '{\"location\":\"Toronto, ON\",\"format\":\"celsius\"}', 'name': 'get_current_weather'}, 'type': 'function'}]\n",+ "\u001b[0m\n"+ ]}],"source": [@@ -464,7 +483,8 @@"chat_response = chat_completion_request(\n"," messages, tools=tools\n",")\n",- "chat_response.choices[0].message"+ "messages.append(chat_response.choices[0].message.to_dict())\n",+ "pretty_print_conversation(messages)"]},{@@ -488,14 +508,22 @@},"outputs": [{- "data": {- "text/plain": [- "ChatCompletionMessage(content=\"Sure, I'll get the current weather for Toronto, Canada in Celsius.\", role='assistant', function_call=None, tool_calls=None)"- ]- },- "execution_count": 66,- "metadata": {},- "output_type": "execute_result"+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\u001b[31msystem: Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\n",+ "\u001b[0m\n",+ "\u001b[32muser: Give me the current weather (use Celcius) for Toronto, Canada.\n",+ "\u001b[0m\n",+ "\u001b[34massistant: I don’t have live access to pull the current conditions right now. To get Toronto’s current weather in Celsius, check any of these quickly:\n",+ "- Environment Canada: weather.gc.ca (search “Toronto”)\n",+ "- The Weather Network: theweathernetwork.com/ca/weather/ontario/toronto\n",+ "- Google: search “Toronto weather” (shows °C by default in Canada)\n",+ "- AccuWeather or Weather.com (set units to °C)\n",+ "\n",+ "If you paste the current readings here (temperature, feels-like, wind, precipitation), I can interpret them and advise on what to wear or plan for.\n",+ "\u001b[0m\n"+ ]}],"source": [@@ -505,7 +533,8 @@"chat_response = chat_completion_request(\n"," messages, tools=tools, tool_choice=\"none\"\n",")\n",- "chat_response.choices[0].message\n"+ "messages.append(chat_response.choices[0].message.to_dict())\n",+ "pretty_print_conversation(messages)"]},{@@ -532,11 +561,11 @@{"data": {"text/plain": [- "[ChatCompletionMessageToolCall(id='call_ObhLiJwaHwc3U1KyB4Pdpx8y', function=Function(arguments='{\"location\": \"San Francisco, CA\", \"format\": \"fahrenheit\", \"num_days\": 4}', name='get_n_day_weather_forecast'), type='function'),\n",- " ChatCompletionMessageToolCall(id='call_5YRgeZ0MGBMFKE3hZiLouwg7', function=Function(arguments='{\"location\": \"Glasgow, SCT\", \"format\": \"celsius\", \"num_days\": 4}', name='get_n_day_weather_forecast'), type='function')]"+ "[ChatCompletionMessageFunctionToolCall(id='call_KlZ3Fqt3SviC6o66dVMYSa2Q', function=Function(arguments='{\"location\": \"San Francisco, CA\", \"format\": \"fahrenheit\", \"num_days\": 4}', name='get_n_day_weather_forecast'), type='function'),\n",+ " ChatCompletionMessageFunctionToolCall(id='call_YAnH0VRB3oqjqivcGj3Cd8YA', function=Function(arguments='{\"location\": \"Glasgow, UK\", \"format\": \"celsius\", \"num_days\": 4}', name='get_n_day_weather_forecast'), type='function')]"]},- "execution_count": 67,+ "execution_count": 13,"metadata": {},"output_type": "execute_result"}@@ -546,7 +575,7 @@"messages.append({\"role\": \"system\", \"content\": \"Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\"})\n","messages.append({\"role\": \"user\", \"content\": \"what is the weather going to be like in San Francisco and Glasgow over the next 4 days\"})\n","chat_response = chat_completion_request(\n",- " messages, tools=tools, model=GPT_MODEL\n",+ " messages, tools=tools, model=\"gpt-4o\"\n",")\n","\n","assistant_message = chat_response.choices[0].message.tool_calls\n",@@ -767,7 +796,7 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 21,"id": "e8b7cb9cdc7a7616","metadata": {"ExecuteTime": {@@ -780,7 +809,10 @@"name": "stdout","output_type": "stream","text": [- "ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_wDN8uLjq2ofuU6rVx1k8Gw0e', function=Function(arguments='{\"query\":\"SELECT Album.Title, COUNT(Track.TrackId) AS TrackCount FROM Album INNER JOIN Track ON Album.AlbumId = Track.AlbumId GROUP BY Album.Title ORDER BY TrackCount DESC LIMIT 1;\"}', name='ask_database'), type='function')])\n"+ "\u001b[32muser: What is the name of the album with the most tracks?\n",+ "\u001b[0m\n",+ "\u001b[34massistant: [{'id': 'call_pGRtZZGfd2o41GHlZcEdB9he', 'function': {'arguments': '{\"query\":\"WITH track_counts AS (\\\\n SELECT a.AlbumId, a.Title, COUNT(t.TrackId) AS track_count\\\\n FROM Album a\\\\n JOIN Track t ON t.AlbumId = a.AlbumId\\\\n GROUP BY a.AlbumId, a.Title\\\\n)\\\\nSELECT Title\\\\nFROM track_counts\\\\nWHERE track_count = (SELECT MAX(track_count) FROM track_counts);\"}', 'name': 'ask_database'}, 'type': 'function'}]\n",+ "\u001b[0m\n"]}],@@ -800,14 +832,13 @@"\n","# Append the message to messages list\n","response_message = response.choices[0].message \n",- "messages.append(response_message)\n",- "\n",- "print(response_message)"+ "messages.append(response_message.to_dict())\n",+ "pretty_print_conversation(messages)"]},{"cell_type": "code",- "execution_count": null,+ "execution_count": 22,"id": "351c39def3417776","metadata": {"ExecuteTime": {@@ -820,7 +851,7 @@"name": "stdout","output_type": "stream","text": [- "The album with the most tracks is titled \"Greatest Hits,\" which contains 57 tracks.\n"+ "Result found in database: Greatest Hits\n"]}],@@ -850,7 +881,7 @@" model=GPT_MODEL,\n"," messages=messages,\n"," ) # get a new response from the model where it can see the function response\n",- " print(model_response_with_function_call.choices[0].message.content)\n",+ " print(f\"Result found in database: {model_response_with_function_call.choices[0].message.content}\")\n"," else: \n"," print(f\"Error: function {tool_function_name} does not exist\")\n","else: \n",@@ -872,7 +903,7 @@],"metadata": {"kernelspec": {- "display_name": "Python 3 (ipykernel)",+ "display_name": "openai","language": "python","name": "python3"},@@ -886,7 +917,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.12.1"+ "version": "3.12.9"}},"nbformat": 4,