DEV Community

harshit-lyzr
harshit-lyzr

Posted on

Streamline Your Code Documentation with Lyzr Code Comment Generator

In the world of software development, clear and concise code documentation is crucial. It helps in maintaining code, onboarding new team members, and ensuring that codebases remain understandable over time. Introducing the Lyzr Code Comment Generator, an innovative application designed to leverage the power of Lyzr Automata and Streamlit to automatically generate informative comments for your code.

What is Lyzr Code Comment Generator?
The Lyzr Code Comment Generator is an advanced tool that uses AI to analyze your code and generate detailed comments. This app is perfect for developers who want to improve their code readability and maintainability without spending hours on documentation.

Key Features
Automated Code Commenting: Automatically generate clear, concise, and informative comments for your code.
Insightful Explanations: Provides insights into the functionality and purpose of each section of code.
Best Practices: Promotes good coding practices by highlighting important features and techniques used in the code.
User-Friendly Interface: Built using Streamlit, the app offers an intuitive interface for easy use.
How It Works
Secure API Integration: Enter your OpenAI API key in the sidebar to access the GPT-4 Turbo model.
Input Code: Paste your code snippet into the provided text area.
Generate Comments: Click the ‘Convert’ button to generate comments for your code using Lyzr Automa.

Setting Up the Environment
Imports:

Imports necessary libraries: streamlit, libraries from lyzr_automata

pip install lyzr_automata streamlit
Enter fullscreen mode Exit fullscreen mode
import streamlit as st
from lyzr_automata.ai_models.openai import OpenAIModel
from lyzr_automata import Agent,Task
from lyzr_automata.pipelines.linear_sync_pipeline import LinearSyncPipeline
from PIL import Image

Enter fullscreen mode Exit fullscreen mode

Sidebar Configuration
We create a sidebar for user inputs, including an API key input for accessing the OpenAI GPT-4 model. This ensures that the API key remains secure.

api = st.sidebar.text_input("Enter our OPENAI API KEY Here", type="password")
if api:
    openai_model = OpenAIModel(
        api_key=api,
        parameters={
            "model": "gpt-4-turbo-preview",
            "temperature": 0.2,
            "max_tokens": 1500,
        },
    )
else:
    st.sidebar.error("Please Enter Your OPENAI API KEY")
Enter fullscreen mode Exit fullscreen mode

api_documentation Function:

def code_commenter(code_snippet):
    code_comment_agent = Agent(
        prompt_persona="you are a seasoned software engineer with a wealth of experience in writing, reviewing, and improving code",
        role="Software Engineer",
    )

    code_comment_task = Task(
        name="Code Commenting Task",
        output_type=OutputType.TEXT,
        input_type=InputType.TEXT,
        model=openai_model,
        agent=code_comment_agent,
        log_output=True,
        instructions=f"""You are tasked with generating comments for a given piece of code. 
        Your comments should be clear, concise, and informative, providing insight into the functionality and purpose of each section of code. 
        You should strive to explain the logic behind the code, highlight any important features or techniques used, and offer suggestions for improvement if applicable. 
        Your goal is to help readers understand the code more easily and to promote good coding practices through your comments.

        Code: {code_snippet}
        """,
    )

    output = LinearSyncPipeline(
        name="Generate Comment",
        completion_message="Comment Generated!",
        tasks=[
            code_comment_task
        ],
    ).run()
    return output[0]['task_output']
Enter fullscreen mode Exit fullscreen mode

def code_commenter(code_snippet):: Defines a function named code_commenter that takes user-provided code as input.
code_comment_agent = Agent(...): Creates an Agent object defining the prompt persona and role for the AI model. Here, the persona is a "seasoned software engineer" with expertise in code review and improvement.
code_comment_task = Task(...): Creates a Task object specifying the code commenting task. This includes details like:
Task name: “Code Commenting Task”
Output and Input types (text)
The AI model to be used (openai_model)
The defined code_comment_agent
Instructions for the model:
Generate clear, concise, and informative comments for the code.
Explain the logic, highlight important features, and suggest improvements.
Promote good coding practices through comments.
The instructions also specify that the code will be provided as input (Code: {code_snippet}).
output = LinearSyncPipeline(...): Creates a LinearSyncPipeline object specifying:
Pipeline name: “Generate Comment”
Completion message: “Comment Generated!”
List of tasks to be executed: only the code_comment_task in this case.
output.run(): Executes the pipeline, triggering the code commenting task using the defined model and instructions.
return output[0]['task_output']: Retrieves the output of the first task (the code commenting task) from the output list and returns it. This likely contains the generated code comments.

User Code Input:

code = st.text_area("Enter Code", height=300)
Enter fullscreen mode Exit fullscreen mode

code = st.text_area creates a text area for users to enter their code snippet. It sets the height to 300 pixels.

Generate Button and Output Display:

if st.button("Convert"):
    solution = code_commenter(code)
    st.markdown(solution)
Enter fullscreen mode Exit fullscreen mode

Defines a button labeled “Convert”. Clicking the button calls the code_commenter function with the user-provided code and displays the returned comments using markdown formatting.
Running the App
Finally, run the app using the following command in your terminal:

streamlit run app.py
Enter fullscreen mode Exit fullscreen mode

try it now: https://lyzr-code-comment-generator.streamlit.app/

For more information explore the website: Lyzr

Top comments (0)