This tutorial provides a complete, production-ready Python script for generating content in batches using the DeepSeek API. It incorporates best practices
This tutorial provides a complete, production-ready Python script for generating content in batches using the DeepSeek API. It incorporates best practices for interacting with external APIs, including robust error handling, exponential backoff with retries, and clear configuration.
Generating a large volume of unique content, descriptions, or creative text snippets using AI models can be a challenging task. When dealing with hundreds or thousands of prompts, developers often face several issues:
This script addresses these problems by providing an automated, resilient solution to generate content from a list of prompts, ensuring high reliability and efficient resource utilization.
The script is designed for robustness and ease of use. At its core, it leverages the openai Python client library (which is compatible with DeepSeek's API) to send chat completion requests. For resilience against transient failures and rate limits, it integrates the tenacity library, which automatically handles retries with an exponential backoff strategy.
The workflow is as follows:
--limit argument.generate_content_with_retry) is called. This function is decorated with @retry from tenacity, which means if an openai.APIError occurs (e.g., due to a rate limit or server error), the request will be automatically retried after an increasing delay, up to a configured maximum number of attempts.This architecture ensures that the content generation process is largely self-sufficient, capable of recovering from common API interaction issues, and provides clear insights into its operation.
#!/usr/bin/env python3
"""
DeepSeek API Batch Content Generator
This script generates content in batches using the DeepSeek API.
It processes a list of prompts, handles API rate limits and transient errors
with exponential backoff and retries, and saves the generated responses
to individual files in a specified output directory.
"""
import os
import argparse
import logging
import json
import time
from typing import List, Dict, Any, Optional
from openai import OpenAI, APIError
from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception_type
# --- Configuration ---
# DeepSeek API Key (required)
# It's recommended to set this as an environment variable for security.
DEEPSEEK_API_KEY: str = os.environ.get("DEEPSEEK_API_KEY", "")
if not DEEPSEEK_API_KEY:
raise ValueError("DEEPSEEK_API_KEY environment variable not set. Please set it to your DeepSeek API key.")
# DeepSeek Base URL (default for DeepSeek chat models)
DEEPSEEK_BASE_URL: str = os.environ.get("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
# DeepSeek Model to use for content generation
DEEPSEEK_MODEL: str = os.environ.get("DEEPSEEK_MODEL", "deepseek-chat")
# Default output directory for generated content files
DEFAULT_OUTPUT_DIR: str = os.environ.get("OUTPUT_DIR", "generated_content")
# Retry configuration for API calls using tenacity
MAX_RETRIES: int = int(os.environ.get("MAX_RETRIES", 5))
INITIAL_RETRY_DELAY_SEC: float = float(os.environ.get("INITIAL_RETRY_DELAY_SEC", 1.0))
MAX_RETRY_DELAY_SEC: float = float(os.environ.get("MAX_RETRY_DELAY_SEC", 60.0))
API_TIMEOUT_SEC: float = float(os.environ.get("API_TIMEOUT_SEC", 60.0))
# --- Logging Setup ---
# Configure logging to output to both a file and the console
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("batch_ai_generator.log"), # Log to a file
logging.StreamHandler() # Log to console
]
)
logger = logging.getLogger(__name__)
# --- API Client Initialization ---
# Initialize the OpenAI client, pointing its base_url to DeepSeek's API endpoint.
# This client is used for all API interactions.
client = OpenAI(
api_key=DEEPSEEK_API_KEY,
base_url=DEEPSEEK_BASE_URL,
timeout=API_TIMEOUT_SEC # Set a reasonable timeout for API requests
)
# --- Core Logic ---
@retry(
wait=wait_exponential(multiplier=INITIAL_RETRY_DELAY_SEC, min=1, max=MAX_RETRY_DELAY_SEC),
stop=stop_after_attempt(MAX_RETRIES),
retry=retry_if_exception_type(APIError),
reraise=True # Re-raise the last exception if all retries fail, for main() to catch
)
def generate_content_with_retry(prompt: str, model: str) -> Optional[str]:
"""
Generates content using the DeepSeek API, incorporating robust retry