Skip to main content

Integrating AI with Flask: Build Fun AI-Powered Web Apps with Python

· 8 min read
Jesus Paz
Python Expert & AI Indie Hacker

🚀 Turn Your Flask Apps into AI-Powered Wonders with Python! 🚀

Have you ever wanted to create a website that can chat with users, answer questions, or even help with homework? With Flask and the OpenAI API, you can make your web apps smart and interactive! This beginner-friendly guide will show you how to add AI magic to your Flask projects. Let’s get started and build something awesome together!

📚 What You’ll Learn

  • How to set up Flask for building web apps
  • How to connect OpenAI’s AI to your Flask app
  • How to create cool AI features like chatbots and news summaries
  • How to integrate your AI app with messaging apps like Slack and WhatsApp

🤔 Why Integrate AI with Flask?

Flask is a simple and powerful web framework for Python that makes it easy to build websites. When you add AI using the OpenAI API, your apps can do smart things like:

  • Chat with users like a real person
  • Generate creative stories or emails
  • Answer questions instantly
  • Summarize news so you stay informed
  • Respond to messages on Slack or WhatsApp automatically

With Flask and AI, your web apps can become your new smart assistants!

🛠️ Step 1: Setting Up Flask

First, let’s get Flask ready. Follow these easy steps:

1. Install Flask

Open your terminal or command prompt and type:

pip install flask

2. Create a Basic Flask App

Create a file named app.py and add this code:

from flask import Flask, render_template, request

app = Flask(__name__)

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

if __name__ == '__main__':
app.run(debug=True)

This code sets up a simple web page. When you run the app, it will show a page at http://localhost:5000/.

🔗 Step 2: Connecting OpenAI API to Flask

Now, let’s add AI to our Flask app!

1. Install OpenAI Package

In your terminal, type:

pip install openai

2. Secure Your OpenAI API Key

Your OpenAI API key is like a secret password. Keep it safe! Use environment variables to store it.

import openai
import os

openai.api_key = os.getenv("OPENAI_API_KEY")

Don’t have an API key yet? Get one from the OpenAI API Key Page.

3. Update app.py to Use OpenAI

Modify your app.py to handle user input and get AI responses:

import openai
from flask import Flask, render_template, request
import os

app = Flask(__name__)

# Load your API key from an environment variable
openai.api_key = os.getenv("OPENAI_API_KEY")

@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
user_input = request.form['query']
ai_response = get_ai_response(user_input)
return render_template('index.html', query=user_input, response=ai_response)
return render_template('index.html')

def get_ai_response(query):
response = openai.Completion.create(
model="gpt-4o-mini", # A cost-effective AI model
prompt=query,
max_tokens=100
)
return response.choices[0].text.strip()

if __name__ == '__main__':
app.run(debug=True)

This code takes what you type on the website, sends it to OpenAI, and shows the AI’s reply.

🎨 Step 3: Creating the Front-End

Let’s make the web page where you can talk to the AI!

1. Create index.html

Make a folder named templates in the same directory as app.py. Inside templates, create index.html with this content:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI with Flask</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
input, button { padding: 10px; font-size: 16px; }
.response { margin-top: 20px; }
</style>
</head>
<body>
<h1>Ask the AI!</h1>
<form method="POST">
<input type="text" name="query" id="query" placeholder="Type your question here" required>
<button type="submit">Ask</button>
</form>

{% if query and response %}
<div class="response">
<h2>Your Question:</h2>
<p>{{ query }}</p>

<h2>AI Response:</h2>
<p>{{ response }}</p>
</div>
{% endif %}
</body>
</html>

This page has a simple form where you can type a question and see the AI’s answer.

🤖 Step 4: Adding Cool AI Features

Let’s make our app even more fun by adding some cool features!

1. Chatbot Integration

Make your AI respond like a friendly chatbot.

@app.route('/chat', methods=['GET', 'POST'])
def chat():
if request.method == 'POST':
user_message = request.form['message']
ai_reply = get_ai_response(user_message)
return render_template('chat.html', message=user_message, reply=ai_reply)
return render_template('chat.html')

Create chat.html in the templates folder:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chatbot</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
input, button { padding: 10px; font-size: 16px; }
.conversation { margin-top: 20px; }
</style>
</head>
<body>
<h1>Chat with AI!</h1>
<form method="POST">
<input type="text" name="message" id="message" placeholder="Say something..." required>
<button type="submit">Send</button>
</form>

{% if message and reply %}
<div class="conversation">
<h2>You:</h2>
<p>{{ message }}</p>

<h2>AI:</h2>
<p>{{ reply }}</p>
</div>
{% endif %}
</body>
</html>

2. Daily News Summaries

Get quick summaries of today’s news.

