sys:1: ResourceWarning: unclosed <socket.socket ERROR while using ainvoke method of ChatOpenAI #26309
Replies: 1 comment
-
To resolve the "sys:1: ResourceWarning: unclosed <socket.socket" error when using the Here is an example of how you can modify the import importlib
from contextlib import asynccontextmanager
@asynccontextmanager
async def manage_socket(model_config, converted_messages):
try:
yield await model_config.ainvoke(converted_messages)
finally:
await model_config.close() # Ensure the socket is closed
class ChatCompletion:
"""Chat completion."""
@staticmethod
async def acreate(
messages: list,
*,
provider: str = "ChatOpenAI",
stream: bool = False,
**kwargs: Any,
) -> dict:
models = importlib.import_module("langchain.chat_models")
model_cls = getattr(models, provider)
model_config = model_cls(**kwargs)
converted_messages = convert_openai_messages(messages)
if not stream:
async with manage_socket(model_config, converted_messages) as result:
return {"choices": [{"message": convert_message_to_dict(result)}]}
else:
return (
_convert_message_chunk_to_delta(c, i)
async for i, c in aenumerate(model_config.astream(converted_messages))
) In this example, the Additionally, you might want to check if there are any existing context managers or utility functions in the LangChain library that handle resource cleanup. The library provides context managers like For best practices, the LangChain documentation recommends using and extending |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Checked other resources
Commit to Help
Example Code
Description
I am trying to use langchain library to interact with openai models by invoking the async methods, but while invoking it throws the below error:
There seem to be some resource (session probably) which isn't handled well, and I can't seem find any method which would allow me to close the resouce
Any inputs on how to solve this would be really appreciated. Thanks!
System Info
langchain==0.2.16
langchain-community==0.2.16
langchain-core==0.2.38
langchain-huggingface==0.0.3
langchain-openai==0.1.23
langchain-text-splitters==0.2.2
langchain-weaviate==0.0.2
Python version: 3.10.14
Beta Was this translation helpful? Give feedback.
All reactions