DEV Community

jianjun Liu
jianjun Liu

Posted on

Build a $0.50/M Kimi K3 Chatbot in 10 Minutes (Full Code)

Build a $0.50/M Kimi K3 Chatbot in 10 Minutes

Kimi K3 just hit #1 on LMArena at $0.50/M tokens. Here's a full working chatbot you can deploy in 10 minutes.

What we're building

A web-based chatbot that:

  • Uses Kimi K3 via TokenEase API
  • Streams responses (token-by-token)
  • Remembers conversation history
  • Costs ~$0.50 per 1M input tokens
  • Total code: ~80 lines

Step 1: Get your API key (60 seconds)

Go to https://tokenease.io/api/register and register with email. You get $1 in free credits (1M tokens, 14 days). No credit card needed.

Step 2: Install dependencies

pip install flask openai
Enter fullscreen mode Exit fullscreen mode

Step 3: The backend (Python + Flask)

Create app.py:

from flask import Flask, request, jsonify, render_template_string
from openai import OpenAI
import os

app = Flask(__name__)

# TokenEase is OpenAI-compatible
client = OpenAI(
    api_key=os.environ.get("TOKEN_KEY", "your-key-here"),
    base_url="https://tokenease.io/v1"
)

HTML = '''
<!DOCTYPE html>
<html>
<head>
<title>K3 Chatbot</title>
<style>
body { font-family: system-ui; max-width: 800px; margin: 40px auto; padding: 20px; }
#chat { height: 500px; overflow-y: scroll; border: 1px solid #ccc; padding: 20px; border-radius: 8px; }
.msg { margin: 10px 0; padding: 10px; border-radius: 8px; }
.user { background: #007bff; color: white; margin-left: 20%; }
.bot { background: #f1f3f5; margin-right: 20%; }
input { width: 80%; padding: 10px; font-size: 16px; }
button { padding: 10px 20px; font-size: 16px; background: #007bff; color: white; border: none; border-radius: 4px; }
</style>
</head>
<body>
<h1>🤖 Kimi K3 Chatbot</h1>
<p>Powered by <a href="https://tokenease.io">TokenEase</a> · $0.50/M tokens · Free trial available</p>
<div id="chat"></div>
<input id="input" placeholder="Ask anything..." autofocus>
<button onclick="send()">Send</button>
<script>
const chat = document.getElementById('chat');
const input = document.getElementById('input');
const history = [];

function add(role, text) {
    const div = document.createElement('div');
    div.className = 'msg ' + role;
    div.textContent = text;
    chat.appendChild(div);
    chat.scrollTop = chat.scrollHeight;
}

async function send() {
    const msg = input.value.trim();
    if (!msg) return;
    add('user', msg);
    input.value = '';
    history.push({role: 'user', content: msg});

    const res = await fetch('/chat', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({messages: history})
    });
    const data = await res.json();
    add('bot', data.reply);
    history.push({role: 'assistant', content: data.reply});
}

input.addEventListener('keypress', e => { if (e.key === 'Enter') send(); });
add('bot', 'Hi! I am Kimi K3. Ask me anything.');
</script>
</body>
</html>
'''

@app.route('/')
def home():
    return render_template_string(HTML)

@app.route('/chat', methods=['POST'])
def chat():
    messages = request.json.get('messages', [])
    try:
        response = client.chat.completions.create(
            model='kimi-k3',
            messages=messages,
            max_tokens=2000  # K3 needs more for reasoning
        )
        reply = response.choices[0].message.content
        return jsonify({'reply': reply})
    except Exception as e:
        return jsonify({'reply': f'Error: {str(e)}'}), 500

if __name__ == '__main__':
    app.run(debug=True, port=5000)
Enter fullscreen mode Exit fullscreen mode

Step 4: Run it

export TOKEN_KEY="your-tokenease-api-key"
python app.py
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:5000. Done.

Cost breakdown

For 1000 conversations per day, each ~500 tokens in + 500 out:

  • Input: 500K tokens × $0.50/M = $0.25/day
  • Output: 500K tokens × $2.00/M = $1.00/day
  • Total: $1.25/day = $37.50/month

Compare to GPT-5:

  • Same usage: $15 × 0.5 + $60 × 0.5 = $37.50/day = $1,125/month

K3 saves you $1,087/month at the same quality on most tasks.

Why this works

  • K3 is a reasoning model — it "thinks" before answering, so responses are more accurate
  • OpenAI-compatible API — drop-in replacement for any OpenAI client
  • Streaming — add stream=True for real-time token display
  • Memory — the history array keeps conversation context

Add streaming (optional)

Change the /chat endpoint:

@app.route('/chat', methods=['POST'])
def chat():
    messages = request.json.get('messages', [])
    def generate():
        response = client.chat.completions.create(
            model='kimi-k3',
            messages=messages,
            max_tokens=2000,
            stream=True
        )
        for chunk in response:
            if chunk.choices[0].delta.content:
                yield chunk.choices[0].delta.content
    return Response(generate(), mimetype='text/plain')
Enter fullscreen mode Exit fullscreen mode

Add conversation history persistence

Replace in-memory history with Redis or a database. For production, add:

  • Rate limiting (TokenEase: 60 req/min on free tier)
  • User authentication
  • Cost tracking per user

Production tips

  1. Use environment variables for the API key, never hardcode
  2. Add error handling for rate limits and timeouts
  3. Stream responses for better UX on long outputs
  4. Cache common responses to reduce costs
  5. Monitor token usage in TokenEase dashboard

Try it

Free trial: https://tokenease.io/api/register ($1 credit, 1M tokens, 14 days)

Full code above is copy-paste ready. No Chinese phone number required. No VPN needed.


Disclaimer: I work on TokenEase. The pricing above is current as of July 2026.

Top comments (0)