Step 1: PyCharm environment preparation
1. Create a new project
Open PyCharm → New Project → Select a pure Python project → Specify project path → Create a virtual environment (Virtualenv is recommended).
2. Install the dependency library
Open a terminal (Terminal) and execute the following command:
pip install requests python-dotenv
- requests: Used to send HTTP requests to the DeepSeek API.
- python-dotenv: manage environment variables (protect API Key).
Step 2: Configure API Key and Environment Variables
1. Get the DeepSeek API Key
Log in to the DeepSeek Developer Platform → Create an Application → Get API Key (usually a string like ds-xxxxxxxxxxxxxxxxxxxxxxxx).
2. Create .env file
Right-click in the project root directory → New → File → Enter .env → Add content:
DEEPSEEK_API_KEY=yourAPI_Key DEEPSEEK_API_ENDPOINT=/v1/chat/completions # Adjust according to actual API documentation
3. Add .env to .gitignore
Avoid submitting sensitive information to the repository.
Step 3: Write API request code
Create a new Python file
For example, deepseek_client.py, write the following code:
import os import requests from dotenv import load_dotenv # Loading environment variablesload_dotenv() class DeepSeekClient: def __init__(self): self.api_key = ("DEEPSEEK_API_KEY") = ("DEEPSEEK_API_ENDPOINT") = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } def generate_response(self, prompt, model="deepseek-chat", max_tokens=500): payload = { "model": model, "messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens, "temperature": 0.7 } try: response = (, json=payload, headers=) response.raise_for_status() # Check for HTTP errors return ()["choices"][0]["message"]["content"] except as e: return f"APIRequest failed: {str(e)}" except KeyError: return "An error occurred while parsing the response" # Example usageif __name__ == "__main__": client = DeepSeekClient() prompt = "Writing a quick sorting algorithm in Python" response = client.generate_response(prompt) print("DeepSeek Response:\n", response)
Step 4: Debugging and testing
Run the code
Right-click on the code editor → Run 'deepseek_client.py' → Observe the console output.
Frequently Asked Questions
401 Unauthorized: Check whether the API Key is correct and whether the environment variable is loading.
429 Too many requests: confirm the rate limit of the API and increase the latency appropriately.
Response format error: Adjust the parsing logic of () based on the actual API documentation
Step 5: Integrate into the actual project
1. Package as a module
Move the DeepSeekClient class to a standalone module (such as utils/) and call it through the from import DeepSeekClient.
2. Asynchronous request optimization
If you need high performance, use the aiohttp library to implement asynchronous requests instead
pip install aiohttp
import aiohttp import asyncio async def async_generate_response(self, prompt): async with () as session: async with ( , json=payload, headers= ) as response: return await ()
3. Logging
Add log function to track API calls:
import logging (level=)
Step 6: Advanced Feature Extensions
1. Streaming
If the API supports streaming response, modify the code to receive data block by block:
def stream_response(self, prompt): payload["stream"] = True response = (, json=payload, headers=, stream=True) for chunk in response.iter_lines(): if chunk: print(("utf-8"))
2. File interaction
To implement file upload/download (such as document Q&A scenarios), you need to refer to the API document processing multipart/form-data.
PyCharm debugging skills
1. Environment variable configuration
If .env is not used, you can set it manually in PyCharm:
Run → Edit Configurations → Environment variables → Add DEEPSEEK_API_KEY=your Key.
Client Testing
Test the API directly using PyCharm's built-in HTTP Client (.http file):
POST {{DEEPSEEK_API_ENDPOINT}} Content-Type: application/json Authorization: Bearer {{DEEPSEEK_API_KEY}} { "model": "deepseek-chat", "messages": [{"role": "user", "content": "Hello"}] }
Things to note
1. Cost control
Monitor the number of API calls and token consumption to avoid excessive fees (some platforms provide free quotas).
2. Error retry mechanism
Add retry logic (such as the tenacity library) to deal with temporary network problems:
pip install tenacity
from tenacity import retry, stop_after_attempt, wait_exponential @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10)) def generate_response(self, prompt): # Original code
3. Compliance
Comply with DeepSeek's Terms of Use to avoid generating harmful content.
—Through the above steps, you can efficiently connect to the DeepSeek big model in PyCharm and expand functions according to your needs.
The above is the detailed content of the operation process of PyCharm docking DeepSeek big model. For more information about PyCharm docking DeepSeek, please follow my other related articles!