In this article we’ll see how to create an AI code generator using LangChain’s ChatPromptTemplate class and Streamlit for UI. What we are going to built is a UI with a dropdown to select the programming language and an area to state the coding problem. On the click of the "generate code" button, programming language and the problem are inserted as actual values in the prepared prompt template and sent to the model to get an appropriate response.
How the UI looks like
What we are going to built in the UI
- A dropdown to select the programming language
- An area to state the coding problem
- A display area where the generated code is displayed
Prompt templates used in the code are kept in the separate file prompt.py
code_system_prompt_template = """
You are an expert {language} programmer. Write code as per the given instructions. The code should be efficient, well-structured, and properly commented. Use appropriate variable names and follow best practices for coding in the specified programming language.
"""
code_human_prompt_template = """
***Instructions***: Write code to solve the following programming problem: {problem}.
Make sure to include any necessary imports and handle edge cases appropriately.
"""
codegenerator.py
In the code there is a function generate_code() that has two arguments-
- problem (str): The programming problem to solve.
- language (str): The programming language to use for the code generation.
This function is invoked from the streamlit code after selecting the programming language from the given option, stating the coding problem and clicking the button "Generate Code"
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain_ollama import ChatOllama
from prompt import code_system_prompt_template, code_human_prompt_template
import streamlit as st
# Define system and human message templates
system_message = SystemMessagePromptTemplate.from_template(code_system_prompt_template)
human_message = HumanMessagePromptTemplate.from_template(code_human_prompt_template)
def generate_code(problem: str, language: str) -> str:
# Create a ChatPromptTemplate object
prompt = ChatPromptTemplate.from_messages([system_message, human_message])
# Initialize the model
model = ChatOllama(model="llama3.1",
temperature=0.7)
# Format the prompt with the problem and language
formatted_prompt = prompt.format(problem=problem, language=language)
print(f"Formatted prompt: {formatted_prompt}")
# Generate the code using the model
response = model.invoke(formatted_prompt)
# Return the generated code
return response.content
# Streamlit app to demonstrate code generation
st.set_page_config(page_title="AI Code Generator", layout="centered")
st.title("🤖 Code Generator ")
st.markdown("Select **programming language** and state your coding problem to generate code!")
# Create a dropdown with a default value
option = st.selectbox(
'Choose your favorite programming language:',
('Python', 'JavaScript', 'Java', 'C++'),
index=0 # sets the default value to the first option
)
#print(f"Selected programming language: {option}")
problem = st.text_area("Enter the programming problem you want to solve:")
# Generate code when the button is clicked
if st.button("Generate Code"):
if problem.strip() == "":
st.warning("Please enter a programming problem to generate code.")
else:
with st.spinner("Generating code..."):
generated_code = generate_code(problem, option)
st.code(generated_code, language=option.lower())
You can run the code using the following command.
streamlit run codegenerator.py
If there is no error then you should see a message telling how to access your streamlit web app.
You can now view your Streamlit app in your browser. Local URL: http://localhost:8501
The prompt after the insertion of actual values looks like as given below-
Formatted prompt: System:
You are an expert Java programmer. Write code as per the given instructions. The code should be
efficient, well-structured, and properly commented. Use appropriate variable names and follow
best practices for coding in the specified programming language.
Human:
***Instructions***: Write code to solve the following programming problem: For given input array find contiguous array of size k whose sum is equal to given s
Input - [2,2,1,2,3]
s = 5
k = 3
Output- [2,2,1] [2,1,2]
s=4
k=2
Output - [2,2]
If no contiguous array found return "Not Present".
Make sure to include any necessary imports and handle edge cases appropriately.
That's all for this topic LangChain PromptTemplate + Streamlit - Code Generator Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-

No comments:
Post a Comment