Skip to content

BaseClient._prepare_url() corrupts relative endpoint URLs when base_url contains query parameters #4311

Open

Description

@0718lol

Confirm this is an issue with the Python library and not an underlying OpenAI API

  • This is an issue with the Python library

Describe the bug

In src/openai/_base_client.py, _enforce_trailing_slash() already splits url.raw_path.partition(b"?") so that query parameters on base_url are preserved when normalizing the trailing slash (lines 475–479):

def _enforce_trailing_slash(self, url: URL) -> URL:
    path, separator, query = url.raw_path.partition(b"?")
    if path.endswith(b"/"):
        return url
    return url.copy_with(raw_path=path + b"/" + separator + query)

However, BaseClient._prepare_url() (lines 564–575) concatenates self.base_url.raw_path directly with merge_url.raw_path.lstrip(b"/"):

def _prepare_url(self, url: str) -> URL:
    merge_url = URL(url)
    if merge_url.is_relative_url:
        merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/")
        return self.base_url.copy_with(raw_path=merge_raw_path)

    return merge_url

Because httpx2.URL.raw_path includes the ?query portion, whenever base_url carries query parameters (common with enterprise proxies, multi-tenant gateways, or query-routed endpoints), every relative HTTP request path is appended onto the end of the query parameter value instead of the URL path:

  • base_url="https://proxy.example.com/v1?tenant=acme" + "/models" becomes https://proxy.example.com/v1/?tenant=acmemodels instead of https://proxy.example.com/v1/models?tenant=acme.
  • If the relative URL also has query parameters (e.g. "/models?after=m1"), the ? is concatenated into the value as ?tenant=acmemodels?after=m1 (or percent-encoded to ?tenant=acmemodels%3Fafter%3Dm1&limit=5 when merged with params).

This affects OpenAI, AsyncOpenAI, and AzureOpenAI(base_url=...) (as well as any callers delegating to BaseClient._prepare_url()).

To Reproduce

  1. Construct OpenAI(api_key="test", base_url="https://proxy.example.com/v1?tenant=acme") (or AsyncOpenAI).
  2. Build a request for a relative endpoint such as "/models" or "/models?after=m1".
  3. Observe that request.url appends "models" to the tenant query value instead of /v1/.

Code snippets

from openai import OpenAI
from openai._models import FinalRequestOptions

client = OpenAI(api_key="test", base_url="https://proxy.example.com/v1?tenant=acme")

req1 = client._build_request(FinalRequestOptions.construct(method="get", url="/models"))
print(req1.url)
# Actual:   https://proxy.example.com/v1/?tenant=acmemodels
# Expected: https://proxy.example.com/v1/models?tenant=acme

req2 = client._build_request(
    FinalRequestOptions.construct(method="get", url="/models?after=m1", params={"limit": "5"})
)
print(req2.url)
# Actual:   https://proxy.example.com/v1/?tenant=acmemodels%3Fafter%3Dm1&limit=5
# Expected: https://proxy.example.com/v1/models?tenant=acme&after=m1&limit=5

Suggested fix

Partition both self.base_url.raw_path and merge_url.raw_path on b"?", join their path components while preserving raw percent-encoding, and re-attach/combine any query parameters:

--- a/src/openai/_base_client.py
+++ b/src/openai/_base_client.py
@@ -569,7 +569,17 @@ class BaseClient(Generic[_HttpxClientT, _DefaultStreamT]):
         # Copied from httpx's `_merge_url` method.
         merge_url = URL(url)
         if merge_url.is_relative_url:
-            merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/")
+            base_path, _, base_query = self.base_url.raw_path.partition(b"?")
+            rel_path, _, rel_query = merge_url.raw_path.partition(b"?")
+            merge_path = base_path + rel_path.lstrip(b"/")
+            if base_query and rel_query:
+                merge_raw_path = merge_path + b"?" + base_query + b"&" + rel_query
+            elif base_query:
+                merge_raw_path = merge_path + b"?" + base_query
+            elif rel_query:
+                merge_raw_path = merge_path + b"?" + rel_query
+            else:
+                merge_raw_path = merge_path
             return self.base_url.copy_with(raw_path=merge_raw_path)
 
         return merge_url

OS

macOS

Python version

Python 3.14

Library version

openai v3.57.0 (main@f63f14b)

