5

I work with the OpenAI API. I have extracted slides text from a PowerPoint presentation, and written a prompt for each slide. Now, I want to make asynchronous API calls, so that all the slides are processed at the same time.

this is the code from the async main function:

for prompt in prompted_slides_text:
    task = asyncio.create_task(api_manager.generate_answer(prompt))
    tasks.append(task)
results = await asyncio.gather(*tasks)

and this is generate_answer function:

@staticmethod
    async def generate_answer(prompt):
        """
        Send a prompt to OpenAI API and get the answer.
        :param prompt: the prompt to send.
        :return: the answer.
        """
        completion = await openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[{"role": "user", "content": prompt}]

        )
        return completion.choices[0].message.content

the problem is:

object OpenAIObject can't be used in 'await' expression

and I don't know how to await for the response in generate_answer function

Would appreciate any help!

Shiva
  • 2,627
  • 21
  • 33
DanielG
  • 217
  • 2
  • 6
  • 1
    Does this answer your question? [Using asyncio for Non-async Functions in Python?](https://stackoverflow.com/questions/51050315/using-asyncio-for-non-async-functions-in-python) – Er... May 22 '23 at 10:34

1 Answers1

10

You have to use openai.ChatCompletion.acreate to use the api asynchronously.

It's documented on their Github - https://github.com/openai/openai-python#async-api

Shiva
  • 2,627
  • 21
  • 33
  • The api has a limit of 3 requests per minute, and my program is crashed because of it, do you know how can I overcome this issue? – DanielG May 22 '23 at 12:01
  • @DanielG I had written another answer that limits concurrent requests - https://stackoverflow.com/a/67831742/3007402. See if that helps. You will find more answers at - https://stackoverflow.com/q/48483348/3007402 – Shiva May 22 '23 at 12:45
  • Still it does not work. – Brana Jun 21 '23 at 06:39
  • @Brana What specifically doesn't work? Can you share your code? You may want to ask a new question. – Shiva Jun 21 '23 at 09:21