This tutorial will walk you through adding artificial intelligence capabilities to your Python applications using DeepSeek's API. No prior AI experience required - we'll explain every concept in simple terms!
We'll use two Python packages:
# Run in your terminal
pip install requests python-dotenv
Never store API keys directly in code. We'll use environment variables through a .env
file:
# Create .env file
DEEPSEEK_API_KEY = "your-actual-key-here"
This code establishes secure communication with DeepSeek's servers. The headers
contain authentication, while data
holds your request details.
import os
import requests
from dotenv import load_dotenv
load_dotenv() # Load environment variables
def ask_deepseek(question: str) -> str:
# Set up request headers
headers = {
"Authorization": f"Bearer {os.getenv('DEEPSEEK_API_KEY')}",
"Content-Type": "application/json"
}
# Prepare request body
data = {
"prompt": question,
"max_tokens": 150 # Limit response length
}
# Send POST request
response = requests.post(
"https://api.deepseek.com/v1/chat/completions",
headers=headers,
json=data
)
# Extract and return response text
return response.json()['choices'][0]['text']
This function creates a continuous conversation loop that:
def start_chat():
print("DeepSeek Chat Assistant (type 'exit' to quit)")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
break
response = ask_deepseek(user_input)
print(f"AI: {response}")
if __name__ == "__main__":
start_chat()
Network requests can fail for various reasons. This wrapper function:
import time
from typing import Optional
def safe_ask(prompt: str, max_retries=3) -> Optional[str]:
for attempt in range(max_retries):
try:
return ask_deepseek(prompt)
except requests.exceptions.RequestException as e:
print(f"Error: {e}. Retrying ({attempt+1}/{max_retries})...")
time.sleep(2)
print("Failed after multiple attempts")
return None
The lru_cache
decorator remembers previous responses to:
from functools import lru_cache
@lru_cache(maxsize=100)
def cached_ask(prompt: str) -> str:
return safe_ask(prompt)
You've now built a fully functional AI-integrated Python application! Remember to handle API keys securely and monitor your usage through DeepSeek's dashboard.
Category: deepseek
Similar Articles