Enhancing Code with AI: Building a FastAPI Web App using OpenAI’s Chat Completion API

Amro Ghoneim
4 min readJan 19, 2024

--

Introduction

In today’s fast-paced tech world, developers are always seeking tools to increase their efficiency and improve their code. OpenAI’s Chat Completion API offers a remarkable opportunity to achieve just that. Following our previous article on using the Chat Completion API in Python, we now dive into creating a web application using FastAPI. This app will not only interact with the Chat Completion API but also provide recommendations on enhancing given code snippets.

Understanding FastAPI

FastAPI is a modern, fast, web framework for building APIs with Python. Known for its simplicity and performance, FastAPI is the perfect choice for our application. It supports asynchronous request handling and is built on standard Python type hints, ensuring efficient and error-free code.

Setting Up the FastAPI Project:

To begin, set up a new FastAPI project. Install FastAPI and Uvicorn, an ASGI server, using pip:

pip install fastapi uvicorn

Create a new Python file, main.py, and import FastAPI:

from fastapi import FastAPI 
app = FastAPI()

Integrating OpenAI’s Chat Completion API

The core of our application is the integration with OpenAI’s Chat Completion API. First, ensure you have the OpenAI Python library installed:

pip install openai

In main.py, import the OpenAI library and initialize it with your API key:

import openai

openai.api_key = 'your-api-key'

Creating the Endpoint

Develop an endpoint in your FastAPI app to receive code snippets and interact with the Chat Completion API. This endpoint will take a code snippet as input, send it to the API, and receive recommendations for enhancement.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

class CodeSnippet(BaseModel):
code: str

@app.post("/enhance-code/")
async def enhance_code(snippet: CodeSnippet):
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": f"Enhance this code: {snippet.code}"}
]
)
return response.choices[0].message['content']
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))

In this endpoint, the CodeSnippet class defines the structure of the input, and the /enhance-code/ route handles the POST request to enhance the provided code.

Running the Application

Run the application using Uvicorn:

uvicorn main:app --reload

This command starts the FastAPI application with hot reload enabled, making it easier to develop and test changes.

Testing the Application

To test the application, use tools like cURL, Postman, or the built-in FastAPI documentation at http://127.0.0.1:8000/docs. Send a POST request to /enhance-code/ with a JSON payload containing the code snippet.

Adding a Docker Integration

Docker offers a convenient way to containerize and deploy applications, ensuring consistency across different environments. Integrating Docker into our FastAPI application will simplify deployment and scaling. Here’s how to Dockerize the FastAPI app.

Creating the Dockerfile

First, create a Dockerfile in the root directory of your project. This file contains instructions for building the Docker image of your application. Add the following content to your Dockerfile:

# Use an official Python runtime as a parent image
FROM python:3.9-slim

# Set the working directory in the container
WORKDIR /usr/src/app

# Copy the current directory contents into the container at /usr/src/app
COPY . .

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Make port 8000 available to the world outside this container
EXPOSE 8000

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

This Dockerfile uses the official Python 3.9 slim image, sets up the working directory, copies the current directory’s contents into the container, installs the required packages, exposes port 8000, and specifies the command to run the FastAPI app.

Creating the requirements.txt File

Ensure you have a requirements.txt file listing all your Python dependencies. For our application, it should include FastAPI, Uvicorn, and OpenAI's Python library:

fastapi
uvicorn
openai

Building the Docker Image

In the terminal, navigate to your project directory and run the following command to build the Docker image:

docker build -t fastapi-chat-api .

This command builds a Docker image named fastapi-chat-api based on the instructions in your Dockerfile.

Running the Docker Container

After building the image, run your FastAPI application inside a Docker container:

docker run -d --name myapp -p 8000:8000 fastapi-chat-api

This command runs the Docker container in detached mode, maps port 8000 of the container to port 8000 of the host, and uses the image fastapi-chat-api.

Accessing the Application

With the Docker container running, access the FastAPI application by navigating to http://localhost:8000 or http://localhost:8000/docs for the interactive API documentation.

Conclusion

This article demonstrates the seamless integration of FastAPI, Docker, and OpenAI’s Chat Completion API to build a powerful and efficient web application. FastAPI’s ease of use and speed, combined with Docker’s containerization, creates a robust and scalable environment. The application’s core functionality, powered by OpenAI’s Chat Completion API, showcases the potential of AI in enhancing code snippets. This blend of technologies illustrates a modern approach to software development, where ease of deployment, AI-driven features, and high performance are harmoniously combined to deliver advanced solutions.

References

  1. FastAPI Documentation. https://fastapi.tiangolo.com/
  2. Docker Documentation. https://docs.docker.com/
  3. OpenAI API Documentation. https://beta.openai.com/docs/
  4. Python 3 Documentation. https://docs.python.org/3/
  5. Uvicorn Documentation. https://www.uvicorn.org/

--

--

Amro Ghoneim
Amro Ghoneim

Written by Amro Ghoneim

I like Coding, sports, music and a little bit of everything else.

No responses yet