Simplifying Javascript API Integration with Lyzr Automata,Streamlit and OpenAI
Published: 2024-06-24 06:20:45

In today’s interconnected digital landscape, leveraging APIs (Application Programming Interfaces) is essential for seamless communication and data exchange between different software systems. As a JavaScript developer, mastering API integration techniques can significantly enhance your ability to build powerful and dynamic web applications. In this blog post, we’ll explore how you can harness the capabilities of Lyzr Automata to streamline the process of generating JavaScript code for API integration.

**Setting Up the Environment**
Imports:

```
Imports necessary libraries: os, 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
```
OpenAI API Key:

```
api = st.sidebar.text_input("Enter Your OPENAI API KEY HERE",type="password")
api = st.sidebar.text_input(“Enter Your OPENAI API KEY HERE”,type=”password”)
```
 Creates a text input field in the sidebar where users can enter their OpenAI API key securely (password mode).

OpenAI Model Setup :

```
if api:
    open_ai_text_completion_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")
```
if api: This block executes only if the user has entered an API key.
open_ai_text_completion_model = OpenAIModel(): Creates an instance of the OpenAIModel class with the provided API key and sets the model parameters like "gpt-4-turbo-preview" for the text generation model, temperature for randomness, and maximum token limit.
else: If no API key is provided, an error message is displayed in the sidebar using st.sidebar.error().

Defining the js_api_integration function:

```
def js_api_integration(technique, operation):
    js_agent = Agent(
        prompt_persona="You Are Expert Javascript API Integration Expert.",
        role="JS API Expert",
    )

    integration_task = Task(
        name="JS API Integration",
        output_type=OutputType.TEXT,
        input_type=InputType.TEXT,
        model=openai_model,
        agent=js_agent,
        log_output=True,
        instructions=f"""You Are Expert Javascript API Integration Expert.You are Expert in {operation} using {technique}.
        write a integration code for it. create separate function for integration and example usage also give instructions in bullet points.
        Include Import library commands.

        If step by step code guidance needed for API Integration then do that.follow below format:
        Step 1 :
        Step 2 :
        Step 3 :
        Instructions :
            """,
    )

    output = LinearSyncPipeline(
        name="Generate Integration Script",
        completion_message="Script Generated!",
        tasks=[
            integration_task
        ],
    ).run()
    return output[0]['task_output']
```
This function takes two arguments: technique (API interaction technique) and operation (specific API operation).
Creates an Agent object with a prompt persona describing the agent's expertise in Javascript API integration.
Defines a Task object specifying details of the script generation process:
Task name — “JS API Integration”
Output type — Text (generated script)
Input type — Text (user inputs)
Model to be used — openai_model (created earlier)
Agent to interact with the model — js_agent
Enables logging output for debugging.
Sets instructions for the model, including the user-provided technique and operation, and desired script structure with functions, examples, and bullet points for clarity.
Creates a LinearSyncPipeline object to execute the defined task.
Sets the pipeline name — “Generate Integration Script”
Completion message — “Script Generated!”
Defines the task list containing only the integration_task defined earlier.
Runs the pipeline and retrieves the generated script as output.
Returns the script text.

User Input and Script Generation:

```
technique = st.text_input("Specific API Interaction Techniques or Libraries", help="Use popular libraries like Axios or Fetch for API interaction.Research different techniques such as RESTful APIs or GraphQL for effective communication.",placeholder="Fetch API")
operation = st.text_input("Specific API Operation",placeholder="GET /users")

if st.button("Generate"):
    solution = js_api_integration(technique, operation)
    st.markdown(solution)
```
Creates text input fields for users to enter the technique and operation.
Provides help text and placeholder examples for user guidance.
Includes a button named “Generate”.
When the button is clicked:
Calls the js_api_integration function with the entered technique and operation.
Retrieves the generated script output.
Displays the generated script as markdown text in the app.

try it now: https://lyzr-api-integration-specialist.streamlit.app/

For more information explore the website: Lyzr