Search code examples
pythonlistfor-loopopenai-apichatgpt-api

OpenAI Chat Completions API: How to implement a for loop with a list of questions in Python?


I've been trying to run a for loop to run through the OpenAI Chat Completions API, but I don't seem to make it work. I'm puzzled. My goal is to have a list of all the responses.

Basically, I have a list of sentences. Let's call this list input_list. Here's an example of what this would look like:

['Who won the Champions League in 2017?', 'Who won the World Cup in 2014?', ...]

And here's how I tried to loop through the input:

output = []
for i in range(len(input_list)):
  response = openai.ChatCompletion.create(
      model="gpt-3.5-turbo",
      messages=[
          {"role": "system", "content": "You are a chatbot."},
          {"role": "user", "content": input_list[i]},
          ]
          )
  
  chat_response = response['choices'][0]['message']['content']
  output.append(chat_response)

When running this, however, the responses don't seem to append. I only ever see the very first answer in the output list. Why is this the case? And how can I fix it? I would like to see all the responses.

Many thanks in advance for your help!


Solution

  • You need to print the output.

    If you run test.py the OpenAI API will return a completion:

    ['The winner of the UEFA Champions League in 2017 was Real Madrid.', 'The 2014 FIFA World Cup was won by Germany.']

    test.py

    import openai
    import os
    
    openai.api_key = os.getenv('OPENAI_API_KEY')
    
    input_list = ['Who won the Champions League in 2017?', 'Who won the World Cup in 2014?']
    
    output = []
    
    for i in range(len(input_list)):
      response = openai.ChatCompletion.create(
        model = 'gpt-3.5-turbo',
        messages = [
          {'role': 'system', 'content': 'You are a chatbot.'},
          {'role': 'user', 'content': input_list[i]},
        ]
      )
      
      chat_response = response['choices'][0]['message']['content']
      output.append(chat_response)
    
    print(output)