I'm trying to figure out how ChatGPT and Code Interpreter (or anything else) gets GPT to complete an arbitrary number of actions before it ends its turn and hands it back to the user. I'm using a while loop to have it perform multiple actions but I can't figure out a way to end its turn when it has completed all tasks. I tried making an end_turn() button but it doesn't adhere to using it.
def get_some_value():
some_value = "one plus one equals two."
return json.dumps({"some_value_one": some_value})
def get_some_value_two():
some_value = "two times two equals four."
return json.dumps({"some_value_two": some_value})
def end_turn():
return json.dumps({"message": "All tasks are completed."})
Initialize the assistant and its state
messages = [
{"role": "system", "content": "You can call the function get_some_value, get_some_value_two, and call the end_turn function when your tasks are complete to hand the conversation back to the user."},
{"role": "user",
"content": "activate the get_some_value function, then activate the get_some_value_two function, then tell me the value of both. "}
]
messages = [
{"role": "system", "content": "You must quietly activate the end_turn function to give control back to the user after you are done with your current response"},
{"role": "user",
"content": "hi"}
]
Describe the functions
functions = [
{
"name": "get_some_value",
"description": "This function returns some value",
"parameters": {"type": "object", "properties": {}}
},
{
"name": "get_some_value_two",
"description": "This function returns some value",
"parameters": {"type": "object", "properties": {}}
},
{
"name": "end_turn",
"description": "This function ends the assistant's turn so the user can respond",
"parameters": {"type": "object", "properties": {}}
}
]
while True:
# Make the API call
response = openai.ChatCompletion.create(
model="gpt-4-0613",
messages=messages,
functions=functions,
function_call="auto"
)
# print(response)
function_name = response["choices"][0]["message"].get("function_call", {}).get("name")
if function_name:
# Call the function based on its name
if function_name == "get_some_value":
function_response = get_some_value()
elif function_name == "get_some_value_two":
function_response = get_some_value_two()
elif function_name == "end_turn":
function_response = end_turn()
print("Assistant says: All tasks are completed.")
break
messages.append({"role": "function", "name": function_name, "content": function_response})
else:
assistant_message = response["choices"][0]["message"]["content"]
print("Assistant says:", assistant_message)