Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix AsyncOpenAI "RuntimeError: Event loop is closed bug" when instances of AsyncOpenAI are rapidly created & destroyed #12946

Merged

Conversation

philipchung
Copy link
Contributor

… avoid openai/openai-python#1262

Description

When AsyncOpenAI classes are rapidly created and destroyed, the underlying httpx.AsyncClient is not properly opened and closed unless requests are made from a context manager. AsyncOpenAI clients underlie LlamaIndex OpenAI and OpenAI-Like classes, so if we rapidly create and destroy these (e.g. in multithread/multiprocess context) this error will arise. This PR just wraps the completions.create() calls within a client context manager and ensures that the underlying httpx.AsyncClient used by the OpenAI python client is properly opened and closed.

For completeness, completion.create() requests from the Sync OpenAI client are also wrapped in a client context manager. This PR also aligns the _achat() method to return logprobs similar to _chat() method.

Fixes issues raised in openai/openai-python#1262, openai/openai-python#1254

New Package?

Did I fill in the tool.llamahub section in the pyproject.toml and provide a detailed README.md for my new integration or package?

  • Yes
  • No

Version Bump?

Did I bump the version in the pyproject.toml file of the package I am updating? (Except for the llama-index-core package)

  • Yes
  • No

Type of Change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration

  • Added new unit/integration tests
  • Added new notebook (that tests end-to-end)
  • I stared at the code and made sure it makes sense
  • I implemented it in my project code and it resolves the RuntimeError

Suggested Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • I have added Google Colab support for the newly added notebooks.
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I ran make format; make lint to appease the lint gods

@dosubot dosubot bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 18, 2024
@logan-markewich
Copy link
Collaborator

@philipchung This seems to have caused more issues when I run your branch?

from llama_index.llms.openai import OpenAI
from llama_index.core.llms import ChatMessage

llm = OpenAI()

async def arun():
  await llm.acomplete("Hello World!")
  gen = await llm.astream_complete("Hello world!")
  async for token in gen:
    pass
  await llm.achat([ChatMessage(role="user", content="Hello World!")])
  gen = await llm.astream_chat([ChatMessage(role="user", content="Hello World!")])
  async for token in gen:
    pass

def run():
  llm.complete("Hello World!")
  gen = llm.stream_complete("Hello world!")
  for token in gen:
    pass
  llm.chat([ChatMessage(role="user", content="Hello World!")])
  gen = llm.stream_chat([ChatMessage(role="user", content="Hello World!")])
  for token in gen:
    pass


async def run_many():
  tasks = [arun(), arun(), arun()]
  await asyncio.gather(*tasks)

# test async
import asyncio
tasks = [arun(), arun(), arun()]
asyncio.run(run_many())

# test sync
run()

I get this error

RuntimeError: Cannot send a request, as the client has been closed.

If I install an older version of the openai package, it works fine though

@logan-markewich
Copy link
Collaborator

I know using a global LLM is probably not advisable, but I know many users who do this

…ntext closes client's connection pool; do not use client context in streaming methods
…nt's connection pool will be closed; context manager not used for streaming methods
@philipchung
Copy link
Contributor Author

I believe I resolved the issues, and running your test code works. Also passes pytest.

Changes are:

  1. Using a client context manager closes the connection pool after leaving the context block, so if reuse_client=True, then this would cause an error for future completion.Create() calls. I changed the code to only use only client context manager if reuse_client=False.
  2. I removed client context manager from streaming methods so they are now unchanged. It was unclear to me how to implement the client context manager with a generator. Also, use cases with streaming completion.Create() calls are unlikely to use multithread/multiprocessing.

@logan-markewich
Copy link
Collaborator

Yea streaming is kind of hard in this case -- lgtm otherwise now

@logan-markewich logan-markewich enabled auto-merge (squash) April 19, 2024 17:33
@dosubot dosubot bot added the lgtm This PR has been approved by a maintainer label Apr 19, 2024
@logan-markewich logan-markewich merged commit 7b52057 into run-llama:main Apr 19, 2024
8 checks passed
chrisalexiuk-nvidia pushed a commit to chrisalexiuk-nvidia/llama_index that referenced this pull request Apr 25, 2024
mattf pushed a commit to mattf/llama_index that referenced this pull request Apr 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants