This folder contains a small end-to-end example of how to connect a FastAPI backend to a Streamlit frontend using LangChain and LangServe.
This is the backend API server.
- It creates a FastAPI application.
- It loads environment variables from a
.envfile. - It configures OpenAI and LangChain credentials.
- It exposes LangChain routes with
langserve.add_routes(). - It defines a simple prompt that asks the model to write a poem about a topic in two paragraphs.
Two routes are added:
/llm/openai- exposes the rawChatOpenAImodel./llm/res/openai- exposes the prompt plus model chain that generates the final response.
When you run this file, the API starts on http://localhost:8800.
This is the frontend app built with Streamlit.
- It shows a small page title.
- It gives the user a text box to type a topic.
- It sends that topic to the FastAPI server using
requests.post(). - It displays the response returned by the model.
In simple terms, this file is the user interface, and app.py is the brain that talks to the language model.
- You start the FastAPI server from
app.py. - You start the Streamlit app from
client.py. - You type a topic such as
nature,friendship, ortechnology. - The Streamlit app sends the topic to the API.
- The API sends the topic to OpenAI through LangChain.
- The generated poem is returned and shown on the page.
Make sure the required packages are installed. The exact packages should be listed in requirement.txt.
You also need a .env file with your API keys, such as:
OPENAI_API_KEY=your_openai_key_here
LANGCHAIN_API_KEY=your_langchain_key_hereRun the backend from this folder:
python app.pyThe server should start on port 8800.
In another terminal, run:
streamlit run client.pyType a topic into the input box and wait for the poem response.
FastAPIis used to build the backend API.Streamlitis used to build the simple user interface.LangChainhelps structure the prompt and model call.LangServeturns the LangChain chain into API endpoints.requestsis used in the client to send data to the backend.
Developed by Asad Hussain.
- GitHub: @snackoverflowasad
- LinkedIn: Asad Hussain
- Portfolio: asadhussain.in