from openai import OpenAI from pydantic.typing import ( ImportError: cannot import name…
- User
from openai import OpenAI
from pydantic.typing import ( ImportError: cannot import name 'is_union' from 'pydantic.typing' (/XXX.10/site-packages/pydantic/typing.py)
- Assistant
That error happens because is_union was removed in Pydantic v2, but some libraries (like openai) still assume Pydantic v1. 👉 You have two options to fix it:
Option 1: Install Pydantic v1 (recommended for openai) The current openai Python package is written against Pydantic v1.x. bashCopy codepip install "pydantic<2"
This will downgrade you to a compatible version. You may also want to pin it: bashCopy codepip install "pydantic==1.10.14"
Option 2: Use the latest openai client that supports Pydantic v2 If you really need Pydantic v2 (maybe other packages depend on it), you should upgrade the openai client to the new unified version: bashCopy codepip install --upgrade openai
The latest openai package (>=1.0.0) no longer depends on pydantic.typing.is_union. But note: it has a new API style, so instead of: pythonCopy codefrom openai import OpenAI client = OpenAI()
you’ll now use: pythonCopy codeimport openai client = openai.OpenAI()
✅ So the quick fix: If you want to keep your current code as-is → downgrade Pydantic. If you don’t mind adapting to the new API → upgrade OpenAI.
Do you want me to adjust your code snippet to work with the new OpenAI client (so you can stay on Pydantic v2), or do you prefer the safer route of downgrading Pydantic?