Activity

  1. abhi478jeetur-rgb commented on Nov 22, 2026

    @abhi478jeetur-rgb

    Reproduced exactly as described, on openai 3.57.0:

    client = OpenAI(api_key="sk-test", base_url="https://proxy.example.com/v1?tenant=acme")
    client._build_request(FinalRequestOptions.construct(method="get", url="/models")).url
    # https://proxy.example.com/v1/?tenant=acmemodels
    client._build_request(FinalRequestOptions.construct(method="get", url="/models?after=m1")).url
    # https://proxy.example.com/v1/?tenant=acmemodels?after=m1

    Same client with a base_url carrying no query gives the correct https://proxy.example.com/v1/models, so it's specifically the query on base_url that breaks it. The cause is what you identified: _prepare_url concatenates self.base_url.raw_path with the relative path, and raw_path includes the ?query part, so the endpoint gets appended to the query value instead of the path.

    The fix is to split the query off before concatenating — the same partition(b"?") trick _enforce_trailing_slash already uses a few lines above. I patched _prepare_url that way in a scratch install and verified:

    "/models"          -> https://proxy.example.com/v1/models?tenant=acme
    "/models?after=m1" -> https://proxy.example.com/v1/models?tenant=acme&after=m1

    i.e. the base query is preserved, and a query on the relative URL is appended after it with &. Absolute URLs are untouched, since that branch returns merge_url directly.

  2. Shanmukh-l33t commented on Nov 22, 2026

    @Shanmukh-l33t

    Reproduced this on main@f63f14b and pushed a minimal fix with a regression test to a fork branch (I am not a collaborator, so no PR per CONTRIBUTING.md).

    Branch: fix/prepare-url-base-query on Shanmukh-l33t/openai-python
    Compare: main...Shanmukh-l33t:openai-python:fix/prepare-url-base-query
    Commit: bf1edff56f00ec77817185819940e526884a2518

    With base_url="https://proxy.example.com/v1?tenant=acme":

    • /models, no params
      • before: https://proxy.example.com/v1/?tenant=acmemodels
      • after: https://proxy.example.com/v1/models?tenant=acme
    • /models?after=m1, no params
      • before: https://proxy.example.com/v1/?tenant=acmemodels?after=m1
      • after: https://proxy.example.com/v1/models?tenant=acme&after=m1
    • /models?after=m1, params={"limit": "5"}
      • before: https://proxy.example.com/v1/?tenant=acmemodels%3Fafter%3Dm1&limit=5
      • after: https://proxy.example.com/v1/models?tenant=acme&after=m1&limit=5
    • /models, no params, base_url without a query: https://proxy.example.com/v1/models, unchanged

    The change is 8 lines in _prepare_url, using the same partition(b"?") pattern as _enforce_trailing_slash a few lines above:

             if merge_url.is_relative_url:
    -            merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/")
    -            return self.base_url.copy_with(raw_path=merge_raw_path)
    +            # `raw_path` includes any query string, so merge paths only and append queries.
    +            base_path, _, base_query = self.base_url.raw_path.partition(b"?")
    +            merge_path, _, merge_query = merge_url.raw_path.partition(b"?")
    +            query = b"&".join(part for part in (base_query, merge_query) if part)
    +            raw_path = base_path + merge_path.lstrip(b"/") + (b"?" + query if query else b"")
    +            return self.base_url.copy_with(raw_path=raw_path)

    Merge semantics here are the conservative ones: base query parameters are kept, then any query parameters from the relative url, joined with &. Duplicate keys are kept in that order rather than deduplicated. When call params are passed, _build_request folds the merged query into params as before, so the order there is base query, relative query, call params.

    Tests: added test_relative_request_url_preserves_base_query in tests/test_client.py beside the existing base_url tests, parametrized over the four rows above, all through _build_request.

    • RED on unmodified main: 3 failed, 1 passed (only the plain base_url case passes, as expected).
    • GREEN with the fix: 4 passed, 294 deselected.
    • Full tests/test_client.py: 296 passed, 2 skipped.
    • tests/lib/test_azure.py, tests/test_httpx2.py, tests/test_data_residency_regressions.py: 116 passed, 1 skipped.
    • ruff check and ruff format in check mode on both touched files: clean.

    One path I deliberately left alone: BaseAzureClient._prepare_url in src/openai/lib/azure.py does its own raw_path concatenation for the deployment path, so azure_endpoint="https://res.example.com/base?tenant=acme" plus a deployment still yields https://res.example.com/base?tenant=acme/openai/models. AzureOpenAI(base_url=...) does go through the fixed method. The same two line partition would fit there if you want it in the same change.

    AI assistance disclosure: reproduced, fixed, and tested with an AI coding agent, reviewed and pushed by me.

  3. 721189 commented on Nov 24, 2026

    @721189

    Additional review finding (separate from the reported BaseClient bug): static inspection of src/openai/lib/azure.py shows BaseAzureClient._prepare_url() independently builds merge_raw_path from self._azure_endpoint.raw_path.rstrip(b"/") + b"/openai/" + merge_url.raw_path.... Since raw_path includes the query string, an azure_endpoint such as https://resource.example.com/base?tenant=acme appears to have the same path/query concatenation defect when a deployment-based relative endpoint is prepared. This is a distinct code path from AzureOpenAI(base_url=...), which delegates to BaseClient._prepare_url(), so it may deserve a separate issue and regression test rather than expanding this fix. I have not executed a runtime reproduction for the Azure-specific path; this observation is from source inspection.

    AI-use disclosure: This review comment was prepared with AI assistance and submitted through the linked GitHub account. The account holder is responsible for validating the observation and any follow-up.

  4. Rewaskc02-lang commented on Nov 25, 2026

    @Rewaskc02-lang

    hello, maintainer can you assign it to me , i am looking forward to contribute.

  5. rdxrahul12 commented on Dec 2, 2026

    @rdxrahul12

    I will take this issue and submit a PR with the fix.

  6. rdxrahul12 commented on Dec 2, 2026

    @rdxrahul12

    Withdrawing my claim on this issue. I have a fix ready on my fork (rdxrahul12/openai-python, branch fix/prepare-url-query-params), but this repository only allows collaborators to open pull requests, so I cannot submit it upstream. The issue is available again for anyone who can open a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions