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

langchain_openai: fix ChatOpenAI model's openai proxy #19559

Merged
merged 8 commits into from
Mar 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions libs/partners/openai/langchain_openai/chat_models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,12 +380,31 @@ def validate_environment(cls, values: Dict) -> Dict:
"default_query": values["default_query"],
}

openai_proxy = values["openai_proxy"]
if not values.get("client"):
if openai_proxy and not values["http_client"]:
try:
import httpx
except ImportError as e:
raise ImportError(
"Could not import httpx python package. "
"Please install it with `pip install httpx`."
) from e
values["http_client"] = httpx.Client(proxy=openai_proxy)
sync_specific = {"http_client": values["http_client"]}
values["client"] = openai.OpenAI(
**client_params, **sync_specific
).chat.completions
if not values.get("async_client"):
if openai_proxy and not values["http_async_client"]:
try:
import httpx
except ImportError as e:
raise ImportError(
"Could not import httpx python package. "
"Please install it with `pip install httpx`."
) from e
values["http_async_client"] = httpx.AsyncClient(proxy=openai_proxy)
async_specific = {"http_client": values["http_async_client"]}
values["async_client"] = openai.AsyncOpenAI(
**client_params, **async_specific
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -501,3 +501,25 @@ class MyModel(BaseModel):
assert isinstance(result, MyModel)
assert result.name == "Erick"
assert result.age == 27


def test_openai_proxy() -> None:
"""Test ChatOpenAI with proxy."""
chat_openai = ChatOpenAI(
openai_proxy="http://localhost:8080",
)
mounts = chat_openai.client._client._client._mounts
assert len(mounts) == 1
for key, value in mounts.items():
proxy = value._pool._proxy_url.origin
assert proxy.scheme == b"http"
assert proxy.host == b"localhost"
assert proxy.port == 8080

async_client_mounts = chat_openai.async_client._client._client._mounts
assert len(async_client_mounts) == 1
for key, value in async_client_mounts.items():
proxy = value._pool._proxy_url.origin
assert proxy.scheme == b"http"
assert proxy.host == b"localhost"
assert proxy.port == 8080
Loading