@app.route('/news', methods=['GET', 'POST'])
def news():
if request.method == 'POST':
news_text = request.form['news']
summary = summarize_news(news_text)
return render_template('news.html', news=news_text, summary=summary)
return render_template('news.html')

def summarize_news(news):
response = openai.Completion.create(
model="gpt-4o-mini",
prompt=f"Summarize these news articles: {news}",
max_tokens=150
)
return response.choices[0].text.strip()

Create news.html in the templates folder:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Daily News Summary</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
textarea, button { padding: 10px; font-size: 16px; }
.summary { margin-top: 20px; }
</style>
</head>
<body>
<h1>Get Today's News Summary!</h1>
<form method="POST">
<textarea name="news" id="news" rows="5" cols="50" placeholder="Paste news articles here..." required></textarea><br>
<button type="submit">Summarize</button>
</form>

{% if news and summary %}
<div class="summary">
<h2>Original News:</h2>
<p>{{ news }}</p>

<h2>Summary:</h2>
<p>{{ summary }}</p>
</div>
{% endif %}
</body>
</html>

3. Integrate with Slack and WhatsApp

Make your AI respond to messages on Slack or WhatsApp automatically!

🔧 Slack Integration

  1. Create a Slack App and get an API token.

  2. Install Slack SDK:

    pip install slack_sdk
  3. Update app.py for Slack:

    from slack_sdk import WebClient
    from slack_sdk.errors import SlackApiError

    slack_token = os.getenv("SLACK_API_TOKEN")
    client = WebClient(token=slack_token)

    @app.route('/slack', methods=['POST'])
    def slack_message():
    data = request.form
    user_message = data.get('text')
    ai_reply = get_ai_response(user_message)
    try:
    response = client.chat_postMessage(
    channel='#general',
    text=ai_reply
    )
    except SlackApiError as e:
    print(f"Error sending message: {e.response['error']}")
    return '', 200

💬 WhatsApp Integration with Twilio

  1. Sign up for Twilio and get a WhatsApp number.

  2. Install Twilio SDK:

    pip install twilio
  3. Update app.py for WhatsApp:

    from twilio.rest import Client

    account_sid = os.getenv("TWILIO_ACCOUNT_SID")
    auth_token = os.getenv("TWILIO_AUTH_TOKEN")
    twilio_client = Client(account_sid, auth_token)

    @app.route('/whatsapp', methods=['POST'])
    def whatsapp_message():
    incoming_msg = request.form.get('Body')
    ai_reply = get_ai_response(incoming_msg)
    message = twilio_client.messages.create(
    body=ai_reply,
    from_='whatsapp:+14155238886', # Your Twilio WhatsApp number
    to='whatsapp:+1234567890' # User's WhatsApp number
    )
    return '', 200

🛡️ Step 5: Best Practices

To keep your AI app running smoothly and safely, follow these tips:

  • Limit API Requests: Prevent high costs by limiting how often your app can call the OpenAI API. Learn more in our OpenAI API Best Practices for Python guide.
  • Choose the Right Model: Use GPT-4o mini for a balance between cost and performance.
  • Protect Your API Key: Always store your API key securely using environment variables or a secrets manager. Check out our How to Code AI with OpenAI API post for details.
  • Monitor Token Usage: Keep track of how many tokens your app uses to stay within budget. Our OpenAI API Best Practices for Python guide can help.

Frequently Asked Questions (FAQs)

Q1: What can I build by integrating AI with Flask?

A: You can create chatbots, automatic email responders, news summarizers, and even smart assistants that respond on Slack or WhatsApp. Check out our Using AI to Automate Tasks with Python guide for more ideas!

Q2: How do I keep my API costs low?

A: Use cost-effective models, limit your API requests, and monitor your usage. Our OpenAI API Best Practices for Python article has all the tips you need.

Q3: Can I make my AI respond to multiple platforms?

A: Yes! You can integrate your AI with platforms like Slack and WhatsApp to respond to messages automatically. Learn how in this guide!

Q4: How do I make my AI smarter for specific tasks?

A: Fine-tune your AI models to better handle your specific needs. Check out our How to Fine-Tune OpenAI Models with Python post for a step-by-step guide.

Q5: What if I'm working alone on my projects?

A: Solo developers can optimize their workflow by automating repetitive tasks with AI. Get more tips in our Optimize Solo Developer Workflow article.

🎉 Conclusion

Integrating AI with Flask lets you build smart, interactive web apps that can chat, answer questions, and much more. By following this simple guide, you can create your own AI-powered projects and make your web apps truly amazing. Remember to keep your API key safe, choose the right AI models, and monitor your usage to keep everything running smoothly.

Ready to create something awesome? Dive into our other tutorials like Using AI to Automate Tasks with Python and OpenAI API Best Practices for Python to keep learning and building!