Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save keyboardAnt/e9237d056d923d8c8bf761963b369c6c to your computer and use it in GitHub Desktop.
Save keyboardAnt/e9237d056d923d8c8bf761963b369c6c to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"id": "3e67f200",
"metadata": {},
"source": [
"# How to call functions with chat models\n",
"\n",
"This notebook covers how to use the Chat Completions API in combination with external functions to extend the capabilities of GPT models.\n",
"\n",
"`functions` is an optional parameter in the Chat Completion API which can be used to provide function specifications. The purpose of this is to enable models to generate function arguments which adhere to the provided specifications. Note that the API will not actually execute any function calls. It is up to developers to execute function calls using model outputs.\n",
"\n",
"If the `functions` parameter is provided then by default the model will decide when it is appropriate to use one of the functions. The API can be forced to use a specific function by setting the `function_call` parameter to `{\"name\": \"<insert-function-name>\"}`. The API can also be forced to not use any function by setting the `function_call` parameter to `\"none\"`. If a function is used, the output will contain `\"finish_reason\": \"function_call\"` in the response, as well as a `function_call` object that has the name of the function and the generated function arguments.\n",
"\n",
"### Overview\n",
"\n",
"This notebook contains the following 2 sections:\n",
"\n",
"- **How to generate function arguments:** Specify a set of functions and use the API to generate function arguments.\n",
"- **How to call functions with model generated arguments:** Close the loop by actually executing functions with model generated arguments."
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "64c85e26",
"metadata": {},
"source": [
"## How to generate function arguments"
]
},
{
"cell_type": "code",
"execution_count": 66,
"id": "80e71f33",
"metadata": {
"pycharm": {
"is_executing": true
},
"ExecuteTime": {
"end_time": "2023-07-21T22:19:29.018360Z",
"start_time": "2023-07-21T22:19:22.851047Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Requirement already satisfied: scipy in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (1.11.1)\r\n",
"Requirement already satisfied: numpy<1.28.0,>=1.21.6 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from scipy) (1.25.1)\r\n",
"Requirement already satisfied: tenacity in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (8.2.2)\r\n",
"Requirement already satisfied: tiktoken in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (0.4.0)\r\n",
"Requirement already satisfied: regex>=2022.1.18 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from tiktoken) (2023.6.3)\r\n",
"Requirement already satisfied: requests>=2.26.0 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from tiktoken) (2.29.0)\r\n",
"Requirement already satisfied: charset-normalizer<4,>=2 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests>=2.26.0->tiktoken) (2.0.4)\r\n",
"Requirement already satisfied: idna<4,>=2.5 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests>=2.26.0->tiktoken) (3.4)\r\n",
"Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests>=2.26.0->tiktoken) (1.26.16)\r\n",
"Requirement already satisfied: certifi>=2017.4.17 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests>=2.26.0->tiktoken) (2023.5.7)\r\n",
"Requirement already satisfied: termcolor in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (2.3.0)\r\n",
"Requirement already satisfied: openai in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (0.27.8)\r\n",
"Requirement already satisfied: requests>=2.20 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from openai) (2.29.0)\r\n",
"Requirement already satisfied: tqdm in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from openai) (4.65.0)\r\n",
"Requirement already satisfied: aiohttp in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from openai) (3.8.5)\r\n",
"Requirement already satisfied: charset-normalizer<4,>=2 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests>=2.20->openai) (2.0.4)\r\n",
"Requirement already satisfied: idna<4,>=2.5 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests>=2.20->openai) (3.4)\r\n",
"Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests>=2.20->openai) (1.26.16)\r\n",
"Requirement already satisfied: certifi>=2017.4.17 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests>=2.20->openai) (2023.5.7)\r\n",
"Requirement already satisfied: attrs>=17.3.0 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from aiohttp->openai) (22.1.0)\r\n",
"Requirement already satisfied: multidict<7.0,>=4.5 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from aiohttp->openai) (6.0.4)\r\n",
"Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from aiohttp->openai) (4.0.2)\r\n",
"Requirement already satisfied: yarl<2.0,>=1.0 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from aiohttp->openai) (1.9.2)\r\n",
"Requirement already satisfied: frozenlist>=1.1.1 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from aiohttp->openai) (1.4.0)\r\n",
"Requirement already satisfied: aiosignal>=1.1.2 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from aiohttp->openai) (1.3.1)\r\n",
"Requirement already satisfied: requests in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (2.29.0)\r\n",
"Requirement already satisfied: charset-normalizer<4,>=2 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests) (2.0.4)\r\n",
"Requirement already satisfied: idna<4,>=2.5 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests) (3.4)\r\n",
"Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests) (1.26.16)\r\n",
"Requirement already satisfied: certifi>=2017.4.17 in /Users/nadavt/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages (from requests) (2023.5.7)\r\n"
]
}
],
"source": [
"!pip install scipy\n",
"!pip install tenacity\n",
"!pip install tiktoken\n",
"!pip install termcolor \n",
"!pip install openai\n",
"!pip install requests"
]
},
{
"cell_type": "code",
"execution_count": 67,
"id": "dab872c5",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-21T22:19:29.024656Z",
"start_time": "2023-07-21T22:19:29.020827Z"
}
},
"outputs": [],
"source": [
"import json\n",
"import openai\n",
"import requests\n",
"from tenacity import retry, wait_random_exponential, stop_after_attempt\n",
"from termcolor import colored\n",
"\n",
"GPT_MODEL = \"gpt-3.5-turbo-0613\""
]
},
{
"cell_type": "code",
"execution_count": 68,
"outputs": [],
"source": [
"from getpass import getpass\n",
"\n",
"openai.api_key = getpass(\"OpenAI Key: \")"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-07-21T22:19:41.048452Z",
"start_time": "2023-07-21T22:19:29.023764Z"
}
}
},
{
"attachments": {},
"cell_type": "markdown",
"id": "69ee6a93",
"metadata": {},
"source": [
"### Utilities\n",
"\n",
"First let's define a few utilities for making calls to the Chat Completions API and for maintaining and keeping track of the conversation state."
]
},
{
"cell_type": "code",
"execution_count": 69,
"id": "745ceec5",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-21T22:19:41.048700Z",
"start_time": "2023-07-21T22:19:41.043413Z"
}
},
"outputs": [],
"source": [
"@retry(wait=wait_random_exponential(multiplier=1, max=40), stop=stop_after_attempt(3))\n",
"def chat_completion_request(messages, functions=None, function_call=None, model=GPT_MODEL):\n",
" headers = {\n",
" \"Content-Type\": \"application/json\",\n",
" \"Authorization\": \"Bearer \" + openai.api_key,\n",
" }\n",
" json_data = {\"model\": model, \"messages\": messages}\n",
" if functions is not None:\n",
" json_data.update({\"functions\": functions})\n",
" if function_call is not None:\n",
" json_data.update({\"function_call\": function_call})\n",
" try:\n",
" response = requests.post(\n",
" \"https://api.openai.com/v1/chat/completions\",\n",
" headers=headers,\n",
" json=json_data,\n",
" )\n",
" return response\n",
" except Exception as e:\n",
" print(\"Unable to generate ChatCompletion response\")\n",
" print(f\"Exception: {e}\")\n",
" return e\n"
]
},
{
"cell_type": "code",
"execution_count": 70,
"id": "c4d1c99f",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-21T22:19:41.055084Z",
"start_time": "2023-07-21T22:19:41.052080Z"
}
},
"outputs": [],
"source": [
"def pretty_print_conversation(messages):\n",
" role_to_color = {\n",
" \"system\": \"red\",\n",
" \"user\": \"green\",\n",
" \"assistant\": \"blue\",\n",
" \"function\": \"magenta\",\n",
" }\n",
" \n",
" for message in messages:\n",
" if message[\"role\"] == \"system\":\n",
" 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",
" 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"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "29d4e02b",
"metadata": {},
"source": [
"### Basic concepts\n",
"\n",
"Let's create some function specifications to interface with a hypothetical weather API. We'll pass these function specification to the Chat Completions API in order to generate function arguments that adhere to the specification."
]
},
{
"cell_type": "code",
"execution_count": 71,
"id": "d2e25069",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-21T22:19:41.060081Z",
"start_time": "2023-07-21T22:19:41.057628Z"
}
},
"outputs": [],
"source": [
"functions = [\n",
" {\n",
" \"name\": \"get_current_weather\",\n",
" \"description\": \"Get the current weather\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"location\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The city and state, e.g. San Francisco, CA\",\n",
" },\n",
" \"format\": {\n",
" \"type\": \"string\",\n",
" \"enum\": [\"celsius\", \"fahrenheit\"],\n",
" \"description\": \"The temperature unit to use. Infer this from the users location.\",\n",
" },\n",
" },\n",
" \"required\": [\"location\", \"format\"],\n",
" },\n",
" },\n",
" {\n",
" \"name\": \"get_n_day_weather_forecast\",\n",
" \"description\": \"Get an N-day weather forecast\",\n",
" \"parameters\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"location\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"The city and state, e.g. San Francisco, CA\",\n",
" },\n",
" \"format\": {\n",
" \"type\": \"string\",\n",
" \"enum\": [\"celsius\", \"fahrenheit\"],\n",
" \"description\": \"The temperature unit to use. Infer this from the users location.\",\n",
" },\n",
" \"num_days\": {\n",
" \"type\": \"integer\",\n",
" \"description\": \"The number of days to forecast\",\n",
" }\n",
" },\n",
" \"required\": [\"location\", \"format\", \"num_days\"]\n",
" },\n",
" },\n",
"]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "bfc39899",
"metadata": {},
"source": [
"If we prompt the model about the current weather, it will respond with some clarifying questions."
]
},
{
"cell_type": "code",
"execution_count": 72,
"id": "518d6827",
"metadata": {
"ExecuteTime": {
"end_time": "2023-07-21T22:19:42.201626Z",
"start_time": "2023-07-21T22:19:41.062326Z"
}
},
"outputs": [
{
"data": {
"text/plain": "{'role': 'assistant',\n 'content': 'Sure, I can help you with that. Can you please provide me with the city and state?'}"
},
"execution_count": 72,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"messages = []\n",
"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's the weather like today\"})\n",
"chat_response = chat_completion_request(\n",
" messages, functions=functions\n",
")\n",
"assistant_message = chat_response.json()[\"choices\"][0][\"message\"]\n",
"messages.append(assistant_message)\n",
"assistant_message\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "4c999375",
"metadata": {},
"source": [
"Once we provide the missing information, it will generate the appropriate function arguments for us."
]
},
{
"cell_type": "code",
"execution_count": 80,
"id": "23c42a6e",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": "{'role': 'assistant',\n 'content': None,\n 'function_call': {'name': 'get_current_weather',\n 'arguments': '{\\n \"location\": \"Glasgow, Scotland\",\\n \"format\": \"celsius\"\\n}'}}"
},
"execution_count": 73,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"text/plain": "{'role': 'assistant',\n 'content': None,\n 'function_call': {'name': 'Game',\n 'arguments': '{\\n \"players\": [\\n { \"player_name\": \"Alice\" },\\n { \"player_name\": \"Bob\" }\\n ],\\n \"moves\": [],\\n \"location\": \"Glasgow, Scotland\"\\n}'}}"
},
"execution_count": 80,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"messages.append({\"role\": \"user\", \"content\": \"I'm in Glasgow, Scotland.\"})\n",
"chat_response = chat_completion_request(\n",
" messages, functions=functions\n",
")\n",
"assistant_message = chat_response.json()[\"choices\"][0][\"message\"]\n",
"messages.append(assistant_message)\n",
"assistant_message\n"
]
},
{
"cell_type": "markdown",
"source": [
"# Not adhering to a JSON schema (with `minItems`)"
],
"metadata": {
"collapsed": false
}
},
{
"cell_type": "code",
"execution_count": 74,
"outputs": [
{
"data": {
"text/plain": "Game(players=[Player(player_name='Alice'), Player(player_name='Bob')], moves=[Move(player=Player(player_name='Alice'), move='move 1 to 2'), Move(player=Player(player_name='Bob'), move='move 2 to 3')])"
},
"execution_count": 74,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from pydantic import BaseModel, Field\n",
"\n",
"\n",
"class Player(BaseModel):\n",
" \"\"\"A player.\"\"\"\n",
" player_name: str\n",
"\n",
"class Move(BaseModel):\n",
" \"\"\"A move.\"\"\"\n",
" player: Player\n",
" move: str\n",
"\n",
"class Game(BaseModel):\n",
" \"\"\"A game.\"\"\"\n",
" players: list[Player] = Field(description=\"List of players\")\n",
" moves: list[Move] = Field(description=\"List of moves\", min_items=1)\n",
"\n",
"game: Game = Game(**{\n",
" \"players\": [\n",
" {\"player_name\": \"Alice\"},\n",
" {\"player_name\": \"Bob\"},\n",
" ],\n",
" \"moves\": [\n",
" {\"player\": {\"player_name\": \"Alice\"}, \"move\": \"move 1 to 2\"},\n",
" {\"player\": {\"player_name\": \"Bob\"}, \"move\": \"move 2 to 3\"},\n",
" ],\n",
"})\n",
"game"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-07-21T22:21:34.123839Z",
"start_time": "2023-07-21T22:21:34.114304Z"
}
}
},
{
"cell_type": "code",
"execution_count": 75,
"outputs": [
{
"data": {
"text/plain": "{'$defs': {'Move': {'description': 'A move.',\n 'properties': {'player': {'$ref': '#/$defs/Player'},\n 'move': {'title': 'Move', 'type': 'string'}},\n 'required': ['player', 'move'],\n 'title': 'Move',\n 'type': 'object'},\n 'Player': {'description': 'A player.',\n 'properties': {'player_name': {'title': 'Player Name', 'type': 'string'}},\n 'required': ['player_name'],\n 'title': 'Player',\n 'type': 'object'}},\n 'description': 'A game.',\n 'properties': {'players': {'description': 'List of players',\n 'items': {'$ref': '#/$defs/Player'},\n 'title': 'Players',\n 'type': 'array'},\n 'moves': {'description': 'List of moves',\n 'items': {'$ref': '#/$defs/Move'},\n 'minItems': 1,\n 'title': 'Moves',\n 'type': 'array'}},\n 'required': ['players', 'moves'],\n 'title': 'Game',\n 'type': 'object'}"
},
"execution_count": 75,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Game.model_json_schema()"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-07-21T22:21:34.128526Z",
"start_time": "2023-07-21T22:21:34.125824Z"
}
}
},
{
"cell_type": "code",
"execution_count": 76,
"outputs": [
{
"data": {
"text/plain": "{'name': 'Game',\n 'description': 'A game.',\n 'parameters': {'$defs': {'Move': {'description': 'A move.',\n 'properties': {'player': {'$ref': '#/$defs/Player'},\n 'move': {'type': 'string'}},\n 'required': ['player', 'move'],\n 'type': 'object'},\n 'Player': {'description': 'A player.',\n 'properties': {'player_name': {'type': 'string'}},\n 'required': ['player_name'],\n 'type': 'object'}},\n 'description': 'A game.',\n 'properties': {'players': {'description': 'List of players',\n 'items': {'$ref': '#/$defs/Player'},\n 'type': 'array'},\n 'moves': {'description': 'List of moves',\n 'items': {'$ref': '#/$defs/Move'},\n 'minItems': 1,\n 'type': 'array'}},\n 'required': ['players', 'moves'],\n 'type': 'object'}}"
},
"execution_count": 76,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# https://stackoverflow.com/a/58938747\n",
"def remove_a_key(d, remove_key):\n",
" if isinstance(d, dict):\n",
" for key in list(d.keys()):\n",
" if key == remove_key:\n",
" del d[key]\n",
" else:\n",
" remove_a_key(d[key], remove_key)\n",
"\n",
"\n",
"def schema_to_function(schema: ...):\n",
" assert schema.__doc__, f\"{schema.__name__} is missing a docstring.\"\n",
" schema_dict = schema.model_json_schema()\n",
" remove_a_key(schema_dict, \"title\")\n",
"\n",
" return {\n",
" \"name\": schema.__name__,\n",
" \"description\": schema.__doc__,\n",
" \"parameters\": schema_dict,\n",
" }\n",
"\n",
"\n",
"schema_to_function(Game)"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-07-21T22:21:34.149871Z",
"start_time": "2023-07-21T22:21:34.132413Z"
}
}
},
{
"cell_type": "code",
"execution_count": 77,
"outputs": [
{
"data": {
"text/plain": "{'role': 'assistant',\n 'content': None,\n 'function_call': {'name': 'Game',\n 'arguments': '{\\n \"players\": [\\n { \"player_name\": \"Alice\" },\\n { \"player_name\": \"Bob\" }\\n ],\\n \"moves\": []\\n}'}}"
},
"execution_count": 77,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"messages = []\n",
"messages.append({\"role\": \"system\", \"content\": \"Create a chess game.\"})\n",
"messages.append({\"role\": \"user\", \"content\": \"The players are Alice and Bob.\"})\n",
"chat_response = chat_completion_request(\n",
" messages, functions=[schema_to_function(Game)], function_call={\"name\": \"Game\"}\n",
")\n",
"assistant_message = chat_response.json()[\"choices\"][0][\"message\"]\n",
"messages.append(assistant_message)\n",
"assistant_message"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-07-21T22:21:35.972734Z",
"start_time": "2023-07-21T22:21:34.137549Z"
}
}
},
{
"cell_type": "code",
"execution_count": 78,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"print(assistant_message[\"content\"])"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-07-21T22:21:35.976468Z",
"start_time": "2023-07-21T22:21:35.973766Z"
}
}
},
{
"cell_type": "code",
"execution_count": 79,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\n",
" \"players\": [\n",
" { \"player_name\": \"Alice\" },\n",
" { \"player_name\": \"Bob\" }\n",
" ],\n",
" \"moves\": []\n",
"}\n"
]
}
],
"source": [
"print(assistant_message[\"function_call\"][\"arguments\"])"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-07-21T22:21:35.981383Z",
"start_time": "2023-07-21T22:21:35.979106Z"
}
}
},
{
"cell_type": "code",
"execution_count": 84,
"outputs": [
{
"ename": "ValidationError",
"evalue": "1 validation error for Game\nmoves\n List should have at least 1 item after validation, not 0 [type=too_short, input_value=[], input_type=list]\n For further information visit https://errors.pydantic.dev/2.1.2/v/too_short",
"output_type": "error",
"traceback": [
"\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
"\u001B[0;31mValidationError\u001B[0m Traceback (most recent call last)",
"Cell \u001B[0;32mIn[84], line 3\u001B[0m\n\u001B[1;32m 1\u001B[0m \u001B[38;5;28;01mimport\u001B[39;00m \u001B[38;5;21;01mjson\u001B[39;00m\n\u001B[0;32m----> 3\u001B[0m \u001B[43mGame\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[43mjson\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mloads\u001B[49m\u001B[43m(\u001B[49m\u001B[43massistant_message\u001B[49m\u001B[43m[\u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43mfunction_call\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m]\u001B[49m\u001B[43m[\u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43marguments\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m]\u001B[49m\u001B[43m)\u001B[49m\u001B[43m)\u001B[49m\n",
"File \u001B[0;32m~/opt/anaconda3/envs/simpleaichat-env/lib/python3.10/site-packages/pydantic/main.py:150\u001B[0m, in \u001B[0;36mBaseModel.__init__\u001B[0;34m(__pydantic_self__, **data)\u001B[0m\n\u001B[1;32m 148\u001B[0m \u001B[38;5;66;03m# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks\u001B[39;00m\n\u001B[1;32m 149\u001B[0m __tracebackhide__ \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;01mTrue\u001B[39;00m\n\u001B[0;32m--> 150\u001B[0m \u001B[43m__pydantic_self__\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43m__pydantic_validator__\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mvalidate_python\u001B[49m\u001B[43m(\u001B[49m\u001B[43mdata\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mself_instance\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43m__pydantic_self__\u001B[49m\u001B[43m)\u001B[49m\n",
"\u001B[0;31mValidationError\u001B[0m: 1 validation error for Game\nmoves\n List should have at least 1 item after validation, not 0 [type=too_short, input_value=[], input_type=list]\n For further information visit https://errors.pydantic.dev/2.1.2/v/too_short"
]
}
],
"source": [
"import json\n",
"\n",
"Game(**json.loads(assistant_message[\"function_call\"][\"arguments\"]))"
],
"metadata": {
"collapsed": false,
"ExecuteTime": {
"end_time": "2023-07-21T22:23:06.830657Z",
"start_time": "2023-07-21T22:23:06.828110Z"
}
}
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment