DEV Community

tunan666
tunan666

Posted on

Build a Chatbot with DeepSeek V4 in 5 Minutes (Python Tutorial)

Build a Chatbot with DeepSeek V4 in 5 Minutes (Python Tutorial)

Want to add AI chat to your app without the $10/M token bill? DeepSeek V4 delivers GPT-4-level performance at $0.70/$1.40 per million tokens. Here's how to build a working chatbot in 5 minutes.


Why DeepSeek V4?

DeepSeek V4 is underpriced. The model performs competitively with GPT-4o on coding and reasoning tasks, yet costs roughly 14x less on input tokens and 7x less on output tokens. But here's the catch for international developers: accessing DeepSeek's API from outside China requires a Chinese phone number and payment method. That's where TunanAPI comes in.

In this tutorial, we'll build a complete chatbot using Python and the OpenAI SDK.


What We're Building

By the end of this tutorial, you'll have:

  1. A Python chatbot that connects to DeepSeek V4
  2. Streaming responses (token-by-token display)
  3. Conversation history (multi-turn chat)
  4. A clean CLI interface anyone can use

Prerequisites:

  • Python 3.8+
  • An API key from tunanapi.com (free tier: 500K tokens)
  • 5 minutes

Step 1: Install Dependencies

pip install openai python-dotenv
Enter fullscreen mode Exit fullscreen mode

Step 2: Get Your API Key

  1. Go to tunanapi.com
  2. Sign up (free, no Chinese phone number required)
  3. Copy your API key

Create a .env file:

TUNAN_API_KEY=your-key-here
Enter fullscreen mode Exit fullscreen mode

Step 3: Build the Chatbot

Create chatbot.py:

import os
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()
api_key = os.getenv("TUNAN_API_KEY")

client = OpenAI(
    api_key=api_key,
    base_url="https://api.tunanapi.com/v1"
)

MODELS = {
    "fast": "deepseek-chat",
    "pro": "deepseek-reasoner",
}

def chat(model="fast", system_prompt="You are a helpful assistant."):
    messages = [{"role": "system", "content": system_prompt}]
    print(f"🤖 Chatbot ready (model: {model})")
    print("Type 'quit' to exit, 'clear' to reset conversation\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() == "quit":
            print("Goodbye!")
            break
        if user_input.lower() == "clear":
            messages = [{"role": "system", "content": system_prompt}]
            print("Conversation cleared.\n")
            continue
        if not user_input:
            continue

        messages.append({"role": "user", "content": user_input})

        try:
            response = client.chat.completions.create(
                model=MODELS[model],
                messages=messages,
                stream=True,
                temperature=0.7,
                max_tokens=2000
            )

            print("Assistant: ", end="", flush=True)
            assistant_message = ""
            for chunk in response:
                if chunk.choices[0].delta.content:
                    token = chunk.choices[0].delta.content
                    print(token, end="", flush=True)
                    assistant_message += token
            print("\n")

            messages.append({"role": "assistant", "content": assistant_message})
        except Exception as e:
            print(f"Error: {e}\n")

if __name__ == "__main__":
    import sys
    model = sys.argv[1] if len(sys.argv) > 1 else "fast"
    chat(model=model)
Enter fullscreen mode Exit fullscreen mode

Step 4: Run It

python chatbot.py
Enter fullscreen mode Exit fullscreen mode

Sample output:

🤖 Chatbot ready (model: fast)
You: Explain quantum entanglement
Assistant: Quantum entanglement is like having two coins that always land the same way—no matter how far apart they are.
You: quit
Goodbye!
Enter fullscreen mode Exit fullscreen mode

Compare the Costs

Provider Model Input Output 1K queries/day
TunanAPI DeepSeek V4 $0.70 $1.40 ~$12/month
OpenAI GPT-4o $2.50 $10.00 ~$180/month
Anthropic Claude 3.5 $3.00 $15.00 ~$270/month

Savings: 90%+ compared to premium tier


What's Next?

  1. Add more models — Switch between DeepSeek, Qwen, GLM with one line change
  2. Build a web UI — Use Streamlit, Gradio, or Flask
  3. Add RAG — Connect to a vector database
  4. Deploy — Host on Railway, Render, or Vercel

Get Started

  1. Get your free API key: tunanapi.com
  2. 500K tokens free, no credit card required
  3. Full code on GitHub: github.com/tunanapi/examples

This tutorial uses TunanAPI to access Chinese AI models.

Top comments (0)