beta.agents: environments.files.upload() reuses a single Idempotency-Key across both Files API upload and environment staging POST requests
Mantenedores costumam responder em até 1 dia
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 3/5
- Tempo estimado
- 1-3 horas
- Facilidade para iniciantes
- 45/100
Direção de pesquisa
Start with upload() and async_upload() in src/openai/lib/beta/agents/_files.py, around lines 261-297, and compare them with _prepare_selection() near lines 100-103, which already rejects a reused Idempotency-Key. The tests test_preflight_all_files_before_upload and test_client_default_idempotency_key_is_rejected_for_batch show the expected pattern. Done means a ValueError is raised before any HTTP request when Idempotency-Key comes from extra_headers or default_headers, while Omit still clears a client default, with sync and async tests covering both.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
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
client.beta.agents.environments.files.upload() (upload() and async_upload() in src/openai/lib/beta/agents/_files.py:261-297) always performs two distinct POST requests using the same **options (forwarding both extra_headers and client default_headers unchanged):
POST /v1/files(resource._client.files.create(file=content, purpose="user_data", **options))POST /v1/agents/environments/{environment_id}/files(resource.create(environment_id, type="file_id", file_id=uploaded.id, path=destination, **options))
Unlike sibling environments.files.prepare() (_prepare_selection in src/openai/lib/beta/agents/_files.py:100-103, explicitly covered by test_preflight_all_files_before_upload and test_client_default_idempotency_key_is_rejected_for_batch), neither upload() nor async_upload() validates that an Idempotency-Key header is not present in extra_headers or resource._client.default_headers.
As a result, passing extra_headers={"Idempotency-Key": ...} (or calling upload() on a client configured with a default Idempotency-Key header) sends the exact same Idempotency-Key to both POST /v1/files and POST /v1/agents/environments/{environment_id}/files, causing a server-side idempotency conflict during staging after the file has already been uploaded (orphaning the uploaded file).
To Reproduce
- Call
client.beta.agents.environments.files.upload(...)(sync or async) withextra_headers={"Idempotency-Key": "idem-123"}or withIdempotency-Keyset in clientdefault_headers. - Inspect the two outgoing HTTP
POSTrequests. - Observe that no preflight
ValueErroris raised and bothPOST /v1/filesandPOST /v1/agents/environments/{environment_id}/filescarryIdempotency-Key: idem-123.
Code snippets
import httpx2
from openai import OpenAI
seen = []
def handle(request: httpx2.Request) -> httpx2.Response:
seen.append((request.method, request.url.path, request.headers.get("idempotency-key")))
if request.url.path.endswith("/files") and "environments" not in request.url.path:
return httpx2.Response(
200,
json={
"id": "file_1", "bytes": 3, "created_at": 1, "filename": "source.txt",
"object": "file", "purpose": "user_data", "status": "processed",
},
)
return httpx2.Response(
200,
json={
"id": "envfile_1", "object": "agent.environment.file",
"environment_id": "env_test", "path": "/workspace/source.txt", "size_bytes": 3, "created_at": 1,
},
)
with OpenAI(api_key="test", http_client=httpx2.Client(transport=httpx2.MockTransport(handle))) as client:
client.beta.agents.environments.files.upload(
"env_test",
file=("source.txt", b"abc"),
path="/workspace/source.txt",
extra_headers={"Idempotency-Key": "idem-123"},
)
for method, path, key in seen:
print(f"{method} {path} -> Idempotency-Key={key!r}")
Actual output:
POST /v1/files -> Idempotency-Key='idem-123'
POST /v1/agents/environments/env_test/files -> Idempotency-Key='idem-123'
Expected behavior:
Consistent with environments.files.prepare(), upload() and async_upload() should fail preflight with ValueError before sending any HTTP request when a single Idempotency-Key is supplied via extra_headers or client default_headers (while still allowing extra_headers={"Idempotency-Key": omit} to clear a client default header).
Suggested Fix
Extract a shared _reject_reused_idempotency_key(defaults, options, message) helper in src/openai/lib/beta/agents/_files.py and invoke it during preflight in _prepare_selection(), upload(), and async_upload():
def _reject_reused_idempotency_key(defaults: Headers, options: _RequestOptions, message: str) -> None:
headers = {key.lower(): value for key, value in defaults.items()}
headers.update({key.lower(): value for key, value in (options["extra_headers"] or {}).items()})
if "idempotency-key" in headers and not isinstance(headers["idempotency-key"], Omit):
raise ValueError(message)
(Verified locally with sync/async regression tests covering extra_headers, default_headers, and Omit overrides: 517 passed across tests/lib/streaming/agents/, tests/lib/beta/agents/test_tools.py, and tests/test_agents_budget_events.py, with ruff and pyright clean.)
OS
macOS
Python version
Python 3.14.8
Library version
openai v3.57.0 (main@f63f14b)
- Linguagem predominante
- Python
- Estrelas
- 32.2k
- Forks
- 5.8k
- Merge médio
- 12h 31min
- PRs com merge (30d)
- 101
Preparar o ambiente
Inicia o contêiner de desenvolvimento do projeto no navegador, com a sua própria conta do GitHub.
- Sem Dockerfile nem arquivo Docker Compose
- Tem um modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de openai/openai-python
-
`parse(to=A | None)` raises "Unsupported type" below Python 3.14 while `Union[A, None]` worksAberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
openai/openai-python#4339 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
openai/openai-python#4338 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
`DeprecationWarning` thrown when calling websockets (17.1 and later)Talvez já em andamento @akhil9tiet assumiu há 1 dia. Abertabug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
openai/openai-python#4337 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
`BaseClient._prepare_url()` corrupts relative endpoint URLs when `base_url` contains query parametersTalvez já em andamento @Rewaskc02-lang assumiu há 2 dias. Aberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
openai/openai-python#4311 · 4 comentários ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
openai/openai-python#4310 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
Todas as issues de openai/openai-python
Issues semelhantes
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 69/100
-
frontend testing
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 84/100
vendrabuck/HERD#1588 ·
Mantenedores costumam responder em até 1 dia
-
Lessons: record the second case of L14 (security updates cover only pip)Talvez já em andamento @vishwanathj assumiu hoje. Abertaarea/docs no-test-needed type/docs
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
vishwanathj/ocp_lab.ai#39 · 1 comentário ·
-
enhancement good first issue
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 88/100
laaielichter/Gulliver#228 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 68/100
Mantenedores costumam responder em até 1 dia