Chainlit / chainlit

Build Conversational AI in minutes ⚡️
https://docs.chainlit.io
Apache License 2.0
7.29k stars 962 forks source link

SSL error using openai #66

Closed uttambarthakur closed 1 year ago

uttambarthakur commented 1 year ago

Hi,

I am executing the below example code in poetry environment having python 3.11.3 but I am getting SSL error. When I execute openai script directly without using Chainlit then I don't see the error. Error appears when user sends message and Chainlit tries to make a connection to openai. I tried with and without VPN. I have also used cert.pem using which it usually works in case of any other libraries which sometimes throws SSL error. In my case the error is only appearing when I use Chainlit. Please help me out!

code: ` import chainlit as cl import openai import os from dotenv import load_dotenv import certifi

load_dotenv()

os.environ["REQUESTS_CA_BUNDLE"] = certifi.where()

openai.api_key = os.getenv("OPENAI_API_KEY") openai.verify_ssl_certs = False

prompt = """SQL tables (and columns):

A well-written SQL query that {input}:



model_name = "text-davinci-003"

settings = {
    "temperature": 0,
    "max_tokens": 500,
    "top_p": 1,
    "frequency_penalty": 0,
    "presence_penalty": 0,
    "stop": ["```"]
}

@cl.on_message
async def main(message: str):
    formatted_prompt = prompt.format(input=message)

    # Prepare the message for streaming
    msg = cl.Message(
        content="",
        language="sql",
        prompt=formatted_prompt,
        llm_settings=cl.LLMSettings(model_name=model_name, **settings),
    )

    async for stream_resp in await openai.Completion.acreate(
        model=model_name, prompt=formatted_prompt, stream=True, **settings
    ):
        token = stream_resp.get("choices")[0].get("text")
        await msg.stream_token(token)

    await msg.send()
`

**Error:**
2023-06-15 09:11:03 - Loaded .env file
2023-06-15 09:11:04 - Your app is available at http://localhost:8000
2023-06-15 09:11:09 - Error communicating with OpenAI
Traceback (most recent call last):
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/aiohttp/connector.py", line 980, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore[return-value]  # noqa
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/base_events.py", line 1112, in create_connection
    transport, protocol = await self._create_connection_transport(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/base_events.py", line 1145, in _create_connection_transport
    await waiter
  File "/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/futures.py", line 287, in __await__
    yield self  # This tells Task to wait for completion.
    ^^^^^^^^^^
  File "/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/tasks.py", line 339, in __wakeup
    future.result()
  File "/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/futures.py", line 203, in result
    raise self._exception.with_traceback(self._exception_tb)
  File "/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/sslproto.py", line 574, in _on_handshake_complete
    raise handshake_exc
  File "/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/sslproto.py", line 556, in _do_handshake
    self._sslobj.do_handshake()
  File "/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/ssl.py", line 979, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1002)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/openai/api_requestor.py", line 668, in arequest_raw
    result = await session.request(**request_kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/aiohttp/client.py", line 536, in _request
    conn = await self._connector.connect(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/aiohttp/connector.py", line 540, in connect
    proto = await self._create_connection(req, traces, timeout)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/aiohttp/connector.py", line 901, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/aiohttp/connector.py", line 1206, in _create_direct_connection
    raise last_exc
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/aiohttp/connector.py", line 1175, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/aiohttp/connector.py", line 982, in _wrap_create_connection
    raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host api.openai.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1002)')]

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/chainlit/__init__.py", line 60, in wrapper
    return await user_function(**params_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "app2.py", line 44, in main
    async for stream_resp in await openai.Completion.acreate(
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/openai/api_resources/completion.py", line 45, in acreate
    return await super().acreate(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/openai/api_resources/abstract/engine_api_resource.py", line 217, in acreate
    response, _, api_key = await requestor.arequest(
                           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/openai/api_requestor.py", line 372, in arequest
    result = await self.arequest_raw(
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ub/Library/CloudStorage/OneDrive/mac/Projects/04Pycodes/langchain/.venv/lib/python3.11/site-packages/openai/api_requestor.py", line 685, in arequest_raw
    raise error.APIConnectionError("Error communicating with OpenAI") from e
openai.error.APIConnectionError: Error communicating with OpenAI
willydouhard commented 1 year ago

This is unexpected. I found something on SO let me know if that helps.

Chainlit does the load_dotenv() for you, you do not need to call it yourself (probably wont fix your issue though)