Let’s take some example input (example of how gpt-3.5-turbo is on edge of not understanding…)
(expand) ChatCompletion response n=6
output_object =
{
"id": "chatcmpl-7xCLl4yD4nAqrBDXv2FUe6IBmIzKs",
"object": "chat.completion",
"created": 1694343181,
"model": "gpt-3.5-turbo-0613",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "{\"joke_question\": \"Why don't scientists trust atoms?\", \"joke_answer\": \"0. Because they make up everything!\"}"
},
"finish_reason": "stop"
},
{
"index": 1,
"message": {
"role": "assistant",
"content": "{\"joke_question\": \"Why don\u2019t scientists trust atoms?\", \"joke_answer\": \"1. Because they make up everything!\"}"
},
"finish_reason": "stop"
},
{
"index": 2,
"message": {
"role": "assistant",
"content": "{\"joke_question\": \"(AI random joke)\", \"joke_answer\": \"2. (punchline)\"}"
},
"finish_reason": "stop"
},
{
"index": 3,
"message": {
"role": "assistant",
"content": "{\"joke_question\": \"(AI random joke)\", \"joke_answer\": \"3. I'm reading a book about anti-gravity. It's impossible to put down!\"}"
},
"finish_reason": "stop"
},
{
"index": 4,
"message": {
"role": "assistant",
"content": "{\"joke_question\": \"Why don't scientists trust atoms?\", \"joke_answer\": \"4. Because they make up everything!\"}"
},
"finish_reason": "stop"
},
{
"index": 5,
"message": {
"role": "assistant",
"content": "{\"joke_question\": \"Why don't scientists trust atoms?\", \"joke_answer\": \"5. Because they make up everything!\"}"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 40,
"completion_tokens": 159,
"total_tokens": 199
}
}
So we just put that in our example code as “response” - or you can start with the response of an actual chat completion call (although note that response can be a generator without completed response)
Then some code to extract one AI response, and some code to demonstrate picking, thanks to AI specifications about as long as the output:
def pick_choice(response, index):
choices = response.get("choices", [])
if 0 <= index < len(choices):
return choices[index]["message"]["content"]
else:
return "Error: Index does not exist in choices."
# Demonstration of the function
while True:
try:
choice_index = input("Enter choice index (0-5) or press Enter to exit: ")
if not choice_index:
break
choice_index = int(choice_index)
content = pick_choice(response, choice_index)
print(content)
except ValueError:
print("Error: Invalid input. Please enter a valid integer index.")
except IndexError as e:
print(str(e))
(handle errors in a way that actually works for you)