FastAPI

What is FastAPI?

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be easy to use and to provide a good developer experience, while also being one of the fastest frameworks available. FastAPI automatically generates interactive API documentation and is built on top of Starlette for the web parts and Pydantic for the data parts.

Getting Started

Prerequisites

Installation

You need to install the necessary libraries. You can do this using pip:

pip install fastapi uvicorn transformers pydantic

Note: Installing these modules manually via pip is just for demonstration purposes. We are going to create requirements.txt and install these modules via GitHub Action.

# Imports the pipeline function from the Hugging Face transformers library.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import pipeline
import uvicorn

Importing Necessary Libraries:

app = FastAPI()

Creating the FastAPI Application:

app = FastAPI() initializes the FastAPI application.

Initialize the Hugging Face question-answering pipeline

qa_pipeline = pipeline(“question-answering”, model=”distilbert-base-uncased-distilled-squad”)

# Initialize the Hugging Face question-answering pipeline
qa_pipeline = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad")

Initializing the Question-Answering Pipeline:

The qa_pipeline is created using the “distilbert-base-uncased-distilled-squad” model from Hugging Face’s model hub. This pipeline will handle the question-answering task.

Note: For a more detailed explanation on this topic, please check the Hugging Face

class ChatRequest(BaseModel):
    question: str
    context: str

class ChatResponse(BaseModel):
    answer: str

Defining Data Models:

@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
    try:
        result = qa_pipeline(question=request.question, context=request.context)
        return ChatResponse(answer=result['answer'])
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

Creating the /chat Endpoint:

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Running the Server:

← Previous Next →