How to migrate from OpenAI to DeepSeek
Quick answer
To migrate from OpenAI to DeepSeek, replace the OpenAI client with the OpenAI client configured to use DeepSeek's base_url. Update your API key environment variable and use the same chat.completions.create method with DeepSeek's model names like deepseek-chat. This allows a smooth transition with minimal code changes.
PREREQUISITES
Python 3.8+OpenAI API key (works for DeepSeek)pip install openai>=1.0DeepSeek API access (API key)
Setup
Install the official openai Python SDK version 1.0 or higher, which supports DeepSeek via custom base_url. Set your DeepSeek API key in the environment variable DEEPSEEK_API_KEY.
Run:
pip install openai>=1.0 Step by step
Use the OpenAI client from the openai package, but specify DeepSeek's API endpoint via base_url. Replace your OpenAI model with DeepSeek's deepseek-chat. The rest of the chat completion call remains the same.
import os
from openai import OpenAI
# Initialize DeepSeek client with base_url override
client = OpenAI(api_key=os.environ["DEEPSEEK_API_KEY"], base_url="https://api.deepseek.com")
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": "Hello from DeepSeek!"}]
)
print(response.choices[0].message.content) output
Hello from DeepSeek! How can I assist you today?
Common variations
You can switch models by changing the model parameter to other DeepSeek models like deepseek-reasoner. Async calls are not natively supported in the OpenAI SDK, but you can run calls in async frameworks using threads or asyncio wrappers. Streaming is not currently supported by DeepSeek's API.
Troubleshooting
- If you get authentication errors, verify your
DEEPSEEK_API_KEYenvironment variable is set correctly. - If requests time out, check your network and DeepSeek service status.
- For unexpected errors, confirm you are using the latest
openaiSDK and the correctbase_url.
Key Takeaways
- Use the OpenAI SDK with the DeepSeek API by setting the base_url to https://api.deepseek.com.
- Replace OpenAI model names with DeepSeek models like deepseek-chat for compatibility.
- Keep your API key in the environment variable DEEPSEEK_API_KEY for security.
- DeepSeek supports the same chat.completions.create method, enabling minimal code changes.
- Check network and API key if you encounter authentication or timeout errors.