DEV Community

ChinaWHAPI Team
ChinaWHAPI Team

Posted on

How to Use DeepSeek API in Python - Complete Developer Guide

Introduction

DeepSeek is one of the most powerful Chinese LLM models available today. In this tutorial, I'll show you how to integrate DeepSeek API into your Python applications using an OpenAI-compatible interface.

Prerequisites

  • Python 3.7+
  • A ChinaWHAPI account (get free credits at signup)
  • Basic understanding of REST APIs

Installation

First, install the required packages:

pip install openai requests
Enter fullscreen mode Exit fullscreen mode

Setting Up Your API Key

  1. Sign up at ChinaWHAPI
  2. Navigate to Dashboard → API Keys
  3. Create a new API key
  4. Copy and save your API key securely

Basic Usage Example

from openai import OpenAI

client = OpenAI(
    api_key="your-api-key",
    base_url="https://api.chinawhapi.com/v1"
)

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {"role": "user", "content": "Hello, how are you?"}
    ]
)

print(response.choices[0].message.content)
Enter fullscreen mode Exit fullscreen mode

Streaming Responses

from openai import OpenAI

client = OpenAI(
    api_key="your-api-key",
    base_url="https://api.chinawhapi.com/v1"
)

stream = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
Enter fullscreen mode Exit fullscreen mode

Error Handling

from openai import OpenAI, APIError

client = OpenAI(
    api_key="your-api-key",
    base_url="https://api.chinawhapi.com/v1"
)

try:
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[{"role": "user", "content": "Hello"}]
    )
    print(response.choices[0].message.content)
except APIError as e:
    print(f"API Error: {e}")
Enter fullscreen mode Exit fullscreen mode

Cost Optimization Tips

  1. Use appropriate model for your use case
  2. Implement token limits
  3. Cache frequent responses
  4. Monitor usage in dashboard

Conclusion

ChinaWHAPI provides an OpenAI-compatible interface that makes it easy to switch from OpenAI to Chinese LLMs like DeepSeek, Qwen, Kimi, and GLM with minimal code changes.

Get started with $10 free credits at ChinaWHAPI!

Top comments (0)