Ошибка API OpenAI ChatGPT (gpt-3.5-turbo): «InvalidRequestError: предоставлен нераспознанный аргумент запроса: сообщения»

ВАЖНЫЙ

Для людей, у которых такая же проблема: обратитесь к ответу @Rok Benko. Вводное руководство по gpt-3.5 только что было обновлено. Это код, который они сообщают, и он отлично работает:

      import openai

openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who won the world series in 2020?"},
        {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
        {"role": "user", "content": "Where was it played?"}
    ]
)

В то время, когда был задан этот вопрос, код в документации вместо этого сообщал о конечной точке завершения GPT-3:

          openai.Completion.create()

ВОПРОС

В настоящее время я пытаюсь использовать самую последнюю модель OpenAI:gpt-3.5-turbo. Я следую очень простому руководству .

Я работаю из ноутбука Google Collab. Я должен сделать запрос для каждой подсказки в списке подсказок, который для простоты выглядит так:

      prompts = ['What are your functionalities?', 'what is the best name for an ice-cream shop?', 'who won the premier league last year?']

Я определил функцию для этого:

      import openai

# Load your API key from an environment variable or secret management service
openai.api_key = 'my_API'

def get_response(prompts: list, model = "gpt-3.5-turbo"):
  responses = []

  
  restart_sequence = "\n"

  for item in prompts:

      response = openai.Completion.create(
      model=model,
      messages=[{"role": "user", "content": prompt}],
      temperature=0,
      max_tokens=20,
      top_p=1,
      frequency_penalty=0,
      presence_penalty=0
    )

      responses.append(response['choices'][0]['message']['content'])

  return responses

Однако, когда я звонюresponses = get_response(prompts=prompts[0:3])Я получаю следующую ошибку:

      InvalidRequestError: Unrecognized request argument supplied: messages

Какие-либо предложения?

РЕДАКТИРОВАТЬ :

Заменаmessagesаргумент сpromptприводит к следующей ошибке:

      InvalidRequestError: [{'role': 'user', 'content': 'What are your functionalities?'}] is valid under each of {'type': 'array', 'minItems': 1, 'items': {'oneOf': [{'type': 'integer'}, {'type': 'object', 'properties': {'buffer': {'type': 'string', 'description': 'A serialized numpy buffer'}, 'shape': {'type': 'array', 'items': {'type': 'integer'}, 'description': 'Array shape'}, 'dtype': {'type': 'string', 'description': 'Stringified dtype'}, 'token': {'type': 'string'}}}]}, 'example': '[1, 1313, 451, {"buffer": "abcdefgh", "shape": [1024], "dtype": "float16"}]'}, {'type': 'array', 'minItems': 1, 'maxItems': 2048, 'items': {'oneOf': [{'type': 'string'}, {'type': 'object', 'properties': {'buffer': {'type': 'string', 'description': 'A serialized numpy buffer'}, 'shape': {'type': 'array', 'items': {'type': 'integer'}, 'description': 'Array shape'}, 'dtype': {'type': 'string', 'description': 'Stringified dtype'}, 'token': {'type': 'string'}}}], 'default': '', 'example': 'This is a test.', 'nullable': False}} - 'prompt'

3 ответа

      response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
  messages=[
    {"role": "user", "content": "What is openAI?"}],
max_tokens=193,
temperature=0,
)

print(response)
print(response["choices"][0]["message"]["content"])

Для gpt4 у меня это сработало

              for prompt in prompts:
            # from openai import OpenAI
            # client = OpenAI(api_key=openai.api_key)
            print(f'{self.model_name=}')
            response = openai.chat.completions.create(
            # response = client.chat.completions.create(
                model = self.model_name,
                messages = 
                [
                    # {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": prompt},
                ],
                temperature = temperature 
            )
            generated_text: str = response.choices[0].message.content.strip()
            generated_texts.append(generated_text)

когда ошибка

      openai.NotFoundError: Error code: 404 - {'error': {'message': 'This is a chat model and not supported in the v1/completions endpoint. Did you mean to use v1/chat/completions?', 'type': 'invalid_request_error', 'param': 'model', 'code': None}}

появился.

Вы должны определитьmessages=[{"role": "user", "content": prompt}]вне вашей переменной ответа и вызовите это в переменной ответа, например:

      messages=[{"role": "user", "content": prompt}]
for item in prompts:
      response = openai.Completion.create(
      model=model,
      messages=messages,
      temperature=0,
      max_tokens=20,
      top_p=1,
      frequency_penalty=0,
      presence_penalty=0
    )
Другие вопросы по тегам