Automating API Documentation Generation with Lyzr and OpenAI
Published: 2024-06-24 06:41:51

In modern software development, maintaining comprehensive and up-to-date API documentation is crucial for developers, collaborators, and users. However, creating and maintaining such documentation manually is often labor-intensive, time-consuming, and prone to errors. This can lead to outdated, incomplete, or inconsistent documentation, which hampers development efficiency and user satisfaction.

**Challenges:**

Time-Consuming Process: Writing detailed API documentation manually takes significant time and effort, diverting developers from core development tasks.
Inconsistencies and Errors: Manual documentation is susceptible to human errors and inconsistencies, leading to potential misunderstandings or incorrect usage of the API.
Keeping Documentation Updated: APIs frequently change, and keeping documentation in sync with these changes manually can be difficult and often overlooked.
Lack of Standardization: Different developers may have varying styles and levels of detail in their documentation, leading to a lack of uniformity.

**Solution:** To address these challenges, we propose the development of an automated API Documentation Generator using Streamlit and OpenAI’s advanced language model. This tool will:

Automatically generate comprehensive, standardized API documentation from provided API function code.
Save developers time by automating the documentation process.
Ensure consistency and accuracy in the documentation.
Make it easy to keep documentation up-to-date with minimal effort.

**Objectives:**

Develop a user-friendly Streamlit application that allows users to input API function code.
Integrate OpenAI’s language model to analyze the code and generate detailed API documentation.
Ensure the generated documentation includes essential components such as endpoint descriptions, request headers, path parameters, query parameters, request bodies, response formats, and response codes.
Provide example requests and responses for common use cases to enhance the documentation’s utility.

**Setting Up the Environment**
**Imports:**

Imports necessary libraries: streamlit, libraries from lyzr_automata

```
pip install lyzr_automata streamlit
```

```
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

```
**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")
```

**api_documentation Function:**

```
def api_documentation(code_snippet):
    documentation_agent = Agent(
        prompt_persona="You Are Expert In API Documentation Creation.",
        role="API Documentation Expert",
    )

    documentation_task = Task(
        name="API Documentation converter",
        output_type=OutputType.TEXT,
        input_type=InputType.TEXT,
        model=openai_model,
        agent=documentation_agent,
        log_output=True,
        instructions=f"""You Are Expert In API Documentation Creation.
        Your Task Is to Create API Documentation For given API Endpoint and code.
        Follow Below Format and Instruction:
        DO NOT WRITE INTRODUCTION AND CONCLUSION.
        Endpoint: Specify the HTTP method (GET, POST, PUT, DELETE) and the full path of the endpoint (e.g., /api/v1/users).
        Request Headers: List required and optional headers, including content type and authorization.
        Path Parameters: Describe any parameters that are part of the URL path (e.g., /api/v1/users/user_id).Include the parameter name, data type, and a brief description.
        Query Parameters: List any query parameters accepted by the endpoint.Include the parameter name, data type, required/optional status, and a brief description.Provide example query strings.
        Request Body: For endpoints that accept a body (e.g., POST, PUT), describe the body format (JSON, XML).Provide a schema or example of the request body, including data types and required/optional fields.
        Response Format: Describe the response format (usually JSON).Provide a schema or example of the response body, including data types.
        Response Codes: List possible HTTP status codes returned by the endpoint.Provide a brief description for each status code, explaining what it means (e.g., 200 OK, 404 Not Found).
        Examples: Include example requests and responses for common use cases.Provide code snippets in various programming languages if possible.

        Code: {code_snippet}
        """,
    )

    output = LinearSyncPipeline(
        name="Generate Documentation",
        completion_message="Documentation Generated!",
        tasks=[
            documentation_task
        ],
    ).run()
    return output[0]['task_output']](url)
```
This function defines the logic for generating API documentation.

It creates an Agent object with a specific persona and role for documentation creation.
A Task object is created with details like name, input/output types, model to be used (from openai_model), the created agent, logging enabled, and instructions for the model.
The instructions provide a template and explanation for the expected documentation format, including sections like Endpoint, Request Headers, etc. It also includes the provided code snippet (code_snippet) as input for the model.
A LinearSyncPipeline object is created to run the defined task.
The function runs the pipeline and returns the output from the first task (the documentation generation task).
w
**User Code Input:**
```
code = st.text_area("Enter Code", height=300)
```
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("Generate"):
    solution = api_documentation(code)
    st.markdown(solution)
```
A button labeled “Generate” is created using st.button.
When the button is clicked, the following happens:
The api_documentation function is called with the user-entered code (code).
The returned documentation text (solution) is displayed as markdown using st.markdown.
Running the App
Finally, run the app using the following command in your terminal:

streamlit run app.py
try it now: https://lyzr-api-documentation.streamlit.app/

For more information explore the website: [Lyzr](https://lyzr.ai)