AiCredits
Flask + AI

How to Add AI Chat to a Flask App in 30 Minutes (Streaming Python)

Build a streaming AI chat endpoint in Flask in 30 minutes: app.py, SSE frontend, conversation memory, and production hardening — with runnable Python code.

Published 2026-09-21 Updated 2026-09-21 7 min

What You Can Actually Build in 30 Minutes

Adding AI chat to Flask is mostly plumbing. The model call itself is about ten lines with the official OpenAI SDK; everything else is a route, a streaming response, and a fetch loop in the browser. You can have a working prototype in half an hour and then spend your real time on the parts that break in production — conversation memory, key handling, and streams that die mid-sentence.

This walkthrough builds a token-by-token streaming chat endpoint against DeepSeek models through AiCredits, an OpenAI-compatible gateway you can pay for with an international card or PayPal. No JS framework, no database, two files plus a .env.

Step 1 — Project Setup

mkdir flask-chat && cd flask-chat
python -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install flask openai python-dotenv

Flask expects your templates in a folder called templates, so create this layout:

flask-chat/
├── app.py
├── .env
└── templates/
    └── index.html

Your .env holds the only secret in the project:

AICREDITS_API_KEY=your_key_here

Keep that key on the server. Every model call goes through your Flask route, so the browser never sees it.

Step 2 — The Flask Backend

Here is the complete server. It streams server-sent events so users watch words appear instead of staring at a spinner:

import json
import os

from dotenv import load_dotenv
from flask import Flask, Response, jsonify, render_template, request
from openai import OpenAI

load_dotenv()

app = Flask(__name__)

client = OpenAI(
    api_key=os.environ['AICREDITS_API_KEY'],
    base_url='https://api.aicreditsapi.com/v1',
    timeout=60.0,
    max_retries=2,
)

SYSTEM_PROMPT = (
    'You are a concise assistant embedded in a Flask app. '
    'Reply in plain text and keep answers under 150 words unless asked for detail.'
)

MAX_TURNS = 10


def sanitize_history(raw):
    """Keep only valid user/assistant turns; drop a leading assistant turn."""
    clean = []
    for turn in (raw or [])[-MAX_TURNS:]:
        if not isinstance(turn, dict):
            continue
        role = turn.get('role')
        content = (turn.get('content') or '').strip()
        if role in ('user', 'assistant') and content:
            clean.append({'role': role, 'content': content})
    while clean and clean[0]['role'] == 'assistant':
        clean.pop(0)
    return clean


@app.get('/')
def index():
    return render_template('index.html')


@app.post('/api/chat')
def chat():
    payload = request.get_json(silent=True) or {}
    message = (payload.get('message') or '').strip()
    if not message:
        return jsonify({'error': 'message is required'}), 400

    messages = [{'role': 'system', 'content': SYSTEM_PROMPT}]
    messages += sanitize_history(payload.get('history'))
    messages.append({'role': 'user', 'content': message})

    def generate():
        try:
            stream = client.chat.completions.create(
                model='deepseek-v4-flash',
                messages=messages,
                stream=True,
            )
            for chunk in stream:
                if not chunk.choices:
                    continue
                delta = chunk.choices[0].delta.content
                if delta:
                    yield 'data: ' + json.dumps({'delta': delta}) + '\n\n'
        except Exception:
            yield 'data: ' + json.dumps({'error': 'upstream_failed'}) + '\n\n'
        yield 'data: [DONE]\n\n'

    return Response(
        generate(),
        mimetype='text/event-stream',
        headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'},
    )


if __name__ == '__main__':
    app.run(debug=True, threaded=True)
  • Messages are assembled server-side. The browser sends a message and a list of past turns; the system prompt is never client-controlled.

  • sanitize_history is not optional. Without it, a caller can post {"role": "system"} in the history array and rewrite your assistant's instructions.

  • X-Accel-Buffering: no tells nginx and similar proxies not to buffer the response, which is what keeps the stream feeling live.

Step 3 — The Frontend

One template, no build step. It keeps the conversation in a local array and sends the whole thing with every request, which keeps the server completely stateless:

<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>Flask AI Chat</title>
<style>
  body { font-family: system-ui, sans-serif; max-width: 680px; margin: 40px auto; padding: 0 16px; }
  #log { border: 1px solid #ddd; border-radius: 10px; padding: 14px; min-height: 220px; line-height: 1.5; }
  form { display: flex; gap: 8px; margin-top: 12px; }
  input { flex: 1; padding: 10px; border: 1px solid #ccc; border-radius: 8px; }
  button { padding: 10px 18px; border: 0; border-radius: 8px; background: #0a58ca; color: #fff; cursor: pointer; }
  button:disabled { opacity: 0.5; cursor: default; }
</style>
</head>
<body>
<h1>Flask AI Chat</h1>
<div id='log'></div>
<form id='form'>
  <input id='msg' autocomplete='off' placeholder='Ask anything...'>
  <button id='send'>Send</button>
</form>

<script>
const log = document.getElementById('log');
const form = document.getElementById('form');
const input = document.getElementById('msg');
const send = document.getElementById('send');
const turns = [];

function addLine(text) {
  const line = document.createElement('div');
  line.textContent = text;
  log.appendChild(line);
  log.scrollTop = log.scrollHeight;
  return line;
}

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const text = input.value.trim();
  if (!text) return;

  input.value = '';
  send.disabled = true;
  addLine('You: ' + text);
  const aiLine = addLine('AI: ');

  let reply = '';
  try {
    const res = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message: text, history: turns })
    });
    if (!res.ok) throw new Error('HTTP ' + res.status);

    const reader = res.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { value, done } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });

      const events = buffer.split('\n\n');
      buffer = events.pop();

      for (const event of events) {
        if (!event.startsWith('data: ')) continue;
        const payload = event.slice(6);
        if (payload === '[DONE]') continue;
        const parsed = JSON.parse(payload);
        if (parsed.error) throw new Error(parsed.error);
        reply += parsed.delta;
        aiLine.textContent = 'AI: ' + reply;
        log.scrollTop = log.scrollHeight;
      }
    }

    turns.push({ role: 'user', content: text });
    turns.push({ role: 'assistant', content: reply });
  } catch (err) {
    aiLine.textContent = 'AI: [error] ' + err.message;
  } finally {
    send.disabled = false;
    input.focus();
  }
});
</script>
</body>
</html>

Because history lives in the browser, a refresh clears the chat. That is usually what you want for a prototype, and it is a short hop to storing turns server-side against a user id once you add accounts.

Step 4 — Run It and Smoke-Test It

flask --app app run --debug

# in a second terminal, verify streaming without a browser:
curl -N -X POST http://127.0.0.1:5000/api/chat \
  -H 'Content-Type: application/json' \
  -d '{"message":"Explain Flask request contexts in two sentences.","history":[]}'

You should see data: {...} chunks arriving one after another, ending with data: [DONE]. If everything shows up at once, buffering is the culprit — check the WSGI server and anything sitting in front of it. Then open http://127.0.0.1:5000 and ask a follow-up question to confirm memory works.

Step 5 — Five Things to Fix Before You Ship

  • Never send the key to the browser. Every request funnels through your route; the client only ever sees your own domain.

  • Run a threaded WSGI server. A streaming response holds a worker for the life of the connection, so gunicorn -w 2 --threads 8 app:app handles far more simultaneous chats than extra workers with a single thread each.

  • Turn off proxy buffering. On nginx, set proxy_buffering off; on the chat location. Without it, the entire answer arrives in one lump and you have paid for streaming and received none of it.

  • Cap the input. Reject messages beyond a few thousand characters and keep MAX_TURNS low. One user pasting a novel becomes your largest bill of the month.

  • Rate limit the route. Flask-Limiter per IP or session is a few lines, and a chat endpoint is the easiest thing in your app to hammer.

flash or pro for the chat route?

ModelUse it forTradeoff
deepseek-v4-flashThe default for chat UIs — quick first tokens, everyday Q&A, summarization, small code editsWeaker on long multi-step reasoning chains
deepseek-v4-proDebugging sessions with many steps, reviewing a whole file, answers where being wrong costs more than being slowSlower to respond than flash and priced higher

Cost control on a chat route is mostly about what you re-send on every turn. The system prompt and the older turns travel with every single request, so a stable, byte-identical system prompt sitting first in the message list is your biggest lever — providers that support prompt caching bill repeated prefixes at a lower rate, and reordering the prompt or tweaking it per request throws that away. Off-peak usage costs less than peak, which matters if you batch jobs like summarizing a backlog of tickets. And since pro costs more than flash, start every conversation on flash and escalate only the requests that fail a check or that the user explicitly pushes harder.

Current rates are listed at aicreditsapi.com/pricing.

The cheapest token is the one you never send twice: keep your system prompt first and unchanged across requests so cached prefixes keep hitting.

Frequently Asked Questions

Do I need a Chinese phone number or bank account to use DeepSeek models?

No. AiCredits is an OpenAI-compatible gateway for DeepSeek models that you pay for with an international card or PayPal, so the code above works as written — the only difference from any other provider is the base_url.

Can I use the official OpenAI Python SDK?

Yes. Point base_url at https://api.aicreditsapi.com/v1 and keep calling client.chat.completions.create. Swapping providers later stays a one-line change, which is the whole reason to use the SDK instead of raw HTTP.

Why does my stream stall after a few tokens?

It is almost always buffering somewhere: nginx proxy_buffering, a CDN in front of the app, or a short server timeout. Check those three before you suspect the model, and keep threaded=True on the Flask dev server.

Should I store conversation history in a database?

Once you have real users, yes. Client-supplied history is convenient but untrusted — sanitize_history exists above precisely because a caller can send any role it likes. Validate the shape server-side and key stored turns to a user id.

How do I switch to deepseek-v4-pro?

Change the model string in the create call. Since pro costs more than flash, the common pattern is to keep a per-request flag and escalate only when flash returns something your own checks reject.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×