OpenAIConversationsSession and OpenAIResponsesCompactionSession ignore set_default_openai_key()

Abierto Apto para principiantes
#5,471 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
78/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python
Área
backend

Línea de trabajo

Empieza en src/agents/memory/openai_conversations_session.py, donde se construye el AsyncOpenAI() de respaldo cerca de las líneas 21 y 50. Luego revisa src/agents/memory/openai_responses_compaction_session.py alrededor de la línea 196 y src/agents/models/openai_provider.py para ver el patrón get_default_openai_key() que hay que copiar. Ejecuta el script de reproducción del issue en ambas fases y después tests/memory. Está terminado cuando ambas sesiones reportan la clave de set_default_openai_key(), tanto si OPENAI_API_KEY está definida como si no.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Please read this first
  • Have you read the docs? Yes
  • Have you searched for related issues? Yes. Nothing covers it. #2164 is a feature request for several keys per run.
Describe the bug

set_default_openai_key() is documented as the key that "will be used instead of the OPENAI_API_KEY environment variable". OpenAIProvider honors it, and so do the voice provider and the Codex tool. OpenAIConversationsSession and OpenAIResponsesCompactionSession don't. When no default client is set, they build a bare AsyncOpenAI(), which reads only OPENAI_API_KEY. That causes two problems:

  • When the key is set only through the SDK, OpenAIConversationsSession() raises OpenAIError: Missing credentials when it's constructed, and the compaction session raises on its first responses.compact call.
  • When OPENAI_API_KEY is also set, the sessions quietly use the environment key while model calls use the SDK key. Conversation items and the billed responses.compact calls land in a different project or org than the run's responses.
Debug information
  • Agents SDK version: main (e355d69), also 0.24.0
  • Related library versions: openai 3.29.0
  • Python version: 3.14.7
  • Operating system: macOS
  • Model and model provider: OpenAI
  • Does the issue reproduce with the latest Agents SDK release? Yes
  • Does the issue occur consistently or intermittently? Consistently
Repro steps
import os
os.environ.pop("OPENAI_API_KEY", None)  # key is configured only through the SDK

from agents import SQLiteSession, set_default_openai_key
from agents.memory import OpenAIConversationsSession, OpenAIResponsesCompactionSession
from agents.models.multi_provider import MultiProvider

set_default_openai_key("sk-from-set-default-openai-key")

def show(label, make):
    try:
        print(f"{label}:", make().api_key)
    except Exception as e:
        print(f"{label}:", type(e).__name__, "-", str(e)[:40])

for phase in ("SDK key only", "OPENAI_API_KEY also set"):
    if phase == "OPENAI_API_KEY also set":
        os.environ["OPENAI_API_KEY"] = "sk-other-project-from-env"
    print("--", phase)
    print("model client        :", MultiProvider().get_model("gpt-4.1")._client.api_key)
    show("ConversationsSession", lambda: OpenAIConversationsSession()._openai_client)
    show("CompactionSession   ", lambda: OpenAIResponsesCompactionSession("s", SQLiteSession("s")).client)
-- SDK key only
model client        : sk-from-set-default-openai-key
ConversationsSession: OpenAIError - Missing credentials. Please pass a
CompactionSession   : OpenAIError - Missing credentials. Please pass a
-- OPENAI_API_KEY also set
model client        : sk-from-set-default-openai-key
ConversationsSession: sk-other-project-from-env
CompactionSession   : sk-other-project-from-env
Expected behavior

With no client passed and no default client set, both sessions use the key from set_default_openai_key(), as model calls do.

Root cause and a possible fix

The sessions fall back to AsyncOpenAI(): openai_conversations_session.py#L21, #L50 and openai_responses_compaction_session.py#L196. The provider passes get_default_openai_key() instead (openai_provider.py#L156-L161).

--- a/src/agents/memory/openai_conversations_session.py
+++ b/src/agents/memory/openai_conversations_session.py
-from agents.models._openai_shared import get_default_openai_client
+from agents.models._openai_shared import get_default_openai_client, get_default_openai_key
@@ async def start_openai_conversations_session(
-        _maybe_openai_client = default_client if default_client is not None else AsyncOpenAI()
+        _maybe_openai_client = (
+            default_client
+            if default_client is not None
+            else AsyncOpenAI(api_key=get_default_openai_key())
+        )
@@ class OpenAIConversationsSession(SessionABC):
-            _openai_client = default_client if default_client is not None else AsyncOpenAI()
+            _openai_client = (
+                default_client
+                if default_client is not None
+                else AsyncOpenAI(api_key=get_default_openai_key())
+            )
--- a/src/agents/memory/openai_responses_compaction_session.py
+++ b/src/agents/memory/openai_responses_compaction_session.py
-from ..models._openai_shared import get_default_openai_client
+from ..models._openai_shared import get_default_openai_client, get_default_openai_key
@@ def client(self) -> AsyncOpenAI:
-            self._client = default_client if default_client is not None else AsyncOpenAI()
+            self._client = (
+                default_client
+                if default_client is not None
+                else AsyncOpenAI(api_key=get_default_openai_key())
+            )

AsyncOpenAI(api_key=None) still falls back to OPENAI_API_KEY, so nothing changes for callers who haven't set a default key. With the patch, both sessions report the SDK key in both phases, and tests/memory passes (444 passed).

Lenguaje dominante
Python
Estrellas
30.5k
Forks
5k
Merge medio
22 h 21 min
PR fusionados (30 d)
98

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de openai/openai-agents-python

Todos los issues de openai/openai-agents-python

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.