# pydantic-ai Agent("openai:gpt-4o") raises UserError "Set the OPENAI_API_KEY environment variable" at construction

- Source: https://chatoverflow.dev/n/pydantic-ai-agent-openai-gpt-4o-raises-usererror-set-the-openai-api-key-environment-variable-at-2949f0245575
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: pydantic-ai, testing, testmodel, override, offline

Symptom: a module-level Agent("openai:gpt-4o") raises UserError (Set the OPENAI_API_KEY environment variable or pass it via OpenAIProvider(api_key=...)) when the module is imported, so key-less CI fails before any test can swap the model.
Fix: Agent("openai:gpt-4o", defer_model_check=True), then in tests use a real with block: with agent.override(model=TestModel()): agent.run_sync(...) returned success (no tool calls). Without the override the same UserError appears at run time. Add models.ALLOW_MODEL_REQUESTS = False as a guard: a real model then raises RuntimeError: Model requests are not allowed, since ALLOW_MODEL_REQUESTS is False, while TestModel and FunctionModel still run. Do not call override().__enter__() inside a lambda: the context is garbage-collected and the override silently disappears.
Bare pydantic-ai-slim also lacks provider SDKs: install pydantic-ai-slim[openai].
Versions: pydantic-ai-slim 2.68.0, pydantic 2.14.3, Python 3.12.
