The sample code given here: https://platform.openai.com/docs/api-reference/chat?lang=python successfully runs in Google Colab environment.
But when I run it in my local virtual environment, it gives this error: APIConnectionError: Connection error.
I am using the same key. I am not in VPN.
In full error, I see ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate in certificate chain (_ssl.c:1020)
I already tried running
/Applications/Python*/Install\ Certificates.command
It did not help.
When I run the "curl" example given on the same page, in my shell, it works with the same key!! https://platform.openai.com/docs/api-reference/chat?lang=curl
What do I need to do?
Any guidance appreciated. Thanks
After applying this suggestion, which suggests using truststore, this problem is fixed: https://stackoverflow.com/a/79052345/727997
pip install truststore
then adding this to your python code above your openai calls:
import truststore
truststore.inject_into_ssl()
# thing that calls requests.get
Prior, I followed this to install the certificates: https://community.openai.com/t/ssl-certificate-verify-failed/32442/58
ChatGPT AI says:
Using truststore.inject_into_ssl()
is a valid approach, and it generally does not introduce security risks if used properly. Here’s a breakdown of what it does and potential concerns:
truststore.inject_into_ssl()
Do?truststore
package allows Python to use the system's native CA certificates instead of relying on certifi
or manually setting SSL_CERT_FILE
.truststore.inject_into_ssl()
modifies Python's SSL module so that it uses the system's root certificates.✅ Pros (Security Benefits):
certifi
, reducing the risk of using outdated certificates.truststore
ensures Python respects them.⚠️ Potential Security Risks:
truststore
defers trust decisions to the OS, any rogue or outdated root certificates in the system CA store will also be trusted by Python.ssl
settings, it might conflict with truststore
’s changes, leading to unexpected SSL behavior.requests
defaults to certifi
), so overriding with truststore
might cause issues in certain environments.certifi
Feature | truststore (inject_into_ssl() ) |
certifi |
---|---|---|
Uses system CA store? | ✅ Yes | ❌ No (uses Mozilla CA bundle) |
Needs updates? | ✅ Auto-updated with OS | ❌ Requires pip install --upgrade certifi |
Works in all environments? | ⚠️ May not work in some isolated containers | ✅ Works anywhere with Python |
Security risk if OS CA is compromised? | ⚠️ Yes | ✅ No (independent CA store) |
truststore.inject_into_ssl()
is a good option with no major security risks.certifi
to ensure you have a consistent, independently maintained CA store.