ConnectionRefusedError
builtins.ConnectionRefusedError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
client = LangSmithClient(api_key=os.environ["LANGSMITH_API_KEY"])
File "/usr/local/lib/python3.9/site-packages/langsmith/client.py", line 88, in __init__
self._connect()
File "/usr/local/lib/python3.9/site-packages/langsmith/client.py", line 102, in _connect
raise ConnectionRefusedError("Connection refused by LangSmith server")
ConnectionRefusedError: Connection refused by LangSmith server Why it happens
This error occurs when the LangSmith client attempts to establish a network connection to the LangSmith server but the server actively refuses the connection. Common causes include incorrect endpoint URLs, network firewall restrictions, or the LangSmith service being down or unreachable.
Detection
Monitor connection attempts and catch ConnectionRefusedError exceptions when initializing the LangSmith client; log the endpoint and network status to detect connectivity issues early.
Causes & fixes
Incorrect or missing LangSmith API endpoint URL in client configuration
Verify and set the correct LangSmith API endpoint URL in your client initialization or environment variables.
Network firewall or proxy blocking outbound connections to LangSmith servers
Ensure your network firewall or proxy allows outbound traffic to the LangSmith server IPs and ports.
LangSmith service is temporarily down or unreachable due to maintenance or outage
Check LangSmith service status page and retry connection after confirming service availability.
Invalid or missing LANGSMITH_API_KEY environment variable causing client to fail early
Set a valid LANGSMITH_API_KEY in your environment before initializing the client.
Code: broken vs fixed
import os
from langsmith import LangSmithClient
client = LangSmithClient(api_key=os.environ["LANGSMITH_API_KEY"])
# This line raises ConnectionRefusedError if server refuses connection
client.connect() import os
from langsmith import LangSmithClient
# Ensure environment variables are set correctly
os.environ["LANGSMITH_API_KEY"] = os.getenv("LANGSMITH_API_KEY", "")
os.environ["LANGSMITH_API_ENDPOINT"] = os.getenv("LANGSMITH_API_ENDPOINT", "https://api.langsmith.com")
client = LangSmithClient(api_key=os.environ["LANGSMITH_API_KEY"], endpoint=os.environ["LANGSMITH_API_ENDPOINT"])
client.connect() # Fixed: specify correct endpoint and ensure API key is set
print("LangSmith client connected successfully") Workaround
Wrap the client connection call in try/except ConnectionRefusedError, log the error, and implement exponential backoff retries to handle transient network issues.
Prevention
Use environment validation on startup to confirm API keys and endpoints are set, and implement network connectivity checks before client initialization to avoid runtime connection refusals.