How to use DeepSeek R1 for math problems
Quick answer
Use the
deepseek-reasoner model via the OpenAI-compatible API by setting base_url to DeepSeek's endpoint and calling chat.completions.create with math problem prompts. This leverages DeepSeek R1's advanced reasoning capabilities specialized for math and logic tasks.PREREQUISITES
Python 3.8+DeepSeek API keypip install openai>=1.0
Setup
Install the openai Python package and set your DeepSeek API key as an environment variable. Use the DeepSeek API base URL to access the deepseek-reasoner model.
pip install openai>=1.0 Step by step
This example shows how to send a math problem prompt to DeepSeek R1 and print the reasoning answer.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["DEEPSEEK_API_KEY"], base_url="https://api.deepseek.com")
response = client.chat.completions.create(
model="deepseek-reasoner",
messages=[{"role": "user", "content": "Solve the equation: 3x + 5 = 20. What is x?"}]
)
print("Answer:", response.choices[0].message.content) output
Answer: x = 5
Common variations
- Use different math prompts like calculus or probability questions.
- Switch to
deepseek-chatfor general-purpose chat if reasoning is not required. - Implement async calls using
asyncioand the OpenAI SDK's async methods.
import asyncio
import os
from openai import OpenAI
async def main():
client = OpenAI(api_key=os.environ["DEEPSEEK_API_KEY"], base_url="https://api.deepseek.com")
response = await client.chat.completions.acreate(
model="deepseek-reasoner",
messages=[{"role": "user", "content": "Integrate x^2 dx."}]
)
print("Answer:", response.choices[0].message.content)
asyncio.run(main()) output
Answer: The integral of x^2 dx is (1/3)x^3 + C
Troubleshooting
- If you get authentication errors, verify your
DEEPSEEK_API_KEYenvironment variable is set correctly. - For timeout errors, check your network connection and retry.
- If the model returns irrelevant answers, ensure you are using
deepseek-reasonerfor math reasoning tasks.
Key Takeaways
- Use the OpenAI-compatible SDK with
base_url="https://api.deepseek.com"to access DeepSeek R1. - The
deepseek-reasonermodel excels at math and logical reasoning problems. - Always set your API key in
os.environ["DEEPSEEK_API_KEY"]for secure authentication.